@jbrowse/mobx-state-tree 6.5.2 → 6.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +33 -0
- package/dist/index.d.ts +151 -116
- package/dist/mobx-state-tree.cjs +416 -386
- package/dist/mobx-state-tree.cjs.map +1 -1
- package/dist/mobx-state-tree.mjs +413 -388
- package/dist/mobx-state-tree.mjs.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mobx-state-tree.mjs","sources":["../src/core/node/livelinessChecking.ts","../src/core/node/Hook.ts","../src/core/mst-operations.ts","../src/core/node/BaseNode.ts","../src/core/node/scalar-node.ts","../src/core/node/object-node.ts","../src/core/type/type.ts","../src/middlewares/create-action-tracking-middleware.ts","../src/middlewares/createActionTrackingMiddleware2.ts","../src/middlewares/on-action.ts","../src/core/action.ts","../src/core/actionContext.ts","../src/core/type/type-checker.ts","../src/core/node/identifier-cache.ts","../src/core/node/create-node.ts","../src/core/node/node-utils.ts","../src/utils.ts","../src/core/flow.ts","../src/core/json-patch.ts","../src/types/utility-types/snapshotProcessor.ts","../src/types/complex-types/collection-hooks.ts","../src/types/complex-types/map.ts","../src/types/complex-types/array.ts","../src/types/complex-types/model.ts","../src/types/primitives.ts","../src/types/utility-types/literal.ts","../src/types/utility-types/refinement.ts","../src/types/utility-types/enumeration.ts","../src/types/utility-types/union.ts","../src/types/utility-types/optional.ts","../src/types/utility-types/maybe.ts","../src/types/utility-types/late.ts","../src/types/utility-types/lazy.ts","../src/types/utility-types/frozen.ts","../src/types/utility-types/reference.ts","../src/types/utility-types/identifier.ts","../src/types/utility-types/custom.ts","../src/types/utility-types/resilient.ts","../src/types/index.ts"],"sourcesContent":["/**\n * Defines what MST should do when running into reads / writes to objects that have died.\n * - `\"warn\"`: Print a warning (default).\n * - `\"error\"`: Throw an exception.\n * - \"`ignore`\": Do nothing.\n */\nexport type LivelinessMode = \"warn\" | \"error\" | \"ignore\"\n\nlet livelinessChecking: LivelinessMode = \"warn\"\n\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 */\nexport function setLivelinessChecking(mode: LivelinessMode) {\n livelinessChecking = mode\n}\n\n/**\n * Returns the current liveliness checking mode.\n *\n * @returns `\"warn\"`, `\"error\"` or `\"ignore\"`\n */\nexport function getLivelinessChecking(): LivelinessMode {\n return livelinessChecking\n}\n\n/**\n * @deprecated use LivelinessMode instead\n * @hidden\n */\nexport type LivelynessMode = LivelinessMode\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 */\nexport function setLivelynessChecking(mode: LivelinessMode) {\n setLivelinessChecking(mode)\n}\n","/**\n * @hidden\n */\nexport enum Hook {\n afterCreate = \"afterCreate\",\n afterAttach = \"afterAttach\",\n afterCreationFinalization = \"afterCreationFinalization\",\n beforeDetach = \"beforeDetach\",\n beforeDestroy = \"beforeDestroy\"\n}\n\nexport interface IHooks {\n [Hook.afterCreate]?: () => void\n [Hook.afterAttach]?: () => void\n [Hook.beforeDetach]?: () => void\n [Hook.beforeDestroy]?: () => void\n}\n\nexport type IHooksGetter<T> = (self: T) => IHooks\n","import { isComputedProp, isObservableProp } from \"mobx\"\n\nimport {\n EMPTY_OBJECT,\n InvalidReferenceError,\n asArray,\n assertArg,\n assertIsFunction,\n assertIsNumber,\n assertIsStateTreeNode,\n assertIsString,\n assertIsType,\n assertIsValidIdentifier,\n fail,\n freeze,\n getRelativePathBetweenNodes,\n getRunningActionContext,\n getStateTreeNode,\n isModelType,\n isStateTreeNode,\n normalizeIdentifier,\n resolveNodeByPath,\n splitJsonPath\n} from \"../internal.ts\"\n\nimport type {\n AnyObjectNode,\n IActionContext,\n IAnyComplexType,\n IAnyModelType,\n IAnyStateTreeNode,\n IAnyType,\n IDisposer,\n IJsonPatch,\n IStateTreeNode,\n IType,\n ReferenceIdentifier,\n TypeOfValue\n} from \"../internal.ts\"\n\n/** @hidden */\nexport type TypeOrStateTreeNodeToStateTreeNode<\n T extends IAnyType | IAnyStateTreeNode\n> = T extends IType<any, any, infer TT> ? TT & IStateTreeNode<T> : T\n\n/**\n * Returns the _actual_ type of the given tree node. (Or throws)\n *\n * @param object\n * @returns\n */\nexport function getType(object: IAnyStateTreeNode): IAnyComplexType {\n assertIsStateTreeNode(object, 1)\n\n return getStateTreeNode(object).type\n}\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 */\nexport function getChildType(\n object: IAnyStateTreeNode,\n propertyName?: string\n): IAnyType {\n assertIsStateTreeNode(object, 1)\n\n return getStateTreeNode(object).getChildType(propertyName)\n}\n\n/**\n * Registers a function that will be invoked for each mutation that is applied to the provided model instance, or to any of its children.\n * See [patches](https://github.com/mobxjs/mobx-state-tree#patches) for more details. onPatch events are emitted immediately and will not await the end of a transaction.\n * Patches can be used to deeply observe a model tree.\n *\n * @param target the model instance from which to receive patches\n * @param callback the callback that is invoked for each patch. The reversePatch is a patch that would actually undo the emitted patch\n * @returns function to remove the listener\n */\nexport function onPatch(\n target: IAnyStateTreeNode,\n callback: (patch: IJsonPatch, reversePatch: IJsonPatch) => void\n): IDisposer {\n // check all arguments\n assertIsStateTreeNode(target, 1)\n assertIsFunction(callback, 2)\n\n return getStateTreeNode(target).onPatch(callback)\n}\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 */\nexport function onSnapshot<S>(\n target: IStateTreeNode<IType<any, S, any>>,\n callback: (snapshot: S) => void\n): IDisposer {\n // check all arguments\n assertIsStateTreeNode(target, 1)\n assertIsFunction(callback, 2)\n\n return getStateTreeNode(target).onSnapshot(callback)\n}\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 */\nexport function applyPatch(\n target: IAnyStateTreeNode,\n patch: IJsonPatch | ReadonlyArray<IJsonPatch>\n): void {\n // check all arguments\n assertIsStateTreeNode(target, 1)\n assertArg(patch, p => typeof p === \"object\", \"object or array\", 2)\n\n getStateTreeNode(target).applyPatches(asArray(patch))\n}\n\nexport interface IPatchRecorder {\n patches: ReadonlyArray<IJsonPatch>\n inversePatches: ReadonlyArray<IJsonPatch>\n reversedInversePatches: ReadonlyArray<IJsonPatch>\n readonly recording: boolean\n stop(): void\n resume(): void\n replay(target?: IAnyStateTreeNode): void\n undo(target?: IAnyStateTreeNode): void\n}\n\n/**\n * Small abstraction around `onPatch` and `applyPatch`, attaches a patch listener to a tree and records all the patches.\n * Returns a recorder object with the following signature:\n *\n * Example:\n * ```ts\n * export interface IPatchRecorder {\n * // the recorded patches\n * patches: IJsonPatch[]\n * // the inverse of the recorded patches\n * inversePatches: IJsonPatch[]\n * // true if currently recording\n * recording: boolean\n * // stop recording patches\n * stop(): void\n * // resume recording patches\n * resume(): void\n * // apply all the recorded patches on the given target (the original subject if omitted)\n * replay(target?: IAnyStateTreeNode): void\n * // reverse apply the recorded patches on the given target (the original subject if omitted)\n * // stops the recorder if not already stopped\n * undo(): void\n * }\n * ```\n *\n * The optional filter function allows to skip recording certain patches.\n *\n * @param subject\n * @param filter\n * @returns\n */\nexport function recordPatches(\n subject: IAnyStateTreeNode,\n filter?: (\n patch: IJsonPatch,\n inversePatch: IJsonPatch,\n actionContext: IActionContext | undefined\n ) => boolean\n): IPatchRecorder {\n // check all arguments\n assertIsStateTreeNode(subject, 1)\n\n interface IPatches {\n patches: IJsonPatch[]\n reversedInversePatches: IJsonPatch[]\n inversePatches: IJsonPatch[]\n }\n\n const data: Pick<IPatches, \"patches\" | \"inversePatches\"> = {\n patches: [],\n inversePatches: []\n }\n\n // we will generate the immutable copy of patches on demand for public consumption\n const publicData: { [K in keyof IPatches]?: IPatches[K] | undefined } = {}\n\n let disposer: IDisposer | undefined\n\n const recorder: IPatchRecorder = {\n get recording() {\n return !!disposer\n },\n get patches() {\n if (!publicData.patches) {\n publicData.patches = data.patches.slice()\n }\n return publicData.patches\n },\n get reversedInversePatches() {\n if (!publicData.reversedInversePatches) {\n publicData.reversedInversePatches = data.inversePatches\n .slice()\n .reverse()\n }\n return publicData.reversedInversePatches\n },\n get inversePatches() {\n if (!publicData.inversePatches) {\n publicData.inversePatches = data.inversePatches.slice()\n }\n return publicData.inversePatches\n },\n stop() {\n if (disposer) {\n disposer()\n disposer = undefined\n }\n },\n resume() {\n if (disposer) {\n return\n }\n disposer = onPatch(subject, (patch, inversePatch) => {\n // skip patches that are asked to be filtered if there's a filter in place\n if (filter && !filter(patch, inversePatch, getRunningActionContext())) {\n return\n }\n data.patches.push(patch)\n data.inversePatches.push(inversePatch)\n\n // mark immutable public patches as dirty\n publicData.patches = undefined\n publicData.inversePatches = undefined\n publicData.reversedInversePatches = undefined\n })\n },\n replay(target?: IAnyStateTreeNode) {\n applyPatch(target || subject, data.patches)\n },\n undo(target?: IAnyStateTreeNode) {\n applyPatch(target || subject, data.inversePatches.slice().reverse())\n }\n }\n\n recorder.resume()\n return recorder\n}\n\n/**\n * The inverse of `unprotect`.\n *\n * @param target\n */\nexport function protect(target: IAnyStateTreeNode): void {\n // check all arguments\n assertIsStateTreeNode(target, 1)\n\n const node = getStateTreeNode(target)\n if (!node.isRoot) {\n throw fail(\"`protect` can only be invoked on root nodes\")\n }\n node.isProtectionEnabled = true\n}\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 */\nexport function unprotect(target: IAnyStateTreeNode): void {\n // check all arguments\n assertIsStateTreeNode(target, 1)\n\n const node = getStateTreeNode(target)\n if (!node.isRoot) {\n throw fail(\"`unprotect` can only be invoked on root nodes\")\n }\n node.isProtectionEnabled = false\n}\n\n/**\n * Returns true if the object is in protected mode, @see protect\n */\nexport function isProtected(target: IAnyStateTreeNode): boolean {\n // check all arguments\n assertIsStateTreeNode(target, 1)\n\n return getStateTreeNode(target).isProtected\n}\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 */\nexport function applySnapshot<C>(\n target: IStateTreeNode<IType<C, any, any>>,\n snapshot: C\n) {\n // check all arguments\n assertIsStateTreeNode(target, 1)\n\n return getStateTreeNode(target).applySnapshot(snapshot)\n}\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 */\nexport function getSnapshot<S>(\n target: IStateTreeNode<IType<any, S, any>>,\n applyPostProcess = true\n): S {\n // check all arguments\n assertIsStateTreeNode(target, 1)\n\n const node = getStateTreeNode(target)\n if (applyPostProcess) {\n return node.snapshot\n }\n\n return freeze(node.type.getSnapshot(node, false))\n}\n\nfunction findParentAtDepth(node: AnyObjectNode, depth: number) {\n let remaining = depth\n let parent: AnyObjectNode | null = node.parent\n while (parent) {\n if (--remaining === 0) {\n return parent\n }\n parent = parent.parent\n }\n return null\n}\n\nfunction findParentOfType(node: AnyObjectNode, type: IAnyComplexType) {\n let parent: AnyObjectNode | null = node.parent\n while (parent) {\n if (type.is(parent.storedValue)) {\n return parent\n }\n parent = parent.parent\n }\n return null\n}\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 */\nexport function hasParent(target: IAnyStateTreeNode, depth = 1): boolean {\n // check all arguments\n assertIsStateTreeNode(target, 1)\n assertIsNumber(depth, 2, 0)\n\n return findParentAtDepth(getStateTreeNode(target), depth) !== null\n}\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 */\nexport function getParent<IT extends IAnyStateTreeNode | IAnyComplexType>(\n target: IAnyStateTreeNode,\n depth = 1\n): TypeOrStateTreeNodeToStateTreeNode<IT> {\n // check all arguments\n assertIsStateTreeNode(target, 1)\n assertIsNumber(depth, 2, 0)\n\n const parent = findParentAtDepth(getStateTreeNode(target), depth)\n if (!parent) {\n throw fail(\n `Failed to find the parent of ${getStateTreeNode(target)} at depth ${depth}`\n )\n }\n return parent.storedValue\n}\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 */\nexport function hasParentOfType(\n target: IAnyStateTreeNode,\n type: IAnyComplexType\n): boolean {\n // check all arguments\n assertIsStateTreeNode(target, 1)\n assertIsType(type, 2)\n\n return findParentOfType(getStateTreeNode(target), type) !== null\n}\n\n/**\n * Returns the target's parent of a given type, or throws.\n *\n * @param target\n * @param type\n * @returns\n */\nexport function getParentOfType<IT extends IAnyComplexType>(\n target: IAnyStateTreeNode,\n type: IT\n): IT[\"Type\"] {\n // check all arguments\n assertIsStateTreeNode(target, 1)\n assertIsType(type, 2)\n\n const parent = findParentOfType(getStateTreeNode(target), type)\n if (!parent) {\n throw fail(\n `Failed to find the parent of ${getStateTreeNode(target)} of a given type`\n )\n }\n return parent.storedValue\n}\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 */\nexport function getRoot<IT extends IAnyComplexType | IAnyStateTreeNode>(\n target: IAnyStateTreeNode\n): TypeOrStateTreeNodeToStateTreeNode<IT> {\n // check all arguments\n assertIsStateTreeNode(target, 1)\n\n return getStateTreeNode(target).root.storedValue\n}\n\n/**\n * Returns the path of the given object in the model tree\n *\n * @param target\n * @returns\n */\nexport function getPath(target: IAnyStateTreeNode): string {\n // check all arguments\n assertIsStateTreeNode(target, 1)\n\n return getStateTreeNode(target).path\n}\n\n/**\n * Returns the path of the given object as unescaped string array.\n *\n * @param target\n * @returns\n */\nexport function getPathParts(target: IAnyStateTreeNode): string[] {\n // check all arguments\n assertIsStateTreeNode(target, 1)\n\n return splitJsonPath(getStateTreeNode(target).path)\n}\n\n/**\n * Returns true if the given object is the root of a model tree.\n *\n * @param target\n * @returns\n */\nexport function isRoot(target: IAnyStateTreeNode): boolean {\n // check all arguments\n assertIsStateTreeNode(target, 1)\n\n return getStateTreeNode(target).isRoot\n}\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 */\nexport function resolvePath<T = any>(\n target: IAnyStateTreeNode,\n path: string\n): T | undefined {\n // check all arguments\n assertIsStateTreeNode(target, 1)\n assertIsString(path, 2)\n\n const node = resolveNodeByPath(getStateTreeNode(target), path)\n return node ? node.value : undefined\n}\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 */\nexport function resolveIdentifier<IT extends IAnyModelType>(\n type: IT,\n target: IAnyStateTreeNode,\n identifier: ReferenceIdentifier\n): IT[\"Type\"] | undefined {\n // check all arguments\n assertIsType(type, 1)\n assertIsStateTreeNode(target, 2)\n assertIsValidIdentifier(identifier, 3)\n\n const node = getStateTreeNode(target).root.identifierCache!.resolve(\n type,\n normalizeIdentifier(identifier)\n )\n return node?.value\n}\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 */\nexport function getIdentifier(target: IAnyStateTreeNode): string | null {\n // check all arguments\n assertIsStateTreeNode(target, 1)\n\n return getStateTreeNode(target).identifier\n}\n\n/**\n * Resolves a reference getter to the referenced node, or `undefined` when the\n * reference is empty, dangling, or (with `checkIfAlive`) points at a dead node.\n * Backs both {@link tryReference} and {@link isValidReference}.\n */\nfunction resolveReference<N extends IAnyStateTreeNode>(\n getter: () => N | null | undefined,\n checkIfAlive: boolean\n): N | undefined {\n try {\n const node = getter()\n if (node === undefined || node === null) {\n return undefined\n }\n if (!isStateTreeNode(node)) {\n throw fail(\n \"The reference to be checked is not one of node, null or undefined\"\n )\n }\n return !checkIfAlive || isAlive(node) ? node : undefined\n } catch (e) {\n if (e instanceof InvalidReferenceError) {\n return undefined\n }\n throw e\n }\n}\n\n/**\n * Tests if a reference is valid (pointing to an existing node and optionally if alive) and returns such reference if the check passes,\n * else it returns undefined.\n *\n * @param getter Function to access the reference.\n * @param checkIfAlive true to also make sure the referenced node is alive (default), false to skip this check.\n * @returns\n */\nexport function tryReference<N extends IAnyStateTreeNode>(\n getter: () => N | null | undefined,\n checkIfAlive = true\n): N | undefined {\n return resolveReference(getter, checkIfAlive)\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 */\nexport function isValidReference<N extends IAnyStateTreeNode>(\n getter: () => N | null | undefined,\n checkIfAlive = true\n): boolean {\n return resolveReference(getter, checkIfAlive) !== undefined\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 */\nexport function tryResolve<T = any>(\n target: IAnyStateTreeNode,\n path: string\n): T | undefined {\n // check all arguments\n assertIsStateTreeNode(target, 1)\n assertIsString(path, 2)\n\n const node = resolveNodeByPath(getStateTreeNode(target), path, false)\n if (node === undefined) {\n 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/**\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 */\nexport function getRelativePath(\n base: IAnyStateTreeNode,\n target: IAnyStateTreeNode\n): string {\n // check all arguments\n assertIsStateTreeNode(base, 1)\n assertIsStateTreeNode(target, 2)\n\n return getRelativePathBetweenNodes(\n getStateTreeNode(base),\n getStateTreeNode(target)\n )\n}\n\n/**\n * Returns a deep copy of the given state tree node as new tree.\n * Shorthand for `snapshot(x) = getType(x).create(getSnapshot(x))`\n *\n * _Tip: clone will create a literal copy, including the same identifiers. To modify identifiers etc. during cloning, don't use clone but take a snapshot of the tree, modify it, and create new instance_\n *\n * @param source\n * @param keepEnvironment indicates whether the clone should inherit the same environment (`true`, the default), or not have an environment (`false`). If an object is passed in as second argument, that will act as the environment for the cloned tree.\n * @returns\n */\nexport function clone<T extends IAnyStateTreeNode>(\n source: T,\n keepEnvironment: boolean | object = true\n): T {\n // check all arguments\n assertIsStateTreeNode(source, 1)\n\n const node = getStateTreeNode(source)\n return node.type.create(\n node.snapshot,\n keepEnvironment === true\n ? node.root.environment\n : keepEnvironment === false\n ? undefined\n : keepEnvironment\n ) // it's an object or something else\n}\n\n/**\n * Removes a model element from the state tree, and let it live on as a new state tree\n */\nexport function detach<T extends IAnyStateTreeNode>(target: T): T {\n // check all arguments\n assertIsStateTreeNode(target, 1)\n\n getStateTreeNode(target).detach()\n return target\n}\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 */\nexport function destroy(target: IAnyStateTreeNode): void {\n // check all arguments\n assertIsStateTreeNode(target, 1)\n\n const node = getStateTreeNode(target)\n if (node.isRoot) {\n node.die()\n } else {\n node.parent!.removeChild(node.subpath)\n }\n}\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 */\nexport function isAlive(target: IAnyStateTreeNode): boolean {\n // check all arguments\n assertIsStateTreeNode(target, 1)\n\n return getStateTreeNode(target).observableIsAlive\n}\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 */\nexport function addDisposer(\n target: IAnyStateTreeNode,\n disposer: IDisposer\n): IDisposer {\n // check all arguments\n assertIsStateTreeNode(target, 1)\n assertIsFunction(disposer, 2)\n\n const node = getStateTreeNode(target)\n node.addDisposer(disposer)\n return disposer\n}\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 */\nexport function getEnv<T = any>(target: IAnyStateTreeNode): T {\n // check all arguments\n assertIsStateTreeNode(target, 1)\n\n const node = getStateTreeNode(target)\n const env = node.root.environment\n if (!env) {\n return EMPTY_OBJECT as T\n }\n return env\n}\n\n/**\n * Performs a depth first walk through a tree.\n */\nexport function walk(\n target: IAnyStateTreeNode,\n processor: (item: IAnyStateTreeNode) => void\n): void {\n // check all arguments\n assertIsStateTreeNode(target, 1)\n assertIsFunction(processor, 2)\n\n const node = getStateTreeNode(target)\n node.getChildren().forEach(child => {\n if (isStateTreeNode(child.storedValue)) {\n walk(child.storedValue, processor)\n }\n })\n processor(node.storedValue)\n}\n\nexport interface IModelReflectionPropertiesData {\n name: string\n properties: { [K: string]: IAnyType }\n}\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 */\nexport function getPropertyMembers(\n typeOrNode: IAnyModelType | IAnyStateTreeNode\n): IModelReflectionPropertiesData {\n let type: IAnyModelType\n\n if (isStateTreeNode(typeOrNode)) {\n type = getType(typeOrNode) as IAnyModelType\n } else {\n type = typeOrNode as IAnyModelType\n }\n\n assertArg(type, t => isModelType(t), \"model type or model instance\", 1)\n\n return {\n name: type.name,\n properties: { ...type.properties }\n }\n}\n\nexport interface IModelReflectionData extends IModelReflectionPropertiesData {\n actions: string[]\n views: string[]\n volatile: string[]\n flowActions: string[]\n}\n\n/**\n * Returns a reflection of the model node, including name, properties, views, volatile state,\n * and actions. `flowActions` is also provided as a separate array of names for any action that\n * came from a flow generator as well.\n *\n * In the case where a model has two actions: `doSomething` and `doSomethingWithFlow`, where\n * `doSomethingWithFlow` is a flow generator, the `actions` array will contain both actions,\n * i.e. [\"doSomething\", \"doSomethingWithFlow\"], and the `flowActions` array will contain only\n * the flow action, i.e. [\"doSomethingWithFlow\"].\n *\n * @param target\n * @returns\n */\nexport function getMembers(target: IAnyStateTreeNode): IModelReflectionData {\n const type = getStateTreeNode(target).type as unknown as IAnyModelType\n\n const reflected: IModelReflectionData = {\n ...getPropertyMembers(type),\n actions: [],\n volatile: [],\n views: [],\n flowActions: []\n }\n\n const props = Object.getOwnPropertyNames(target)\n props.forEach(key => {\n if (key in reflected.properties) {\n return\n }\n const descriptor = Object.getOwnPropertyDescriptor(target, key)!\n if (descriptor.get) {\n if (isComputedProp(target, key)) {\n reflected.views.push(key)\n } else {\n reflected.volatile.push(key)\n }\n return\n }\n const value = descriptor.value\n if (value?._isFlowAction === true) {\n reflected.flowActions.push(key)\n }\n if (value?._isMSTAction === true) {\n reflected.actions.push(key)\n } else if (isObservableProp(target, key)) {\n reflected.volatile.push(key)\n } else {\n reflected.views.push(key)\n }\n })\n return reflected\n}\n\nexport function cast<\n O extends string | number | boolean | null | undefined = never\n>(snapshotOrInstance: O): O\nexport function cast<O = never>(\n snapshotOrInstance:\n | TypeOfValue<O>[\"CreationType\"]\n | TypeOfValue<O>[\"SnapshotType\"]\n | TypeOfValue<O>[\"Type\"]\n): O\n/**\n * Casts a node snapshot or instance type to an instance type so it can be assigned to a type instance.\n * Note that this is just a cast for the type system, this is, it won't actually convert a snapshot to an instance,\n * but just fool typescript into thinking so.\n * Either way, casting when outside an assignation operation won't compile.\n *\n * Example:\n * ```ts\n * const ModelA = types.model({\n * n: types.number\n * }).actions(self => ({\n * setN(aNumber: number) {\n * self.n = aNumber\n * }\n * }))\n *\n * const ModelB = types.model({\n * innerModel: ModelA\n * }).actions(self => ({\n * someAction() {\n * // this will allow the compiler to assign a snapshot to the property\n * self.innerModel = cast({ a: 5 })\n * }\n * }))\n * ```\n *\n * @param snapshotOrInstance Snapshot or instance\n * @returns The same object cast as an instance\n */\nexport function cast(snapshotOrInstance: any): any {\n return snapshotOrInstance\n}\n\n/**\n * Casts a node instance type to a snapshot type so it can be assigned to a type snapshot (e.g. to be used inside a create call).\n * Note that this is just a cast for the type system, this is, it won't actually convert an instance to a snapshot,\n * but just fool typescript into thinking so.\n *\n * Example:\n * ```ts\n * const ModelA = types.model({\n * n: types.number\n * }).actions(self => ({\n * setN(aNumber: number) {\n * self.n = aNumber\n * }\n * }))\n *\n * const ModelB = types.model({\n * innerModel: ModelA\n * })\n *\n * const a = ModelA.create({ n: 5 });\n * // this will allow the compiler to use a model as if it were a snapshot\n * const b = ModelB.create({ innerModel: castToSnapshot(a)})\n * ```\n *\n * @param snapshotOrInstance Snapshot or instance\n * @returns The same object cast as an input (creation) snapshot\n */\nexport function castToSnapshot<I>(\n snapshotOrInstance: I\n): Extract<I, IAnyStateTreeNode> extends never\n ? I\n : TypeOfValue<I>[\"CreationType\"] {\n return snapshotOrInstance\n}\n\n/**\n * Casts a node instance type to a reference snapshot type so it can be assigned to a reference snapshot (e.g. to be used inside a create call).\n * Note that this is just a cast for the type system, this is, it won't actually convert an instance to a reference snapshot,\n * but just fool typescript into thinking so.\n *\n * Example:\n * ```ts\n * const ModelA = types.model({\n * id: types.identifier,\n * n: types.number\n * }).actions(self => ({\n * setN(aNumber: number) {\n * self.n = aNumber\n * }\n * }))\n *\n * const ModelB = types.model({\n * refA: types.reference(ModelA)\n * })\n *\n * const a = ModelA.create({ id: 'someId', n: 5 });\n * // this will allow the compiler to use a model as if it were a reference snapshot\n * const b = ModelB.create({ refA: castToReferenceSnapshot(a)})\n * ```\n *\n * @param instance Instance\n * @returns The same object cast as a reference snapshot (string or number)\n */\nexport function castToReferenceSnapshot<I>(\n instance: I\n): Extract<I, IAnyStateTreeNode> extends never ? I : ReferenceIdentifier {\n return instance as any\n}\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 */\nexport function getNodeId(target: IAnyStateTreeNode): number {\n assertIsStateTreeNode(target, 1)\n\n return getStateTreeNode(target).nodeId\n}\n","import { type IAtom, createAtom } from \"mobx\"\n\nimport {\n type AnyObjectNode,\n EventHandlers,\n Hook,\n type IAnyType,\n type IDisposer,\n NodeLifeCycle,\n devMode,\n escapeJsonPath,\n fail\n} from \"../../internal.ts\"\n\ntype HookSubscribers = {\n [Hook.afterAttach]: (node: AnyNode, hook: Hook) => void\n [Hook.afterCreate]: (node: AnyNode, hook: Hook) => void\n [Hook.afterCreationFinalization]: (node: AnyNode, hook: Hook) => void\n [Hook.beforeDestroy]: (node: AnyNode, hook: Hook) => void\n [Hook.beforeDetach]: (node: AnyNode, hook: Hook) => void\n}\n\n/**\n * @internal\n * @hidden\n */\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport abstract class BaseNode<C, S, T> {\n private _escapedSubpath?: string | undefined\n\n private _subpath!: string\n get subpath() {\n return this._subpath\n }\n\n private _subpathUponDeath?: string\n get subpathUponDeath() {\n return this._subpathUponDeath\n }\n\n private _pathUponDeath?: string\n protected get pathUponDeath() {\n return this._pathUponDeath\n }\n\n storedValue!: any // usually the same type as the value, but not always (such as with references)\n get value(): T {\n return (this.type as any).getValue(this)\n }\n\n private aliveAtom?: IAtom\n private _state = NodeLifeCycle.INITIALIZING\n get state() {\n return this._state\n }\n set state(val: NodeLifeCycle) {\n const wasAlive = this.isAlive\n this._state = val\n const isAlive = this.isAlive\n\n if (this.aliveAtom && wasAlive !== isAlive) {\n this.aliveAtom.reportChanged()\n }\n }\n\n private _hookSubscribers?: EventHandlers<HookSubscribers>\n\n protected abstract fireHook(name: Hook): void\n\n protected fireInternalHook(name: Hook) {\n if (this._hookSubscribers) {\n this._hookSubscribers.emit(name, this, name)\n }\n }\n\n registerHook<H extends Hook>(\n hook: H,\n hookHandler: HookSubscribers[H]\n ): IDisposer {\n if (!this._hookSubscribers) {\n this._hookSubscribers = new EventHandlers()\n }\n return this._hookSubscribers.register(hook, hookHandler)\n }\n\n private _parent!: AnyObjectNode | null\n get parent() {\n return this._parent\n }\n\n constructor(\n readonly type: IAnyType,\n parent: AnyObjectNode | null,\n subpath: string,\n public environment: any\n ) {\n this.baseSetParent(parent, subpath)\n }\n\n getReconciliationType() {\n return this.type\n }\n\n private pathAtom?: IAtom\n protected baseSetParent(parent: AnyObjectNode | null, subpath: string) {\n this._parent = parent\n this._subpath = subpath\n this._escapedSubpath = undefined // regenerate when needed\n if (this.pathAtom) {\n this.pathAtom.reportChanged()\n }\n }\n\n /*\n * Returns (escaped) path representation as string\n */\n get path(): string {\n return this.getEscapedPath(true)\n }\n\n protected getEscapedPath(reportObserved: boolean): string {\n if (reportObserved) {\n if (!this.pathAtom) {\n this.pathAtom = createAtom(`path`)\n }\n this.pathAtom.reportObserved()\n }\n if (!this.parent) {\n return \"\"\n }\n // regenerate escaped subpath if needed\n if (this._escapedSubpath === undefined) {\n this._escapedSubpath = !this._subpath ? \"\" : escapeJsonPath(this._subpath)\n }\n return `${this.parent.getEscapedPath(reportObserved)}/${this._escapedSubpath}`\n }\n\n get isRoot(): boolean {\n return this.parent === null\n }\n\n abstract get root(): AnyObjectNode\n\n abstract setParent(\n newParent: AnyObjectNode | null,\n subpath: string | null\n ): void\n\n abstract get snapshot(): S\n abstract getSnapshot(): S\n\n get isAlive() {\n return this.state !== NodeLifeCycle.DEAD\n }\n\n get isDetaching() {\n return this.state === NodeLifeCycle.DETACHING\n }\n\n get observableIsAlive() {\n if (!this.aliveAtom) {\n this.aliveAtom = createAtom(`alive`)\n }\n this.aliveAtom.reportObserved()\n return this.isAlive\n }\n\n abstract die(): void\n\n abstract finalizeCreation(): void\n\n protected baseFinalizeCreation(whenFinalized?: () => void) {\n if (devMode()) {\n if (!this.isAlive) {\n // istanbul ignore next\n throw fail(\n \"assertion failed: cannot finalize the creation of a node that is already dead\"\n )\n }\n }\n\n // goal: afterCreate hooks runs depth-first. After attach runs parent first, so on afterAttach the parent has completed already\n if (this.state === NodeLifeCycle.CREATED) {\n if (this.parent) {\n if (this.parent.state !== NodeLifeCycle.FINALIZED) {\n // parent not ready yet, postpone\n return\n }\n this.fireHook(Hook.afterAttach)\n }\n\n this.state = NodeLifeCycle.FINALIZED\n\n if (whenFinalized) {\n whenFinalized()\n }\n }\n }\n\n abstract finalizeDeath(): void\n\n protected baseFinalizeDeath() {\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 abstract aboutToDie(): void\n\n protected baseAboutToDie() {\n this.fireHook(Hook.beforeDestroy)\n }\n}\n\n/**\n * @internal\n * @hidden\n */\nexport type AnyNode = BaseNode<any, any, any>\n","import { action } from \"mobx\"\n\nimport {\n type AnyObjectNode,\n BaseNode,\n type Hook,\n NodeLifeCycle,\n type SimpleType,\n devMode,\n fail,\n freeze\n} from \"../../internal.ts\"\n\n/**\n * @internal\n * @hidden\n */\nexport class ScalarNode<C, S, T> extends BaseNode<C, S, T> {\n // note about hooks:\n // - afterCreate is not emmited in scalar nodes, since it would be emitted in the\n // constructor, before it can be subscribed by anybody\n // - afterCreationFinalization could be emitted, but there's no need for it right now\n // - beforeDetach is never emitted for scalar nodes, since they cannot be detached\n\n declare readonly type: SimpleType<C, S, T>\n\n constructor(\n simpleType: SimpleType<C, S, T>,\n parent: AnyObjectNode | null,\n subpath: string,\n environment: any,\n initialSnapshot: C\n ) {\n super(simpleType, parent, subpath, environment)\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\n // for scalar nodes there's no point in firing this event since it would fire on the constructor, before\n // anybody can actually register for/listen to it\n // this.fireHook(Hook.AfterCreate)\n\n this.finalizeCreation()\n }\n\n get root(): AnyObjectNode {\n // future optimization: store root ref in the node and maintain it\n if (!this.parent) {\n throw fail(`This scalar node is not part of a tree`)\n }\n return this.parent.root\n }\n\n setParent(newParent: AnyObjectNode, subpath: string): void {\n const parentChanged = this.parent !== newParent\n const 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(\"assertion failed: subpath expected\")\n }\n if (!newParent) {\n // istanbul ignore next\n throw fail(\"assertion failed: parent expected\")\n }\n if (parentChanged) {\n // istanbul ignore next\n throw fail(\"assertion failed: scalar nodes cannot change their parent\")\n }\n }\n\n this.environment = undefined // use parent's\n this.baseSetParent(this.parent, subpath)\n }\n\n get snapshot(): S {\n return freeze(this.getSnapshot())\n }\n\n getSnapshot(): S {\n return this.type.getSnapshot(this)\n }\n\n override toString(): string {\n const path = (this.isAlive ? this.path : this.pathUponDeath) || \"<root>\"\n return `${this.type.name}@${path}${this.isAlive ? \"\" : \" [dead]\"}`\n }\n\n die(): void {\n if (!this.isAlive || this.state === NodeLifeCycle.DETACHING) {\n return\n }\n this.aboutToDie()\n this.finalizeDeath()\n }\n\n finalizeCreation(): void {\n this.baseFinalizeCreation()\n }\n\n aboutToDie(): void {\n this.baseAboutToDie()\n }\n\n finalizeDeath(): void {\n this.baseFinalizeDeath()\n }\n\n protected fireHook(name: Hook): void {\n this.fireInternalHook(name)\n }\n}\nScalarNode.prototype.die = action(ScalarNode.prototype.die)\n","import {\n type IComputedValue,\n _allowStateChangesInsideComputed,\n action,\n computed,\n reaction\n} from \"mobx\"\n\nimport {\n BaseNode,\n type ComplexType,\n EMPTY_OBJECT,\n EventHandlers,\n Hook,\n IdentifierCache,\n NodeLifeCycle,\n addHiddenFinalProp,\n convertChildNodesToArray,\n createActionInvoker,\n devMode,\n escapeJsonPath,\n fail,\n freeze,\n getCurrentActionContext,\n getLivelinessChecking,\n getPath,\n normalizeIdentifier,\n resolveNodeByPathParts,\n splitJsonPath,\n splitPatch,\n toJSON,\n warnError,\n type AnyNode,\n type ArgumentTypes,\n type IAnyType,\n type IDisposer,\n type IJsonPatch,\n type IMiddleware,\n type IMiddlewareEvent,\n type IMiddlewareHandler,\n type IReversibleJsonPatch,\n type IStateTreeNode,\n type IType,\n type ReferenceIdentifier\n} from \"../../internal.ts\"\n\nlet nextNodeId = 1\n\nconst enum ObservableInstanceLifecycle {\n // the actual observable instance has not been created yet\n UNINITIALIZED,\n // the actual observable instance is being created\n CREATING,\n // the actual observable instance has been created\n CREATED\n}\n\nconst enum InternalEvents {\n Dispose = \"dispose\",\n Patch = \"patch\",\n Snapshot = \"snapshot\"\n}\n\n/**\n * @internal\n * @hidden\n */\nexport interface IChildNodesMap {\n [key: string]: AnyNode\n}\n\nconst snapshotReactionOptions = {\n onError(e: any) {\n throw e\n }\n}\n\n// keepAlive lets the snapshot computed memoize its value even with no observer,\n// so getSnapshot() stays referentially stable without an eager snapshot\n// reaction serializing the whole tree at create time. Shared: mobx only reads it.\nconst snapshotComputedOptions = { keepAlive: true }\n\ntype InternalEventHandlers<S> = {\n [InternalEvents.Dispose]: IDisposer\n [InternalEvents.Patch]: (patch: IJsonPatch, reversePatch: IJsonPatch) => void\n [InternalEvents.Snapshot]: (snapshot: S) => void\n}\n\n/**\n * @internal\n * @hidden\n */\nexport class ObjectNode<C, S, T> extends BaseNode<C, S, T> {\n declare readonly type: ComplexType<C, S, T>\n declare storedValue: T & IStateTreeNode<IType<C, S, T>>\n\n readonly nodeId = ++nextNodeId\n readonly identifierAttribute?: string | undefined\n readonly identifier: string | null // Identifier is always normalized to string, even if the identifier property isn't\n readonly unnormalizedIdentifier: ReferenceIdentifier | null\n\n identifierCache?: IdentifierCache\n isProtectionEnabled = true\n middlewares?: IMiddleware[]\n hasSnapshotPostProcessor = false\n\n private _applyPatches?: (patches: ReadonlyArray<IJsonPatch>) => void\n\n applyPatches(patches: ReadonlyArray<IJsonPatch>): void {\n this.createObservableInstanceIfNeeded()\n this._applyPatches!(patches)\n }\n\n private _applySnapshot?: (snapshot: C) => void\n\n applySnapshot(snapshot: C): void {\n this.createObservableInstanceIfNeeded()\n this._applySnapshot!(snapshot)\n }\n\n private _autoUnbox = true // unboxing is disabled when reading child nodes\n _isRunningAction = false // only relevant for root\n private _snapshotReactionDisposer?: IDisposer | undefined\n\n private _observableInstanceState = ObservableInstanceLifecycle.UNINITIALIZED\n private _childNodes: IChildNodesMap\n private _initialSnapshot: C\n private _cachedInitialSnapshot?: S\n private _cachedInitialSnapshotCreated = false\n private _snapshotComputed: IComputedValue<S>\n // whether _snapshotComputed has ever run — see createObservableInstance\n private _snapshotComputedEvaluated = false\n\n constructor(\n complexType: ComplexType<C, S, T>,\n parent: AnyObjectNode | null,\n subpath: string,\n environment: any,\n initialValue: C\n ) {\n super(complexType, parent, subpath, environment)\n // keepAlive: memoize the snapshot after the first read even with no\n // observer, so getSnapshot() is referentially stable (and reconcile-by-\n // snapshot works) without eagerly serializing the whole tree at create\n // time — the previous cost, driven by the eager root reaction below.\n this._snapshotComputed = computed<S>(() => {\n this._snapshotComputedEvaluated = true\n return freeze(this.getSnapshot())\n }, snapshotComputedOptions)\n\n this.unbox = this.unbox.bind(this)\n\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(\n this,\n this._initialSnapshot\n )\n\n // identifier can not be changed during lifecycle of a node\n // so we safely can read it from initial snapshot\n this.identifier = null\n this.unnormalizedIdentifier = null\n if (this.identifierAttribute && this._initialSnapshot) {\n let id = (this._initialSnapshot as any)[this.identifierAttribute]\n if (id === undefined) {\n // try with the actual node if not (for optional identifiers)\n const childNode = this._childNodes[this.identifierAttribute]\n if (childNode) {\n id = childNode.value\n }\n }\n\n if (typeof id !== \"string\" && typeof id !== \"number\") {\n throw fail(\n `Instance identifier '${this.identifierAttribute}' for type '${this.type.name}' must be a string or a number`\n )\n }\n\n // normalize internal identifier to string\n this.identifier = normalizeIdentifier(id)\n this.unnormalizedIdentifier = id\n }\n\n // addNodeToCache no-ops without an identifier attribute, and reaching the\n // root to ask it is a walk up the whole parent chain\n if (this.identifierAttribute) {\n const cache = parent ? parent.root.identifierCache : this.identifierCache\n cache!.addNodeToCache(this)\n }\n }\n\n createObservableInstanceIfNeeded(fireHooks = true): void {\n if (\n this._observableInstanceState ===\n ObservableInstanceLifecycle.UNINITIALIZED\n ) {\n this.createObservableInstance(fireHooks)\n }\n }\n\n createObservableInstance(fireHooks = true): void {\n if (devMode()) {\n if (this.state !== NodeLifeCycle.INITIALIZING) {\n // istanbul ignore next\n throw fail(\n \"assertion failed: the creation of the observable instance must be done on the initializing phase\"\n )\n }\n }\n this._observableInstanceState = ObservableInstanceLifecycle.CREATING\n\n // make sure the parent chain is created as well\n\n // array with parent chain from parent to child\n const parentChain = []\n\n let parent = this.parent\n // for performance reasons we never go back further than the most direct\n // uninitialized parent\n // this is done to avoid traversing the whole tree to the root when using\n // the same reference again\n while (\n parent?._observableInstanceState ===\n ObservableInstanceLifecycle.UNINITIALIZED\n ) {\n parentChain.unshift(parent)\n parent = parent.parent\n }\n\n // initialize the uninitialized parent chain from parent to child\n for (const p of parentChain) {\n // delay firing hooks until after all parents have been created\n p.createObservableInstanceIfNeeded(false)\n }\n\n const type = this.type\n\n try {\n // @ts-expect-error storedValue type mismatch during initialization\n this.storedValue = type.createNewInstance(this._childNodes)\n this.preboot()\n\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 = ObservableInstanceLifecycle.CREATED\n\n // The snapshot computed branches on the non-observable\n // \"_observableInstanceState\" flag we just flipped, so a value already\n // memoized from the initial snapshot is now stale (mobx can't see the\n // change) — refresh it. When it was never read there is nothing to refresh,\n // and forcing it here would serialize the whole subtree (the dominant cost\n // of creating a root) for a value nobody has asked for yet, so we skip it.\n this.refreshMemoizedSnapshot()\n\n // The root's snapshot reaction only drives onSnapshot; set it up lazily\n // (onSnapshot already does) rather than eagerly here, so a root nobody\n // subscribes to never pays for a full-tree snapshot at creation. keepAlive\n // on _snapshotComputed preserves snapshot referential stability without it.\n\n this._childNodes = EMPTY_OBJECT\n\n this.state = NodeLifeCycle.CREATED\n\n if (fireHooks) {\n this.fireHook(Hook.afterCreate)\n // Note that the parent might not be finalized at this point\n // so afterAttach won't be called until later in that case\n this.finalizeCreation()\n\n // fire the hooks of the parents that we created\n for (const p of parentChain.reverse()) {\n p.fireHook(Hook.afterCreate)\n // This will call afterAttach on the child if necessary\n p.finalizeCreation()\n }\n }\n }\n\n get root(): AnyObjectNode {\n const parent = this.parent\n return parent ? parent.root : this\n }\n\n clearParent(): void {\n if (!this.parent) {\n return\n }\n\n // detach if attached\n this.fireHook(Hook.beforeDetach)\n const previousState = this.state\n this.state = NodeLifeCycle.DETACHING\n\n const root = this.root\n const newEnv = root.environment\n const 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 setParent(newParent: AnyObjectNode, subpath: string): void {\n const parentChanged = newParent !== this.parent\n const 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(\"assertion failed: subpath expected\")\n }\n if (!newParent) {\n // istanbul ignore next\n throw fail(\"assertion failed: new parent expected\")\n }\n\n if (this.parent && parentChanged) {\n throw fail(\n `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(\n `A state tree is not allowed to contain itself. Cannot assign ${this} to path '${newParent.path}/${subpath}'`\n )\n }\n if (\n !this.parent &&\n !!this.environment &&\n this.environment !== newParent.root.environment\n ) {\n throw fail(\n `A state tree cannot be made part of another state tree as long as their environments are different.`\n )\n }\n }\n\n if (parentChanged) {\n // attach to new parent\n this.environment = undefined // will use root's\n newParent.root.identifierCache!.mergeCache(this)\n this.baseSetParent(newParent, subpath)\n this.fireHook(Hook.afterAttach)\n } else if (subpathChanged) {\n // moving to a new subpath on the same parent\n this.baseSetParent(this.parent, subpath)\n }\n }\n\n protected fireHook(name: Hook): void {\n this.fireInternalHook(name)\n\n const fn =\n this.storedValue &&\n typeof this.storedValue === \"object\" &&\n (this.storedValue as any)[name]\n if (typeof fn === \"function\") {\n _allowStateChangesInsideComputed(() => {\n fn.apply(this.storedValue)\n })\n }\n }\n\n private _snapshotUponDeath?: S\n\n // advantage of using computed for a snapshot is that nicely respects transactions etc.\n get snapshot(): S {\n if (this.hasSnapshotPostProcessor) {\n this.createObservableInstanceIfNeeded()\n }\n return this._snapshotComputed.get()\n }\n\n /**\n * @internal\n * @hidden\n * Recompute+retrack the keepAlive snapshot computed if it has already run.\n * Needed whenever something changes what the snapshot would produce without\n * an observable mobx would track: flipping the (non-observable) observable-\n * instance state, or SnapshotProcessor rewriting getSnapshot after\n * construction (see snapshotProcessor._fixNode). If it never ran, there is\n * nothing cached to go stale, so this is a no-op.\n */\n refreshMemoizedSnapshot(): void {\n if (this._snapshotComputedEvaluated) {\n ;(this._snapshotComputed as any).trackAndCompute()\n }\n }\n\n // NOTE: we use this method to get snapshot without creating @computed overhead\n getSnapshot(): S {\n if (!this.isAlive) {\n return this._snapshotUponDeath!\n }\n return this._observableInstanceState === ObservableInstanceLifecycle.CREATED\n ? this._getActualSnapshot()\n : this._getCachedInitialSnapshot()\n }\n\n private _getActualSnapshot(): S {\n return this.type.getSnapshot(this)\n }\n\n private _getCachedInitialSnapshot(): S {\n if (!this._cachedInitialSnapshotCreated) {\n this._cachedInitialSnapshot = this.type.processInitialSnapshot(\n this._childNodes\n )\n this._cachedInitialSnapshotCreated = true\n }\n\n return this._cachedInitialSnapshot!\n }\n\n private isRunningAction(): boolean {\n if (this._isRunningAction) {\n return true\n }\n if (this.isRoot) {\n return false\n }\n return this.parent!.isRunningAction()\n }\n\n assertAlive(context: AssertAliveContext): void {\n const livelinessChecking = getLivelinessChecking()\n if (!this.isAlive && livelinessChecking !== \"ignore\") {\n const error = this._getAssertAliveError(context)\n switch (livelinessChecking) {\n case \"error\":\n throw fail(error)\n case \"warn\":\n warnError(error)\n }\n }\n }\n\n private _getAssertAliveError(context: AssertAliveContext): string {\n const escapedPath = this.getEscapedPath(false) || this.pathUponDeath || \"\"\n const subpath = (context.subpath && escapeJsonPath(context.subpath)) || \"\"\n\n let actionContext = context.actionContext || getCurrentActionContext()\n\n // try to use a real action context if possible since it includes the action name\n if (\n actionContext &&\n actionContext.type !== \"action\" &&\n actionContext.parentActionEvent\n ) {\n actionContext = actionContext.parentActionEvent\n }\n\n let actionFullPath = \"\"\n if (actionContext?.name != null) {\n // try to use the context, and if it not available use the node one\n const actionPath =\n (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 getChildNode(subpath: string): AnyNode {\n this.assertAlive({\n subpath\n })\n this._autoUnbox = false\n try {\n return this._observableInstanceState ===\n ObservableInstanceLifecycle.CREATED\n ? this.type.getChildNode(this, subpath)\n : this._childNodes[subpath]!\n } finally {\n this._autoUnbox = true\n }\n }\n\n getChildren(): ReadonlyArray<AnyNode> {\n this.assertAlive(EMPTY_OBJECT)\n this._autoUnbox = false\n try {\n return this._observableInstanceState ===\n ObservableInstanceLifecycle.CREATED\n ? this.type.getChildren(this)\n : convertChildNodesToArray(this._childNodes)\n } finally {\n this._autoUnbox = true\n }\n }\n\n getChildType(propertyName?: string): IAnyType {\n return this.type.getChildType(propertyName)\n }\n\n get isProtected(): boolean {\n return this.root.isProtectionEnabled\n }\n\n assertWritable(context: AssertAliveContext): void {\n this.assertAlive(context)\n if (!this.isRunningAction() && this.isProtected) {\n throw fail(\n `Cannot modify '${this}', the object is protected and can only be modified by using an action.`\n )\n }\n }\n\n removeChild(subpath: string): void {\n this.type.removeChild(this, subpath)\n }\n\n // bound on the constructor\n unbox(childNode: AnyNode | undefined): AnyNode | undefined {\n if (!childNode) {\n return childNode\n }\n\n this.assertAlive({\n subpath: childNode.subpath || childNode.subpathUponDeath\n })\n return this._autoUnbox ? childNode.value : childNode\n }\n\n override toString(): string {\n const path = (this.isAlive ? this.path : this.pathUponDeath) || \"<root>\"\n const identifier = this.identifier ? `(id: ${this.identifier})` : \"\"\n return `${this.type.name}@${path}${identifier}${this.isAlive ? \"\" : \" [dead]\"}`\n }\n\n finalizeCreation(): void {\n this.baseFinalizeCreation(() => {\n for (const child of this.getChildren()) {\n child.finalizeCreation()\n }\n\n this.fireInternalHook(Hook.afterCreationFinalization)\n })\n }\n\n detach(): void {\n if (!this.isAlive) {\n throw fail(`Error while detaching, node is not alive.`)\n }\n\n this.clearParent()\n }\n\n private preboot(): void {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const self = this\n this._applyPatches = createActionInvoker(\n this.storedValue,\n \"@APPLY_PATCHES\",\n (patches: ReadonlyArray<IJsonPatch>) => {\n patches.forEach(patch => {\n if (!patch.path) {\n self.type.applySnapshot(self, patch.value)\n return\n }\n const parts = splitJsonPath(patch.path)\n const node = resolveNodeByPathParts(\n self,\n parts.slice(0, -1)\n ) as AnyObjectNode\n node.applyPatchLocally(parts[parts.length - 1]!, patch)\n })\n }\n )\n this._applySnapshot = createActionInvoker(\n this.storedValue,\n \"@APPLY_SNAPSHOT\",\n (snapshot: C) => {\n // if the snapshot is the same as the current one, avoid performing a reconcile\n if (snapshot === (self.snapshot as any)) {\n return\n }\n // else, apply it by calling the type logic\n return self.type.applySnapshot(self, snapshot)\n }\n )\n\n addHiddenFinalProp(this.storedValue, \"$treenode\", this)\n addHiddenFinalProp(this.storedValue, \"toJSON\", toJSON)\n }\n\n die(): void {\n if (!this.isAlive || this.state === NodeLifeCycle.DETACHING) {\n return\n }\n this.aboutToDie()\n this.finalizeDeath()\n }\n\n aboutToDie(): void {\n if (\n this._observableInstanceState ===\n ObservableInstanceLifecycle.UNINITIALIZED\n ) {\n return\n }\n\n this.getChildren().forEach(node => {\n node.aboutToDie()\n })\n\n // beforeDestroy should run before the disposers since else we could end up in a situation where\n // a disposer added with addDisposer at this stage (beforeDestroy) is actually never released\n this.baseAboutToDie()\n\n this._internalEventsEmit(InternalEvents.Dispose)\n this._internalEventsClear(InternalEvents.Dispose)\n }\n\n finalizeDeath(): void {\n // invariant: not called directly but from \"die\"\n this.getChildren().forEach(node => {\n node.finalizeDeath()\n })\n this.root.identifierCache!.notifyDied(this)\n\n // \"kill\" the computed prop and just store the last snapshot\n const snapshot = this.snapshot\n this._snapshotUponDeath = snapshot\n\n this._internalEventsClearAll()\n\n this.baseFinalizeDeath()\n }\n\n onSnapshot(onChange: (snapshot: S) => void): IDisposer {\n this._addSnapshotReaction()\n const unregister = this._internalEventsRegister(\n InternalEvents.Snapshot,\n onChange\n )\n return () => {\n unregister()\n // The reaction re-serializes the whole subtree on every change, so leaving\n // it running once the last listener is gone would keep charging the node\n // for a snapshot nobody receives. Referential stability of getSnapshot()\n // does not depend on it — that comes from keepAlive on _snapshotComputed.\n if (!this._internalEventsHasSubscribers(InternalEvents.Snapshot)) {\n this._removeSnapshotReaction()\n }\n }\n }\n\n protected emitSnapshot(snapshot: S): void {\n this._internalEventsEmit(InternalEvents.Snapshot, snapshot)\n }\n\n onPatch(\n handler: (patch: IJsonPatch, reversePatch: IJsonPatch) => void\n ): IDisposer {\n return this._internalEventsRegister(InternalEvents.Patch, handler)\n }\n\n emitPatch(basePatch: IReversibleJsonPatch, source: AnyNode): void {\n if (this._internalEventsHasSubscribers(InternalEvents.Patch)) {\n const localizedPatch: IReversibleJsonPatch = {\n ...basePatch,\n path: `${source.path.slice(this.path.length)}/${basePatch.path}` // calculate the relative path of the patch\n }\n const [patch, reversePatch] = splitPatch(localizedPatch)\n this._internalEventsEmit(InternalEvents.Patch, patch, reversePatch)\n }\n if (this.parent) {\n this.parent.emitPatch(basePatch, source)\n }\n }\n\n hasDisposer(disposer: () => void): boolean {\n return this._internalEventsHas(InternalEvents.Dispose, disposer)\n }\n\n addDisposer(disposer: () => void): void {\n if (!this.hasDisposer(disposer)) {\n this._internalEventsRegister(InternalEvents.Dispose, disposer, true)\n return\n }\n throw fail(\n \"cannot add a disposer when it is already registered for execution\"\n )\n }\n\n removeDisposer(disposer: () => void): void {\n if (!this._internalEventsHas(InternalEvents.Dispose, disposer)) {\n throw fail(\n \"cannot remove a disposer which was never registered for execution\"\n )\n }\n this._internalEventsUnregister(InternalEvents.Dispose, disposer)\n }\n\n private removeMiddleware(middleware: IMiddleware): void {\n if (this.middlewares) {\n const index = this.middlewares.indexOf(middleware)\n if (index >= 0) {\n this.middlewares.splice(index, 1)\n }\n }\n }\n\n addMiddleWare(handler: IMiddlewareHandler, includeHooks = true): IDisposer {\n const middleware = { handler, includeHooks }\n if (!this.middlewares) {\n this.middlewares = [middleware]\n } else {\n this.middlewares.push(middleware)\n }\n\n return () => {\n this.removeMiddleware(middleware)\n }\n }\n\n applyPatchLocally(subpath: string, patch: IJsonPatch): void {\n this.assertWritable({\n subpath\n })\n this.createObservableInstanceIfNeeded()\n this.type.applyPatchLocally(this, subpath, patch)\n }\n\n private _addSnapshotReaction(): void {\n if (!this._snapshotReactionDisposer) {\n const snapshotDisposer = reaction(\n () => this.snapshot,\n snapshot => this.emitSnapshot(snapshot),\n snapshotReactionOptions\n )\n this.addDisposer(snapshotDisposer)\n this._snapshotReactionDisposer = snapshotDisposer\n }\n }\n\n private _removeSnapshotReaction(): void {\n const disposer = this._snapshotReactionDisposer\n if (!disposer) {\n return\n }\n this._snapshotReactionDisposer = undefined\n // not removeDisposer(), which throws when the registration is already gone —\n // the last listener can be disposed from within a disposer, i.e. after\n // aboutToDie has cleared them\n this._internalEventsUnregister(InternalEvents.Dispose, disposer)\n disposer()\n }\n\n // #region internal event handling\n\n private _internalEvents?: EventHandlers<InternalEventHandlers<S>>\n\n // we proxy the methods to avoid creating an EventHandlers instance when it is not needed\n\n private _internalEventsHasSubscribers(event: InternalEvents): boolean {\n return !!this._internalEvents && this._internalEvents.hasSubscribers(event)\n }\n\n private _internalEventsRegister<IE extends InternalEvents>(\n event: IE,\n eventHandler: InternalEventHandlers<S>[IE],\n atTheBeginning = false\n ): IDisposer {\n if (!this._internalEvents) {\n this._internalEvents = new EventHandlers()\n }\n return this._internalEvents.register(event, eventHandler, atTheBeginning)\n }\n\n private _internalEventsHas<IE extends InternalEvents>(\n event: IE,\n eventHandler: InternalEventHandlers<S>[IE]\n ): boolean {\n return (\n !!this._internalEvents && this._internalEvents.has(event, eventHandler)\n )\n }\n\n private _internalEventsUnregister<IE extends InternalEvents>(\n event: IE,\n eventHandler: InternalEventHandlers<S>[IE]\n ): void {\n if (this._internalEvents) {\n this._internalEvents.unregister(event, eventHandler)\n }\n }\n\n private _internalEventsEmit<IE extends InternalEvents>(\n event: IE,\n ...args: ArgumentTypes<InternalEventHandlers<S>[IE]>\n ): void {\n if (this._internalEvents) {\n this._internalEvents.emit(event, ...args)\n }\n }\n\n private _internalEventsClear(event: InternalEvents): void {\n if (this._internalEvents) {\n this._internalEvents.clear(event)\n }\n }\n\n private _internalEventsClearAll(): void {\n if (this._internalEvents) {\n this._internalEvents.clearAll()\n }\n }\n\n // #endregion\n}\nObjectNode.prototype.createObservableInstance = action(\n ObjectNode.prototype.createObservableInstance\n)\nObjectNode.prototype.detach = action(ObjectNode.prototype.detach)\nObjectNode.prototype.die = action(ObjectNode.prototype.die)\n\n/**\n * @internal\n * @hidden\n */\nexport type AnyObjectNode = ObjectNode<any, any, any>\n\n/**\n * @internal\n * @hidden\n */\nexport interface AssertAliveContext {\n subpath?: string | undefined\n actionContext?: IMiddlewareEvent | undefined\n}\n","import { action } from \"mobx\"\n\nimport {\n type BaseNode,\n assertArg,\n fail,\n getStateTreeNode,\n getStateTreeNodeSafe,\n getType,\n isMutable,\n isStateTreeNode,\n normalizeIdentifier,\n typeCheckFailure,\n typeCheckSuccess,\n typecheckInternal,\n type AnyNode,\n type AnyObjectNode,\n type IChildNodesMap,\n type IJsonPatch,\n type IStateTreeNode,\n type IValidationContext,\n type IValidationResult,\n type ModelPrimitive,\n type ObjectNode,\n type ScalarNode\n} from \"../../internal.ts\"\n\n/**\n * @internal\n * @hidden\n */\nexport enum TypeFlags {\n String = 1,\n Number = 1 << 1,\n Boolean = 1 << 2,\n Date = 1 << 3,\n Literal = 1 << 4,\n Array = 1 << 5,\n Map = 1 << 6,\n Object = 1 << 7,\n Frozen = 1 << 8,\n Optional = 1 << 9,\n Reference = 1 << 10,\n Identifier = 1 << 11,\n Late = 1 << 12,\n Refinement = 1 << 13,\n Union = 1 << 14,\n Null = 1 << 15,\n Undefined = 1 << 16,\n Integer = 1 << 17,\n Custom = 1 << 18,\n SnapshotProcessor = 1 << 19,\n Lazy = 1 << 20,\n Finite = 1 << 21,\n Float = 1 << 22\n}\n\n/**\n * The value `getSubTypes()` returns when a type cannot report its subtype,\n * which is distinct from reporting that it has none (`null`).\n */\nexport const cannotDetermineSubtype = \"cannotDetermine\"\n\n/**\n * A state tree node value.\n * @hidden\n */\nexport type STNValue<T, IT extends IAnyType> = T extends object\n ? T & IStateTreeNode<IT>\n : T\n\n/** @hidden */\nconst $type: unique symbol = Symbol(\"$type\")\n\n/**\n * A type, either complex or simple.\n */\nexport interface IType<C, S, T> {\n // fake, will never be present, just for typing\n /** @hidden */\n readonly [$type]: undefined\n\n /**\n * Friendly type name.\n */\n name: string\n\n /**\n * Name of the identifier attribute or null if none.\n */\n readonly identifierAttribute?: string | undefined\n\n /**\n * Creates an instance for the type given an snapshot input.\n *\n * The snapshot argument is required only when leaving it out would be a\n * runtime error: the creation type has a required member (`{} extends C` is\n * false) and does not admit `undefined`, which is what a type supplying its\n * own default snapshot — an array, a map, anything `optional` — does. So\n * `types.model({ a: types.string }).create()` is a compile error rather than\n * a runtime throw, while `types.model().create()`,\n * `types.array(types.string).create()` and\n * `types.optional(types.string, \"x\").create()` stay valid.\n *\n * @returns An instance of that type.\n */\n create(\n ...args: {} extends C\n ? [snapshot?: C, env?: any]\n : undefined extends C\n ? [snapshot?: C, env?: any]\n : [snapshot: C, env?: any]\n ): this[\"Type\"]\n\n /**\n * Checks if a given snapshot / instance is of the given type.\n *\n * @param thing Snapshot or instance to be checked.\n * @returns true if the value is of the current type, false otherwise.\n */\n is(thing: unknown): thing is C | this[\"Type\"]\n\n /**\n * Run's the type's typechecker on the given value with the given validation context.\n *\n * @param thing Value to be checked, either a snapshot or an instance.\n * @param context Validation context, an array of { subpaths, subtypes } that should be validated\n * @returns The validation result, an array with the list of validation errors.\n */\n validate(thing: C, context: IValidationContext): IValidationResult\n\n /**\n * Gets the textual representation of the type as a string.\n */\n describe(): string\n\n /**\n * @deprecated use `Instance<typeof MyType>` instead.\n * @hidden\n */\n readonly Type: STNValue<T, this>\n\n /**\n * @deprecated do not use.\n * @hidden\n */\n readonly TypeWithoutSTN: T\n\n /**\n * @deprecated use `SnapshotOut<typeof MyType>` instead.\n * @hidden\n */\n readonly SnapshotType: S\n\n /**\n * @deprecated use `SnapshotIn<typeof MyType>` instead.\n * @hidden\n */\n readonly CreationType: C\n\n // Internal api's\n\n /**\n * @internal\n * @hidden\n */\n flags: TypeFlags\n /**\n * @internal\n * @hidden\n */\n isType: true\n /**\n * @internal\n * @hidden\n */\n instantiate(\n parent: AnyObjectNode | null,\n subpath: string,\n environment: any,\n initialValue: C | T\n ): BaseNode<C, S, T>\n /**\n * @internal\n * @hidden\n */\n reconcile(\n current: BaseNode<C, S, T>,\n newValue: C | T,\n parent: AnyObjectNode,\n subpath: string\n ): BaseNode<C, S, T>\n /**\n * @internal\n * @hidden\n */\n getSnapshot(node: BaseNode<C, S, T>, applyPostProcess?: boolean): S\n /**\n * @internal\n * @hidden\n */\n isAssignableFrom(type: IAnyType): boolean\n /**\n * @internal\n * @hidden\n */\n getSubTypes(): IAnyType[] | IAnyType | null | typeof cannotDetermineSubtype\n}\n\n/**\n * Any kind of type.\n */\nexport interface IAnyType extends IType<any, any, any> {}\n\n/**\n * A simple type, this is, a type where the instance and the snapshot representation are the same.\n */\nexport interface ISimpleType<T> extends IType<T, T, T> {}\n\n/** @hidden */\nexport type Primitives = ModelPrimitive | null | undefined\n\n/**\n * A complex type.\n * @deprecated just for compatibility with old versions, could be deprecated on the next major version\n * @hidden\n */\nexport interface IComplexType<C, S, T> extends IType<C, S, T & object> {}\n\n/**\n * Any kind of complex type.\n */\nexport interface IAnyComplexType extends IType<any, any, object> {}\n\n/** @hidden */\nexport type ExtractCSTWithSTN<\n IT extends {\n [$type]: undefined\n CreationType: any\n SnapshotType: any\n Type: any\n }\n> = IT[\"CreationType\"] | IT[\"SnapshotType\"] | IT[\"Type\"]\n\n/**\n * The instance representation of a given type.\n */\nexport type Instance<T> = T extends { [$type]: undefined; Type: any }\n ? T[\"Type\"]\n : T\n\n/**\n * The input (creation) snapshot representation of a given type.\n */\nexport type SnapshotIn<T> = T extends { [$type]: undefined; CreationType: any }\n ? T[\"CreationType\"]\n : T extends IStateTreeNode<infer IT>\n ? IT[\"CreationType\"]\n : T\n\n/**\n * The output snapshot representation of a given type.\n */\nexport type SnapshotOut<T> = T extends { [$type]: undefined; SnapshotType: any }\n ? T[\"SnapshotType\"]\n : T extends IStateTreeNode<infer IT>\n ? IT[\"SnapshotType\"]\n : T\n\n/**\n * A type which is equivalent to the union of SnapshotIn and Instance types of a given typeof TYPE or typeof VARIABLE.\n * For primitives it defaults to the primitive itself.\n *\n * For example:\n * - `SnapshotOrInstance<typeof ModelA> = SnapshotIn<typeof ModelA> | Instance<typeof ModelA>`\n * - `SnapshotOrInstance<typeof self.a (where self.a is a ModelA)> = SnapshotIn<typeof ModelA> | Instance<typeof ModelA>`\n *\n * Usually you might want to use this when your model has a setter action that sets a property.\n *\n * Example:\n * ```ts\n * const ModelA = types.model({\n * n: types.number\n * })\n *\n * const ModelB = types.model({\n * innerModel: ModelA\n * }).actions(self => ({\n * // this will accept as property both the snapshot and the instance, whichever is preferred\n * setInnerModel(m: SnapshotOrInstance<typeof self.innerModel>) {\n * self.innerModel = cast(m)\n * }\n * }))\n * ```\n */\nexport type SnapshotOrInstance<T> = SnapshotIn<T> | Instance<T>\n\n/**\n * A base type produces a MST node (Node in the state tree)\n *\n * @internal\n * @hidden\n */\nexport abstract class BaseType<\n C,\n S,\n T,\n N extends BaseNode<any, any, any> = BaseNode<C, S, T>\n> implements IType<C, S, T> {\n // `declare`, not a definite-assignment `!`: none of these five exist at\n // runtime — `$type` is the nominal brand and C/S/T/N only make the inner\n // types available to subclasses as `this[\"C\"]` etc. Under\n // useDefineForClassFields a `!` field is still *emitted*, so every type\n // object in the process was materializing five own slots it never reads.\n declare readonly [$type]: undefined\n\n // these are just to make inner types avaialable to inherited classes\n declare readonly C: C\n declare readonly S: S\n declare readonly T: T\n declare readonly N: N\n\n // on the prototype, not on every instance: it is the same `true` for every\n // type ever built, and an own slot per type is exactly the kind of per-type\n // charge ADR 0003 is about. Assigned below the class body.\n declare readonly isType: true\n\n // `undefined` on the prototype rather than an own slot per type: the\n // composite types leave the name unset (see `name` below), so for a union or\n // an optional this field only ever held `undefined`. The own slot appears\n // when a name is actually assigned, which is the same trick as `isType`.\n declare private _name?: string\n\n /**\n * Builds the name of a type that does not get one handed to it. Composite\n * types (`union`, `array`, `map`, `reference`, ...) override this to fold\n * their members' names; see {@link name}. It runs after construction, so\n * unlike a `super(...)` argument it can read the subclass's own fields.\n */\n protected computeName(): string {\n // istanbul ignore next\n throw fail(`${this.constructor.name} has neither a name nor a computeName`)\n }\n\n /**\n * Friendly type name.\n *\n * A composite type folds its members' names, which for a union is a map +\n * join over every member — and the result is read only by error messages and\n * `describe()`. So those types leave it unset and it is built on first read\n * and cached: a union that never fails a typecheck never builds one, and\n * jbrowse builds a union per config slot, tens of thousands per session load.\n *\n * Deliberately not a lambda passed to the constructor: that allocated a\n * closure per type (the very cost being avoided) and made two separately\n * built but equivalent types compare unequal, since the closures differ.\n */\n get name(): string {\n return (this._name ??= this.computeName())\n }\n\n set name(value: string) {\n this._name = value\n }\n\n constructor(name?: string) {\n if (name !== undefined) {\n this._name = name\n }\n }\n\n create(snapshot?: C, environment?: any) {\n typecheckInternal(this, snapshot)\n return this.instantiate(null, \"\", environment, snapshot!).value\n }\n\n getSnapshot(_node: N, _applyPostProcess?: boolean): S {\n // istanbul ignore next\n throw fail(\"unimplemented method\")\n }\n\n abstract reconcile(\n current: N,\n newValue: C | T,\n parent: AnyObjectNode,\n subpath: string\n ): N\n\n abstract instantiate(\n parent: AnyObjectNode | null,\n subpath: string,\n environment: any,\n initialValue: C | T\n ): N\n\n declare abstract flags: TypeFlags\n\n describe(): string {\n return this.name\n }\n\n abstract isValidSnapshot(\n value: C,\n context: IValidationContext\n ): IValidationResult\n\n isAssignableFrom(type: IAnyType): boolean {\n return type === this\n }\n\n validate(value: C | T, context: IValidationContext): IValidationResult {\n const node = getStateTreeNodeSafe(value)\n if (node) {\n const valueType = getType(value)\n return this.isAssignableFrom(valueType)\n ? typeCheckSuccess()\n : typeCheckFailure(context, value)\n // it is tempting to compare snapshots, but in that case we should always clone on assignments...\n }\n\n return this.isValidSnapshot(value as C, context)\n }\n\n is(thing: unknown): thing is any {\n return this.validate(thing as C, [{ path: \"\", type: this }]).length === 0\n }\n\n get Type(): any {\n // istanbul ignore next\n throw fail(\n \"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 }\n get TypeWithoutSTN(): any {\n // istanbul ignore next\n throw fail(\n \"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 }\n get SnapshotType(): any {\n // istanbul ignore next\n throw fail(\n \"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 }\n get CreationType(): any {\n // istanbul ignore next\n throw fail(\n \"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 }\n\n abstract getSubTypes():\n | IAnyType[]\n | IAnyType\n | null\n | typeof cannotDetermineSubtype\n}\nBaseType.prototype.create = action(BaseType.prototype.create)\n// Defaults that every type shares, kept off the individual type objects. See\n// `isType` and `_name` in the class body.\nObject.assign(BaseType.prototype as object, { isType: true, _name: undefined })\n\n/**\n * @internal\n * @hidden\n */\nexport type ExtractNodeType<IT extends IAnyType> =\n IT extends BaseType<any, any, any, infer N> ? N : never\n\n/**\n * A complex type produces a MST node (Node in the state tree)\n *\n * @internal\n * @hidden\n */\nexport abstract class ComplexType<C, S, T> extends BaseType<\n C,\n S,\n T,\n ObjectNode<C, S, T>\n> {\n identifierAttribute?: string | undefined\n\n override create(snapshot: C = this.getDefaultSnapshot(), environment?: any) {\n return super.create(snapshot, environment)\n }\n\n getValue(node: this[\"N\"]): T {\n node.createObservableInstanceIfNeeded()\n return node.storedValue\n }\n\n abstract getDefaultSnapshot(): C\n\n abstract createNewInstance(childNodes: IChildNodesMap): T\n abstract finalizeNewInstance(node: this[\"N\"], instance: any): void\n\n abstract applySnapshot(node: this[\"N\"], snapshot: C): void\n abstract applyPatchLocally(\n node: this[\"N\"],\n subpath: string,\n patch: IJsonPatch\n ): void\n abstract processInitialSnapshot(childNodes: IChildNodesMap): S\n\n abstract getChildren(node: this[\"N\"]): ReadonlyArray<AnyNode>\n abstract getChildNode(node: this[\"N\"], key: string): AnyNode\n abstract getChildType(propertyName?: string): IAnyType\n abstract initializeChildNodes(node: this[\"N\"], snapshot: any): IChildNodesMap\n abstract removeChild(node: this[\"N\"], subpath: string): void\n\n isMatchingSnapshotId(current: this[\"N\"], snapshot: C): boolean {\n return (\n !current.identifierAttribute ||\n current.identifier ===\n normalizeIdentifier((snapshot as any)[current.identifierAttribute])\n )\n }\n\n private tryToReconcileNode(current: this[\"N\"], newValue: C | T) {\n if (current.isDetaching) {\n return false\n }\n if ((current.snapshot as any) === newValue) {\n // newValue is the current snapshot of the node, noop\n return true\n }\n if (isStateTreeNode(newValue) && getStateTreeNode(newValue) === current) {\n // the current node is the same as the new one\n return true\n }\n if (\n current.type === this &&\n isMutable(newValue) &&\n !isStateTreeNode(newValue) &&\n this.isMatchingSnapshotId(current, newValue as any)\n ) {\n // the newValue has no node, so can be treated like a snapshot\n // we can reconcile\n current.applySnapshot(newValue as C)\n return true\n }\n return false\n }\n\n reconcile(\n current: this[\"N\"],\n newValue: C | T,\n parent: AnyObjectNode,\n subpath: string\n ): this[\"N\"] {\n const nodeReconciled = this.tryToReconcileNode(current, newValue)\n if (nodeReconciled) {\n current.setParent(parent, subpath)\n return current\n }\n\n // current node cannot be recycled in any way\n current.die() // noop if detaching\n // attempt to reuse the new one\n if (isStateTreeNode(newValue) && this.isAssignableFrom(getType(newValue))) {\n // newValue is a Node as well, move it here..\n const newNode = getStateTreeNode(newValue)\n newNode.setParent(parent, subpath)\n return newNode\n }\n // nothing to do, we have to create a new node\n return this.instantiate(parent, subpath, undefined, newValue)\n }\n\n getSubTypes() {\n return null\n }\n}\nComplexType.prototype.create = action(ComplexType.prototype.create)\n\n/**\n * @internal\n * @hidden\n */\nexport abstract class SimpleType<C, S, T> extends BaseType<\n C,\n S,\n T,\n ScalarNode<C, S, T>\n> {\n abstract override instantiate(\n parent: AnyObjectNode | null,\n subpath: string,\n environment: any,\n initialValue: C\n ): this[\"N\"]\n\n createNewInstance(snapshot: C): T {\n return snapshot as any\n }\n\n getValue(node: this[\"N\"]): T {\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 override getSnapshot(node: this[\"N\"]): S {\n return node.storedValue\n }\n\n reconcile(\n current: this[\"N\"],\n newValue: C,\n parent: AnyObjectNode,\n subpath: string\n ): this[\"N\"] {\n // reconcile only if type and value are still the same, and only if the node is not detaching\n if (\n !current.isDetaching &&\n current.type === this &&\n current.storedValue === newValue\n ) {\n return current\n }\n const res = this.instantiate(parent, subpath, undefined, newValue)\n current.die() // noop if detaching\n return res\n }\n\n getSubTypes() {\n return null\n }\n}\n\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 */\nexport function isType(value: unknown): value is IAnyType {\n return (\n typeof value === \"object\" && (value as IAnyType | null)?.isType === true\n )\n}\n\n/**\n * @internal\n * @hidden\n */\nexport function assertIsType(type: IAnyType, argNumber: number | number[]) {\n assertArg(type, isType, \"mobx-state-tree type\", argNumber)\n}\n","import { type IMiddlewareEvent, type IMiddlewareHandler } from \"../internal.ts\"\n\nexport interface IActionTrackingMiddlewareHooks<T> {\n filter?: (call: IMiddlewareEvent) => boolean\n onStart: (call: IMiddlewareEvent) => T\n onResume: (call: IMiddlewareEvent, context: T) => void\n onSuspend: (call: IMiddlewareEvent, context: T) => void\n onSuccess: (call: IMiddlewareEvent, context: T, result: any) => void\n onFail: (call: IMiddlewareEvent, context: T, error: any) => void\n}\n\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 */\nexport function createActionTrackingMiddleware<T = any>(\n hooks: IActionTrackingMiddlewareHooks<T>\n): IMiddlewareHandler {\n // per middleware, not per module: the entries hold the `context` this\n // middleware's own onStart returned, so two middlewares on one tree would\n // otherwise overwrite each other's context and then delete the shared entry —\n // whichever saw `flow_return` second dereferenced `undefined`.\n // createActionTrackingMiddleware2 scopes its map the same way.\n const runningActions = new Map<\n number,\n { async: boolean; call: IMiddlewareEvent; context: T }\n >()\n\n return function actionTrackingMiddleware(\n call: IMiddlewareEvent,\n next: (actionCall: IMiddlewareEvent) => any,\n _abort: (value: any) => any\n ) {\n switch (call.type) {\n case \"action\": {\n if (!hooks.filter || hooks.filter(call) === true) {\n const context = hooks.onStart(call)\n hooks.onResume(call, context)\n runningActions.set(call.id, {\n call,\n context,\n async: false\n })\n try {\n const res = next(call)\n hooks.onSuspend(call, context)\n if (runningActions.get(call.id)!.async === false) {\n runningActions.delete(call.id)\n hooks.onSuccess(call, context, res)\n }\n return res\n } 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 case \"flow_spawn\": {\n const root = runningActions.get(call.rootId)!\n root.async = true\n return next(call)\n }\n case \"flow_resume\":\n case \"flow_resume_error\": {\n const root = runningActions.get(call.rootId)!\n hooks.onResume(call, root.context)\n try {\n return next(call)\n } finally {\n hooks.onSuspend(call, root.context)\n }\n }\n case \"flow_throw\": {\n const root = runningActions.get(call.rootId)!\n runningActions.delete(call.rootId)\n hooks.onFail(call, root.context, call.args[0])\n return next(call)\n }\n case \"flow_return\": {\n const 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","import {\n type IActionContext,\n type IMiddlewareEvent,\n type IMiddlewareHandler\n} from \"../internal.ts\"\n\nexport interface IActionTrackingMiddleware2Call<\n TEnv\n> extends Readonly<IActionContext> {\n env: TEnv | undefined\n readonly parentCall?: IActionTrackingMiddleware2Call<TEnv> | undefined\n}\n\nexport interface IActionTrackingMiddleware2Hooks<TEnv> {\n filter?: (call: IActionTrackingMiddleware2Call<TEnv>) => boolean\n onStart: (call: IActionTrackingMiddleware2Call<TEnv>) => void\n onFinish: (call: IActionTrackingMiddleware2Call<TEnv>, error?: any) => void\n}\n\nclass RunningAction {\n private flowsPending = 0\n private running = true\n\n constructor(\n public readonly hooks: IActionTrackingMiddleware2Hooks<any> | undefined,\n readonly call: IActionTrackingMiddleware2Call<any>\n ) {\n if (hooks) {\n hooks.onStart(call)\n }\n }\n\n finish(error?: any) {\n if (this.running) {\n this.running = false\n if (this.hooks) {\n this.hooks.onFinish(this.call, error)\n }\n }\n }\n\n incFlowsPending() {\n this.flowsPending++\n }\n\n decFlowsPending() {\n this.flowsPending--\n }\n\n get hasFlowsPending() {\n return this.flowsPending > 0\n }\n}\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 */\nexport function createActionTrackingMiddleware2<TEnv = any>(\n middlewareHooks: IActionTrackingMiddleware2Hooks<TEnv>\n): IMiddlewareHandler {\n const runningActions = new Map<number, RunningAction>()\n\n return function actionTrackingMiddleware(\n call: IMiddlewareEvent,\n next: (actionCall: IMiddlewareEvent) => any\n ) {\n // find parentRunningAction\n const parentRunningAction = call.parentActionEvent\n ? runningActions.get(call.parentActionEvent.id)\n : undefined\n\n if (call.type === \"action\") {\n const newCall: IActionTrackingMiddleware2Call<TEnv> = {\n ...call,\n // make a shallow copy of the parent action env\n env: parentRunningAction?.call.env,\n parentCall: parentRunningAction?.call\n }\n\n const passesFilter =\n !middlewareHooks.filter || middlewareHooks.filter(newCall)\n const hooks = passesFilter ? middlewareHooks : undefined\n\n const runningAction = new RunningAction(hooks, newCall)\n runningActions.set(call.id, runningAction)\n\n let res\n try {\n res = next(call)\n } catch (e) {\n runningActions.delete(call.id)\n runningAction.finish(e)\n throw e\n }\n // sync action finished\n if (!runningAction.hasFlowsPending) {\n runningActions.delete(call.id)\n runningAction.finish()\n }\n return res\n } else {\n if (!parentRunningAction) {\n return next(call)\n }\n\n switch (call.type) {\n case \"flow_spawn\": {\n parentRunningAction.incFlowsPending()\n return next(call)\n }\n case \"flow_resume\":\n case \"flow_resume_error\": {\n return next(call)\n }\n case \"flow_throw\": {\n const error = call.args[0]\n try {\n return next(call)\n } finally {\n parentRunningAction.decFlowsPending()\n if (!parentRunningAction.hasFlowsPending) {\n runningActions.delete(call.parentActionEvent!.id)\n parentRunningAction.finish(error)\n }\n }\n }\n case \"flow_return\": {\n try {\n return next(call)\n } finally {\n parentRunningAction.decFlowsPending()\n if (!parentRunningAction.hasFlowsPending) {\n runningActions.delete(call.parentActionEvent!.id)\n parentRunningAction.finish()\n }\n }\n }\n }\n }\n }\n}\n","import { runInAction } from \"mobx\"\n\nimport {\n type IActionContext,\n type IAnyStateTreeNode,\n type IDisposer,\n addMiddleware,\n applyPatch,\n applySnapshot,\n asArray,\n assertArg,\n assertIsStateTreeNode,\n devMode,\n fail,\n getRelativePathBetweenNodes,\n getRunningActionContext,\n getStateTreeNode,\n getType,\n isArray,\n isPlainObject,\n isPrimitive,\n isProtected,\n isRoot,\n isStateTreeNode,\n tryResolve,\n warnError\n} from \"../internal.ts\"\n\nexport interface ISerializedActionCall {\n name: string\n path?: string\n args?: any[]\n}\n\nexport interface IActionRecorder {\n actions: ReadonlyArray<ISerializedActionCall>\n readonly recording: boolean\n stop(): void\n resume(): void\n replay(target: IAnyStateTreeNode): void\n}\n\nfunction serializeArgument(arg: any): any {\n if (arg instanceof Date) {\n return { $MST_DATE: arg.getTime() }\n }\n if (isPrimitive(arg)) {\n return arg\n }\n // We should not serialize MST nodes, even if we can, because we don't know if the receiving party can handle a raw snapshot instead of an\n // MST type instance. So if one wants to serialize a MST node that was pass in, either explitly pass: 1: an id, 2: a (relative) path, 3: a snapshot\n if (isStateTreeNode(arg)) {\n return serializeTheUnserializable(`[MSTNode: ${getType(arg).name}]`)\n }\n if (typeof arg === \"function\") {\n return serializeTheUnserializable(`[function]`)\n }\n if (typeof arg === \"object\" && !isPlainObject(arg) && !isArray(arg)) {\n return serializeTheUnserializable(\n `[object ${arg?.constructor?.name || \"Complex Object\"}]`\n )\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 return arg\n } catch (e) {\n return serializeTheUnserializable(`${e}`)\n }\n}\n\nfunction deserializeArgument(value: any): any {\n if (value && typeof value === \"object\" && \"$MST_DATE\" in value) {\n return new Date(value[\"$MST_DATE\"])\n }\n return value\n}\n\nfunction serializeTheUnserializable(baseType: string) {\n return {\n $MST_UNSERIALIZABLE: true,\n type: baseType\n }\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 */\nexport function applyAction(\n target: IAnyStateTreeNode,\n actions: ISerializedActionCall | ISerializedActionCall[]\n): void {\n // check all arguments\n assertIsStateTreeNode(target, 1)\n assertArg(actions, a => typeof a === \"object\", \"object or array\", 2)\n\n runInAction(() => {\n asArray(actions).forEach(action => baseApplyAction(target, action))\n })\n}\n\nfunction baseApplyAction(\n target: IAnyStateTreeNode,\n action: ISerializedActionCall\n): any {\n const resolvedTarget = tryResolve(target, action.path || \"\")\n if (!resolvedTarget) {\n throw fail(`Invalid action path: ${action.path || \"\"}`)\n }\n const node = getStateTreeNode(resolvedTarget)\n\n // Reserved functions\n if (action.name === \"@APPLY_PATCHES\") {\n return applyPatch.call(null, resolvedTarget, action.args![0])\n }\n if (action.name === \"@APPLY_SNAPSHOT\") {\n return applySnapshot.call(null, resolvedTarget, action.args![0])\n }\n\n if (!(typeof resolvedTarget[action.name] === \"function\")) {\n throw fail(`Action '${action.name}' does not exist in '${node.path}'`)\n }\n return resolvedTarget[action.name](\n ...(action.args ? action.args.map(deserializeArgument) : [])\n )\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 */\nexport function recordActions(\n subject: IAnyStateTreeNode,\n filter?: (\n action: ISerializedActionCall,\n actionContext: IActionContext | undefined\n ) => boolean\n): IActionRecorder {\n // check all arguments\n assertIsStateTreeNode(subject, 1)\n\n const actions: ISerializedActionCall[] = []\n const listener = (call: ISerializedActionCall) => {\n const recordThis = filter ? filter(call, getRunningActionContext()) : true\n if (recordThis) {\n actions.push(call)\n }\n }\n\n let disposer: IDisposer | undefined\n const recorder: IActionRecorder = {\n actions,\n get recording() {\n return !!disposer\n },\n stop() {\n if (disposer) {\n disposer()\n disposer = undefined\n }\n },\n resume() {\n if (disposer) {\n return\n }\n disposer = onAction(subject, listener)\n },\n replay(target) {\n applyAction(target, actions)\n }\n }\n\n recorder.resume()\n return recorder\n}\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 */\nexport function onAction(\n target: IAnyStateTreeNode,\n listener: (call: ISerializedActionCall) => void,\n attachAfter = false\n): IDisposer {\n // check all arguments\n assertIsStateTreeNode(target, 1)\n if (devMode()) {\n if (!isRoot(target)) {\n warnError(\n \"Warning: Attaching onAction listeners to non root nodes is dangerous: No events will be emitted for actions initiated higher up in the tree.\"\n )\n }\n if (!isProtected(target)) {\n warnError(\n \"Warning: Attaching onAction listeners to non protected nodes is dangerous: No events will be emitted for direct modifications without action.\"\n )\n }\n }\n\n return addMiddleware(target, function handler(rawCall, next) {\n if (rawCall.type === \"action\" && rawCall.id === rawCall.rootId) {\n const sourceNode = getStateTreeNode(rawCall.context)\n const info = {\n name: rawCall.name,\n path: getRelativePathBetweenNodes(getStateTreeNode(target), sourceNode),\n args: rawCall.args.map(serializeArgument)\n }\n if (attachAfter) {\n const 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","import { action as mobxAction } from \"mobx\"\n\nimport {\n Hook,\n devMode,\n fail,\n getRoot,\n getStateTreeNode,\n warnError\n} from \"../internal.ts\"\n\nimport type {\n AnyObjectNode,\n IActionContext,\n IAnyStateTreeNode,\n IDisposer\n} from \"../internal.ts\"\n\nexport type IMiddlewareEventType =\n | \"action\"\n | \"flow_spawn\"\n | \"flow_resume\"\n | \"flow_resume_error\"\n | \"flow_return\"\n | \"flow_throw\"\n// | \"task_spawn TODO, see #273\"\n\nexport interface IMiddlewareEvent extends IActionContext {\n /** Event type */\n readonly type: IMiddlewareEventType\n\n /** Parent event unique id */\n readonly parentId: number\n /** Parent event object */\n readonly parentEvent: IMiddlewareEvent | undefined\n\n /** Root event unique id */\n readonly rootId: number\n /** Id of all events, from root until current (excluding current) */\n readonly allParentIds: number[]\n}\n\nexport type FunctionWithFlag = ((...args: any[]) => any) & {\n _isMSTAction?: boolean | undefined\n _isFlowAction?: boolean | undefined\n $mst_middleware?: IMiddleware[] | undefined\n}\n\n/**\n * @internal\n * @hidden\n */\nexport type IMiddleware = {\n handler: IMiddlewareHandler\n includeHooks: boolean\n}\n\nexport type IMiddlewareHandler = (\n actionCall: IMiddlewareEvent,\n next: (actionCall: IMiddlewareEvent, callback?: (value: any) => any) => void,\n abort: (value: any) => void\n) => any\n\nlet nextActionId = 1\nlet currentActionContext: IMiddlewareEvent | undefined\n\n/**\n * @internal\n * @hidden\n */\nexport function getCurrentActionContext() {\n return currentActionContext\n}\n\n/**\n * @internal\n * @hidden\n */\nexport function getNextActionId() {\n return nextActionId++\n}\n\n// TODO: optimize away entire action context if there is no middleware in tree?\n/**\n * @internal\n * @hidden\n */\nexport function runWithActionContext(\n context: IMiddlewareEvent,\n fn: (...args: any[]) => any\n) {\n const node = getStateTreeNode(context.context)\n\n if (context.type === \"action\") {\n node.assertAlive({\n actionContext: context\n })\n }\n\n const baseIsRunningAction = node._isRunningAction\n node._isRunningAction = true\n const previousContext = currentActionContext\n currentActionContext = context\n try {\n return runMiddleWares(node, context, fn)\n } finally {\n currentActionContext = previousContext\n node._isRunningAction = baseIsRunningAction\n }\n}\n\n/**\n * @internal\n * @hidden\n */\nexport function getParentActionContext(\n parentContext: IMiddlewareEvent | undefined\n) {\n if (!parentContext) {\n return undefined\n }\n if (parentContext.type === \"action\") {\n return parentContext\n }\n return parentContext.parentActionEvent\n}\n\n/**\n * @internal\n * @hidden\n */\nexport function createActionInvoker<T extends FunctionWithFlag>(\n target: IAnyStateTreeNode,\n name: string,\n fn: T\n) {\n const res = function (...args: any[]) {\n const id = getNextActionId()\n const parentContext = currentActionContext\n const parentActionContext = getParentActionContext(parentContext)\n\n return runWithActionContext(\n {\n type: \"action\",\n name,\n id,\n args,\n context: target,\n tree: getRoot(target),\n rootId: parentContext ? parentContext.rootId : id,\n parentId: parentContext ? parentContext.id : 0,\n allParentIds: parentContext\n ? [...parentContext.allParentIds, parentContext.id]\n : [],\n parentEvent: parentContext,\n parentActionEvent: parentActionContext\n },\n fn\n )\n }\n ;(res as FunctionWithFlag)._isMSTAction = true\n ;(res as FunctionWithFlag)._isFlowAction = fn._isFlowAction\n return res\n}\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 */\nexport function addMiddleware(\n target: IAnyStateTreeNode,\n handler: IMiddlewareHandler,\n includeHooks = true\n): IDisposer {\n const node = getStateTreeNode(target)\n if (devMode()) {\n if (!node.isProtectionEnabled) {\n warnError(\n \"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/**\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 */\nexport function decorate<T extends (...args: any[]) => any>(\n handler: IMiddlewareHandler,\n fn: T,\n includeHooks = true\n): T {\n const middleware: IMiddleware = { handler, includeHooks }\n const f = fn as FunctionWithFlag\n if (!f.$mst_middleware) {\n f.$mst_middleware = []\n }\n f.$mst_middleware.push(middleware)\n return fn\n}\n\nclass CollectedMiddlewares {\n private arrayIndex = 0\n private inArrayIndex = 0\n private middlewares: IMiddleware[][] = []\n\n constructor(node: AnyObjectNode, fn: (...args: any[]) => any) {\n // we just push middleware arrays into an array of arrays to avoid making copies\n const mw = (fn as FunctionWithFlag).$mst_middleware\n if (mw) {\n this.middlewares.push(mw)\n }\n let n: AnyObjectNode | null = node\n // Find all middlewares. Optimization: cache this?\n while (n) {\n if (n.middlewares) {\n this.middlewares.push(n.middlewares)\n }\n n = n.parent\n }\n }\n\n get isEmpty() {\n return this.middlewares.length <= 0\n }\n\n getNextMiddleware(): IMiddleware | undefined {\n const array = this.middlewares[this.arrayIndex]\n if (!array) {\n return undefined\n }\n const item = array[this.inArrayIndex++]\n if (!item) {\n this.arrayIndex++\n this.inArrayIndex = 0\n return this.getNextMiddleware()\n }\n return item\n }\n}\n\nfunction runMiddleWares(\n node: AnyObjectNode,\n baseCall: IMiddlewareEvent,\n originalFn: (...args: any[]) => any\n): any {\n const middlewares = new CollectedMiddlewares(node, originalFn)\n // Short circuit\n if (middlewares.isEmpty) {\n return mobxAction(originalFn)(...baseCall.args)\n }\n\n let result: any = null\n\n function runNextMiddleware(call: IMiddlewareEvent): any {\n const middleware = middlewares.getNextMiddleware()\n const handler = middleware?.handler\n\n if (!handler) {\n return mobxAction(originalFn)(...call.args)\n }\n\n // skip hooks if asked to\n if (!middleware.includeHooks && call.name in Hook) {\n return runNextMiddleware(call)\n }\n\n let nextInvoked = false\n function next(\n call2: IMiddlewareEvent,\n callback?: (value: any) => any\n ): void {\n nextInvoked = true\n // the result can contain\n // - the non manipulated return value from an action\n // - the non manipulated abort value\n // - one of the above but manipulated through the callback function\n result = runNextMiddleware(call2)\n if (callback) {\n result = callback(result)\n }\n }\n\n let abortInvoked = false\n function abort(value: any) {\n abortInvoked = true\n // overwrite the result\n // can be manipulated through middlewares earlier in the queue using the callback fn\n result = value\n }\n\n handler(call, next, abort)\n if (devMode()) {\n if (!nextInvoked && !abortInvoked) {\n const node2 = getStateTreeNode(call.tree)\n throw fail(\n `Neither the next() nor the abort() callback within the middleware ${handler.name} for the action: \"${call.name}\" on the node: ${node2.type.name} was invoked.`\n )\n } else if (nextInvoked && abortInvoked) {\n const node2 = getStateTreeNode(call.tree)\n throw fail(\n `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 return runNextMiddleware(baseCall)\n}\n","import { type IAnyStateTreeNode, type IMiddlewareEvent } from \"../internal.ts\"\nimport { getCurrentActionContext } from \"./action.ts\"\n\nexport interface IActionContext {\n /** Event name (action name for actions) */\n readonly name: string\n\n /** Event unique id */\n readonly id: number\n\n /** Parent action event object */\n readonly parentActionEvent: IMiddlewareEvent | undefined\n\n /** Event context (node where the action was invoked) */\n readonly context: IAnyStateTreeNode\n /** Event tree (root node of the node where the action was invoked) */\n readonly tree: IAnyStateTreeNode\n\n /** Event arguments in an array (action arguments for actions) */\n readonly args: any[]\n}\n\n/**\n * Returns the currently executing MST action context, or undefined if none.\n */\nexport function getRunningActionContext(): IActionContext | undefined {\n let current = getCurrentActionContext()\n while (current && current.type !== \"action\") {\n current = current.parentActionEvent\n }\n return current\n}\n\nfunction _isActionContextThisOrChildOf(\n actionContext: IActionContext,\n sameOrParent: number | IActionContext | IMiddlewareEvent,\n includeSame: boolean\n) {\n const parentId =\n typeof sameOrParent === \"number\" ? sameOrParent : sameOrParent.id\n\n let current: IActionContext | IMiddlewareEvent | undefined = includeSame\n ? actionContext\n : actionContext.parentActionEvent\n while (current) {\n if (current.id === parentId) {\n return true\n }\n current = current.parentActionEvent\n }\n return false\n}\n\n/**\n * Returns if the given action context is a parent of this action context.\n */\nexport function isActionContextChildOf(\n actionContext: IActionContext,\n parent: number | IActionContext | IMiddlewareEvent\n) {\n return _isActionContextThisOrChildOf(actionContext, parent, false)\n}\n\n/**\n * Returns if the given action context is this or a parent of this action context.\n */\nexport function isActionContextThisOrChildOf(\n actionContext: IActionContext,\n parentOrThis: number | IActionContext | IMiddlewareEvent\n) {\n return _isActionContextThisOrChildOf(actionContext, parentOrThis, true)\n}\n","import {\n EMPTY_ARRAY,\n type ExtractCSTWithSTN,\n type IAnyType,\n fail,\n getStateTreeNode,\n isPrimitive,\n isPrimitiveType,\n isStateTreeNode,\n isTypeCheckingEnabled\n} from \"../../internal.ts\"\n\n/** Validation context entry, this is, where the validation should run against which type */\nexport interface IValidationContextEntry {\n /** Subpath where the validation should be run, or an empty string to validate it all */\n path: string\n /** Type to validate the subpath against */\n type: IAnyType\n}\n\n/** Array of validation context entries */\nexport type IValidationContext = IValidationContextEntry[]\n\n/** Type validation error */\nexport interface IValidationError {\n /** Validation context */\n context: IValidationContext\n /** Value that was being validated, either a snapshot or an instance */\n value: any\n /** Error message */\n message?: string | undefined\n}\n\n/** Type validation result, which is an array of type validation errors */\nexport type IValidationResult = ReadonlyArray<IValidationError>\n\nconst MAX_STRINGIFY_DEPTH = 3\nconst MAX_STRINGIFY_ARRAY_ITEMS = 10\nconst MAX_STRINGIFY_OBJECT_KEYS = 20\nconst MAX_STRINGIFY_STRING_LENGTH = 100\n\n// Recursively cap depth, array length, object key count, and string length so a\n// huge offending snapshot degrades into readable, bounded context instead of a\n// wall of text that then gets sliced mid-structure. The depth cap also bounds\n// recursion on circular structures.\nfunction truncateForStringify(value: any, depth: number): any {\n if (typeof value === \"string\") {\n return value.length > MAX_STRINGIFY_STRING_LENGTH\n ? `${value.substring(0, MAX_STRINGIFY_STRING_LENGTH)}… (${value.length - MAX_STRINGIFY_STRING_LENGTH} more characters)`\n : value\n }\n if (value === null || typeof value !== \"object\") {\n return value\n }\n if (depth >= MAX_STRINGIFY_DEPTH) {\n return Array.isArray(value) ? \"[…]\" : \"{…}\"\n }\n if (Array.isArray(value)) {\n const items = value\n .slice(0, MAX_STRINGIFY_ARRAY_ITEMS)\n .map(item => truncateForStringify(item, depth + 1))\n if (value.length > MAX_STRINGIFY_ARRAY_ITEMS) {\n items.push(`… ${value.length - MAX_STRINGIFY_ARRAY_ITEMS} more items`)\n }\n return items\n }\n const keys = Object.keys(value)\n const result: Record<string, any> = {}\n for (const key of keys.slice(0, MAX_STRINGIFY_OBJECT_KEYS)) {\n result[key] = truncateForStringify(value[key], depth + 1)\n }\n if (keys.length > MAX_STRINGIFY_OBJECT_KEYS) {\n result[\"…\"] = `${keys.length - MAX_STRINGIFY_OBJECT_KEYS} more keys`\n }\n return result\n}\n\nfunction safeStringify(value: any) {\n try {\n return JSON.stringify(truncateForStringify(value, 0))\n } catch (e) {\n // istanbul ignore next\n return `<Unserializable: ${e}>`\n }\n}\n\nfunction prettyPrintValue(value: any) {\n return typeof value === \"function\"\n ? `<function${value.name ? ` ${value.name}` : \"\"}>`\n : isStateTreeNode(value)\n ? `<${value}>`\n : `\\`${safeStringify(value)}\\``\n}\n\nfunction shortenPrintValue(valueInString: string) {\n return valueInString.length < 280\n ? valueInString\n : `${valueInString.substring(0, 272)}......${valueInString.substring(valueInString.length - 8)}`\n}\n\nfunction toErrorString(error: IValidationError): string {\n const { value } = error\n // every context entry carries a type: they are built by getContextForPath and\n // by typecheck's initial `[{ path: \"\", type }]`\n const type = error.context[error.context.length - 1]!.type\n const fullPath = error.context\n .map(({ path }) => path)\n .filter(path => path.length > 0)\n .join(\"/\")\n\n const pathPrefix = fullPath.length > 0 ? `at path \"/${fullPath}\" ` : ``\n\n const currentTypename = isStateTreeNode(value)\n ? `value of type ${getStateTreeNode(value).type.name}:`\n : isPrimitive(value)\n ? \"value\"\n : \"snapshot\"\n\n let expectation: string\n if (isPrimitiveType(type) || isPrimitive(value)) {\n expectation = \".\"\n } else {\n const isSnapshotCompatible =\n isStateTreeNode(value) && type.is(getStateTreeNode(value).snapshot)\n expectation = `, expected an instance of \\`${type.name}\\` or a snapshot like \\`${shortenPrintValue(\n type.describe()\n )}\\` instead.${\n isSnapshotCompatible\n ? \" (Note that a snapshot of the provided value is compatible with the targeted type)\"\n : \"\"\n }`\n }\n\n return `${pathPrefix}${currentTypename} ${shortenPrintValue(\n prettyPrintValue(value)\n )} is not assignable to type: \\`${type.name}\\`${\n error.message ? ` (${error.message})` : \"\"\n }${expectation}`\n}\n\n/**\n * @internal\n * @hidden\n * Pushes a new entry onto the context array (mutates in place for performance).\n * Returns the same context array for chaining.\n */\nexport function getContextForPath(\n context: IValidationContext,\n path: string,\n type: IAnyType\n): IValidationContext {\n context.push({ path, type })\n return context\n}\n\n/**\n * @internal\n * @hidden\n * Pops the last entry from the context array (mutates in place).\n * Must be called after validation to restore context state.\n */\nexport function popContext(context: IValidationContext): void {\n context.pop()\n}\n\n/**\n * @internal\n * @hidden\n */\nexport function typeCheckSuccess(): IValidationResult {\n return EMPTY_ARRAY\n}\n\n/**\n * @internal\n * @hidden\n */\nexport function typeCheckFailure(\n context: IValidationContext,\n value: any,\n message?: string\n): IValidationResult {\n // Clone context since it may be mutated after this error is created\n return [{ context: context.slice(), value, message }]\n}\n\n// TODO; doublecheck: typecheck should only needed to be invoked from: type.create and array / map / value.property will change\n/**\n * @internal\n * @hidden\n */\nexport function typecheckInternal<IT extends IAnyType>(\n type: IAnyType,\n value: ExtractCSTWithSTN<IT>\n): void {\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/**\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 */\nexport function typecheck<IT extends IAnyType>(\n type: IT,\n value: ExtractCSTWithSTN<IT>\n): void {\n const errors = type.validate(value, [{ path: \"\", type }])\n\n if (errors.length > 0) {\n throw fail(validationErrorsToString(type, value, errors))\n }\n}\n\nconst MAX_ERRORS_REPORTED = 10\n\n/**\n * @internal\n * @hidden\n * Format a list of validation errors as bullet-style lines, capped at\n * MAX_ERRORS_REPORTED entries with an overflow suffix. Shared by typecheck()\n * and union's `noMatchMessage` so prod-build union failures can include\n * candidate validation errors using the same formatting.\n */\nexport function formatValidationErrorLines(\n errors: ReadonlyArray<IValidationError>\n): string[] {\n const shown = errors.slice(0, MAX_ERRORS_REPORTED).map(toErrorString)\n const overflow = errors.length - shown.length\n if (overflow > 0) {\n shown.push(`(… and ${overflow} more error${overflow === 1 ? \"\" : \"s\"})`)\n }\n return shown\n}\n\nfunction validationErrorsToString<IT extends IAnyType>(\n type: IT,\n value: ExtractCSTWithSTN<IT>,\n errors: ReadonlyArray<IValidationError>\n): string | undefined {\n if (errors.length === 0) {\n return undefined\n }\n return `Error while converting ${shortenPrintValue(prettyPrintValue(value))} to \\`${\n type.name\n }\\`:\\n\\n ${formatValidationErrorLines(errors).join(\"\\n \")}`\n}\n","import { type IObservableArray, entries, observable, values } from \"mobx\"\n\nimport {\n type AnyObjectNode,\n type IAnyComplexType,\n type ObjectNode,\n fail,\n mobxShallow\n} from \"../../internal.ts\"\n\nlet identifierCacheId = 0\n\n/**\n * @internal\n * @hidden\n */\nexport class IdentifierCache {\n private cacheId = identifierCacheId++\n\n // n.b. in cache all identifiers are normalized to strings\n private cache = observable.map<string, IObservableArray<AnyObjectNode>>()\n\n // last time the cache (array) for a given time changed\n // n.b. it is not really the time, but just an integer that gets increased after each modification to the array\n private lastCacheModificationPerId = observable.map<string, number>()\n\n private updateLastCacheModificationPerId(identifier: string) {\n const lcm = this.lastCacheModificationPerId.get(identifier)\n // we start at 1 since 0 means no update since cache creation\n this.lastCacheModificationPerId.set(\n identifier,\n lcm === undefined ? 1 : lcm + 1\n )\n }\n\n getLastCacheModificationPerId(identifier: string): string {\n const modificationId = this.lastCacheModificationPerId.get(identifier) || 0\n return `${this.cacheId}-${modificationId}`\n }\n\n addNodeToCache(node: AnyObjectNode, lastCacheUpdate = true): void {\n if (node.identifierAttribute) {\n const identifier = node.identifier!\n // one observable-map read, not a has() plus a get(): this runs for every\n // identified node created\n let set = this.cache.get(identifier)\n if (!set) {\n set = observable.array<AnyObjectNode>([], mobxShallow)\n this.cache.set(identifier, set)\n }\n if (set.includes(node)) {\n throw fail(`Already registered`)\n }\n set.push(node)\n if (lastCacheUpdate) {\n this.updateLastCacheModificationPerId(identifier)\n }\n }\n }\n\n mergeCache(node: AnyObjectNode) {\n values(node.identifierCache!.cache).forEach(nodes =>\n nodes.forEach(child => {\n this.addNodeToCache(child)\n })\n )\n }\n\n notifyDied(node: AnyObjectNode) {\n if (node.identifierAttribute) {\n const id = node.identifier!\n const set = this.cache.get(id)\n if (set) {\n set.remove(node)\n // remove empty sets from cache\n if (!set.length) {\n this.cache.delete(id)\n }\n this.updateLastCacheModificationPerId(id)\n }\n }\n }\n\n splitCache(splitNode: AnyObjectNode): IdentifierCache {\n const newCache = new IdentifierCache()\n // The slash is added here so we only match children of the splitNode. In version 5.1.8 and\n // earlier there was no trailing slash, so non children that started with the same path string\n // were being matched incorrectly.\n const basePath = `${splitNode.path}/`\n entries(this.cache).forEach(([id, nodes]) => {\n let modified = false\n for (let i = nodes.length - 1; i >= 0; i--) {\n const node = nodes[i]!\n if (node === splitNode || node.path.startsWith(basePath)) {\n newCache.addNodeToCache(node, false) // no need to update lastUpdated since it is a whole new cache\n nodes.splice(i, 1)\n // remove empty sets from cache\n if (!nodes.length) {\n this.cache.delete(id)\n }\n modified = true\n }\n }\n if (modified) {\n this.updateLastCacheModificationPerId(id)\n }\n })\n return newCache\n }\n\n has(type: IAnyComplexType, identifier: string): boolean {\n const set = this.cache.get(identifier)\n if (!set) {\n return false\n }\n return set.some(candidate => type.isAssignableFrom(candidate.type))\n }\n\n resolve<IT extends IAnyComplexType>(\n type: IT,\n identifier: string\n ): ObjectNode<\n IT[\"CreationType\"],\n IT[\"SnapshotType\"],\n IT[\"TypeWithoutSTN\"]\n > | null {\n const set = this.cache.get(identifier)\n if (!set) {\n return null\n }\n const matches = set.filter(candidate =>\n type.isAssignableFrom(candidate.type)\n )\n switch (matches.length) {\n case 0:\n return null\n case 1:\n return matches[0]!\n default:\n throw fail(\n `Cannot resolve a reference to type '${\n type.name\n }' with id: '${identifier}' unambigously, there are multiple candidates: ${matches\n .map(n => n.path)\n .join(\", \")}`\n )\n }\n }\n}\n","import {\n type AnyNode,\n type AnyObjectNode,\n type ComplexType,\n ObjectNode,\n ScalarNode,\n type SimpleType,\n fail,\n getStateTreeNodeSafe\n} from \"../../internal.ts\"\n\n/**\n * @internal\n * @hidden\n */\nexport function createObjectNode<C, S, T>(\n type: ComplexType<C, S, T>,\n parent: AnyObjectNode | null,\n subpath: string,\n environment: any,\n initialValue: C | T\n): ObjectNode<C, S, T> {\n const existingNode = getStateTreeNodeSafe(initialValue)\n if (existingNode) {\n if (existingNode.parent) {\n // istanbul ignore next\n throw fail(\n `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 '${\n parent ? parent.path : \"\"\n }/${subpath}', but it lives already at '${existingNode.path}'`\n )\n }\n\n if (parent) {\n existingNode.setParent(parent, subpath)\n }\n // else it already has no parent since it is a pre-requisite\n\n return existingNode\n }\n\n // not a node, a snapshot\n return new ObjectNode(type, parent, subpath, environment, initialValue as C)\n}\n\n/**\n * @internal\n * @hidden\n */\nexport function createScalarNode<C, S, T>(\n type: SimpleType<C, S, T>,\n parent: AnyObjectNode | null,\n subpath: string,\n environment: any,\n initialValue: C\n): ScalarNode<C, S, T> {\n return new ScalarNode(type, parent, subpath, environment, initialValue)\n}\n\n/**\n * @internal\n * @hidden\n */\nexport function isNode(value: any): value is AnyNode {\n return value instanceof ScalarNode || value instanceof ObjectNode\n}\n","import {\n EMPTY_ARRAY,\n ObjectNode,\n ScalarNode,\n assertArg,\n fail,\n joinJsonPath,\n splitJsonPath\n} from \"../../internal.ts\"\n\nimport type {\n AnyNode,\n AnyObjectNode,\n IAnyComplexType,\n IAnyType,\n IChildNodesMap,\n IType,\n Instance,\n STNValue\n} from \"../../internal.ts\"\n\n/**\n * @internal\n * @hidden\n */\nexport enum NodeLifeCycle {\n INITIALIZING, // setting up\n CREATED, // afterCreate has run\n FINALIZED, // afterAttach has run\n DETACHING, // being detached from the tree\n DEAD // no coming back from this one\n}\n\n/**\n * Common interface that represents a node instance.\n * @hidden\n */\nexport interface IStateTreeNode<IT extends IAnyType = IAnyType> {\n /**\n * @internal\n */\n readonly $treenode?: any\n\n // Phantom property — never present at runtime, exists only so TypeScript can infer IT\n // via `T extends IStateTreeNode<infer IT>`. The [IT] | [any] tuple forces inference on\n // the concrete type while still allowing widening to IAnyType. A string key is used\n // instead of a unique symbol so tsgo can name the type in declaration files (TS4058).\n readonly $__mstStateTreeNodeType__?: [IT] | [any]\n}\n\n/** @hidden */\nexport type TypeOfValue<T extends IAnyStateTreeNode> =\n T extends IStateTreeNode<infer IT> ? IT : never\n\n/**\n * Represents any state tree node instance.\n * @hidden\n */\nexport interface IAnyStateTreeNode extends STNValue<any, IAnyType> {}\n\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 */\nexport function isStateTreeNode<IT extends IAnyComplexType = IAnyComplexType>(\n value: unknown\n): value is STNValue<Instance<IT>, IT> {\n return !!(value as IStateTreeNode | null | undefined)?.$treenode\n}\n\n/**\n * @internal\n * @hidden\n */\nexport function assertIsStateTreeNode(\n value: IAnyStateTreeNode,\n argNumber: number | number[]\n): void {\n assertArg(value, isStateTreeNode, \"mobx-state-tree node\", argNumber)\n}\n\n/**\n * @internal\n * @hidden\n */\nexport function getStateTreeNode(value: IAnyStateTreeNode): AnyObjectNode {\n if (!isStateTreeNode(value)) {\n // istanbul ignore next\n throw fail(`Value ${value} is no MST Node`)\n }\n return value.$treenode!\n}\n\n/**\n * @internal\n * @hidden\n */\nexport function getStateTreeNodeSafe(\n value: IAnyStateTreeNode\n): AnyObjectNode | null {\n return value?.[\"$treenode\"] || null\n}\n\n/**\n * @internal\n * @hidden\n */\nexport function toJSON<S>(this: IStateTreeNode<IType<any, S, any>>): S {\n return getStateTreeNode(this).snapshot\n}\n\nconst doubleDot = (_: any) => \"..\"\n\n/**\n * @internal\n * @hidden\n */\nexport function getRelativePathBetweenNodes(\n base: AnyObjectNode,\n target: AnyObjectNode\n): string {\n // PRE condition target is (a child of) base!\n if (base.root !== target.root) {\n throw fail(\n `Cannot calculate relative path: objects '${base}' and '${target}' are not part of the same object tree`\n )\n }\n\n const baseParts = splitJsonPath(base.path)\n const targetParts = splitJsonPath(target.path)\n let common = 0\n for (; common < baseParts.length; common++) {\n if (baseParts[common] !== targetParts[common]) {\n break\n }\n }\n // TODO: assert that no targetParts paths are \"..\", \".\" or \"\"!\n return (\n baseParts.slice(common).map(doubleDot).join(\"/\") +\n joinJsonPath(targetParts.slice(common))\n )\n}\n\n/**\n * @internal\n * @hidden\n */\nexport function resolveNodeByPath(\n base: AnyObjectNode,\n path: string,\n failIfResolveFails = true\n): AnyNode | undefined {\n return resolveNodeByPathParts(base, splitJsonPath(path), failIfResolveFails)\n}\n\n/**\n * @internal\n * @hidden\n */\nexport function resolveNodeByPathParts(\n base: AnyObjectNode,\n pathParts: string[],\n failIfResolveFails = true\n): AnyNode | undefined {\n let current: AnyNode | null = base\n try {\n for (let i = 0; i < pathParts.length; i++) {\n const part = pathParts[i]!\n if (part === \"..\") {\n current = current.parent\n if (current) {\n continue\n } // 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 const value: any = current.value\n if (isStateTreeNode(value)) {\n current = getStateTreeNode(value)\n // fall through\n }\n }\n if (current instanceof ObjectNode) {\n const subType = current.getChildType(part)\n if (subType) {\n current = current.getChildNode(part)\n if (current) {\n continue\n }\n }\n }\n }\n throw fail(\n `Could not resolve '${part}' in path '${\n joinJsonPath(pathParts.slice(0, i)) || \"/\"\n }' while resolving '${joinJsonPath(pathParts)}'`\n )\n }\n } catch (e) {\n if (!failIfResolveFails) {\n return undefined\n }\n throw e\n }\n return current\n}\n\n/**\n * @internal\n * @hidden\n */\nexport function convertChildNodesToArray(\n childNodes: IChildNodesMap | null\n): ReadonlyArray<AnyNode> {\n if (!childNodes) {\n return EMPTY_ARRAY\n }\n\n const result = Object.values(childNodes)\n return result.length ? result : EMPTY_ARRAY\n}\n","import {\n defineProperty as mobxDefineProperty,\n isObservableArray,\n isObservableObject\n} from \"mobx\"\n\nimport type { Primitives } from \"./core/type/type.ts\"\n\nconst plainObjectString = Object.toString()\n\n/**\n * @internal\n * @hidden\n */\nexport const EMPTY_ARRAY: readonly never[] = Object.freeze([])\n\n/**\n * @internal\n * @hidden\n */\n\nexport const EMPTY_OBJECT: {} = Object.freeze({})\n\n/**\n * @internal\n * @hidden\n */\nexport const mobxShallow = { deep: false } as const\nObject.freeze(mobxShallow)\n\n/**\n * A generic disposer.\n */\nexport type IDisposer = () => void\n\n/**\n * @internal\n * @hidden\n */\nexport function fail(message = \"Illegal state\"): Error {\n return new Error(`[mobx-state-tree] ${message}`)\n}\n\n/**\n * @internal\n * @hidden\n */\nexport function identity(_: any): any {\n return _\n}\n\n/**\n * @internal\n * @hidden\n */\nexport const isInteger = Number.isInteger\n\n/**\n * @internal\n * @hidden\n */\nexport function isFloat(val: any) {\n return Number(val) === val && val % 1 !== 0\n}\n\n/**\n * @internal\n * @hidden\n */\nexport function isFinite(val: any) {\n return Number.isFinite(val)\n}\n\n/**\n * @internal\n * @hidden\n */\nexport function isArray(val: unknown): val is any[] {\n return Array.isArray(val) || isObservableArray(val)\n}\n\n/**\n * @internal\n * @hidden\n */\nexport function asArray<T>(\n val: undefined | null | T | T[] | ReadonlyArray<T>\n): ReadonlyArray<T> {\n if (!val) {\n return EMPTY_ARRAY\n }\n if (isArray(val)) {\n return val\n }\n return [val] as T[]\n}\n\n/**\n * @internal\n * @hidden\n */\nexport function isPlainObject(value: unknown): value is { [k: string]: any } {\n if (value === null || typeof value !== \"object\") {\n return false\n }\n const proto = Object.getPrototypeOf(value)\n // Fast path for an object literal from this realm — nearly every snapshot MST\n // inspects. The fallback compares the constructor's *source text* so that an\n // `Object` from another realm (iframe, vm context) still counts as plain; it\n // is ~6x slower, so only cross-realm and null-prototype values pay for it.\n if (proto === Object.prototype || proto == null) {\n return true\n }\n return proto.constructor?.toString() === plainObjectString\n}\n\n/**\n * @internal\n * @hidden\n */\nexport function isMutable(value: unknown) {\n return (\n value !== null &&\n typeof value === \"object\" &&\n !(value instanceof Date) &&\n !(value instanceof RegExp)\n )\n}\n\n/**\n * @internal\n * @hidden\n */\nexport function isPrimitive(\n value: unknown,\n includeDate = true\n): value is Primitives {\n return (\n value === null ||\n value === undefined ||\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"boolean\" ||\n (includeDate && value instanceof Date)\n )\n}\n\n/**\n * @internal\n * @hidden\n * Freeze a value and return it (if not in production)\n */\nexport function freeze<T>(value: T): T {\n if (!devMode()) {\n return value\n }\n return isPrimitive(value) || isObservableArray(value)\n ? value\n : Object.freeze(value)\n}\n\n/**\n * @internal\n * @hidden\n * Recursively freeze a value (if not in production)\n */\nexport function deepFreeze<T>(value: T): T {\n if (devMode()) {\n freeze(value)\n if (isPlainObject(value)) {\n for (const v of Object.values(value)) {\n if (!isPrimitive(v) && !Object.isFrozen(v)) {\n deepFreeze(v)\n }\n }\n }\n }\n return value\n}\n\n/**\n * @internal\n * @hidden\n */\nexport function isSerializable(value: any) {\n return typeof value !== \"function\"\n}\n\n/**\n * @internal\n * @hidden\n */\nexport function defineProperty(\n object: any,\n key: PropertyKey,\n descriptor: PropertyDescriptor\n) {\n if (isObservableObject(object)) {\n mobxDefineProperty(object, key, descriptor)\n } else {\n Object.defineProperty(object, key, descriptor)\n }\n}\n\n/**\n * @internal\n * @hidden\n */\nexport function addHiddenFinalProp(object: any, propName: string, value: any) {\n defineProperty(object, propName, {\n enumerable: false,\n writable: false,\n configurable: true,\n value\n })\n}\n\n/**\n * @internal\n * @hidden\n */\nexport function addHiddenWritableProp(\n object: any,\n propName: string,\n value: any\n) {\n defineProperty(object, propName, {\n enumerable: false,\n writable: true,\n configurable: true,\n value\n })\n}\n\n/**\n * @internal\n * @hidden\n */\nexport type ArgumentTypes<F extends (...args: any[]) => any> = F extends (\n ...args: infer A\n) => any\n ? A\n : never\n\n/**\n * @internal\n * @hidden\n */\nclass EventHandler<F extends (...args: any[]) => any> {\n private handlers: F[] = []\n\n get hasSubscribers(): boolean {\n return this.handlers.length > 0\n }\n\n register(fn: F, atTheBeginning = false): IDisposer {\n if (atTheBeginning) {\n this.handlers.unshift(fn)\n } else {\n this.handlers.push(fn)\n }\n return () => {\n this.unregister(fn)\n }\n }\n\n has(fn: F): boolean {\n return this.handlers.includes(fn)\n }\n\n unregister(fn: F) {\n const index = this.handlers.indexOf(fn)\n if (index >= 0) {\n this.handlers.splice(index, 1)\n }\n }\n\n emit(...args: ArgumentTypes<F>) {\n const handlers = this.handlers\n // 0 and 1 handlers are by far the common cases (a patch/snapshot listener, a\n // disposer) and need no copy: with a single handler, calling the value we\n // already read is exactly what iterating a copy of it would do.\n if (handlers.length <= 1) {\n handlers[0]?.(...args)\n return\n }\n // otherwise iterate a copy so (un)registrations during emit don't disturb\n // this pass and reentrant emits stay correct\n for (const f of handlers.slice()) {\n f(...args)\n }\n }\n}\n\n/**\n * @internal\n * @hidden\n */\nexport class EventHandlers<E extends { [k: string]: (...args: any[]) => any }> {\n private eventHandlers?:\n | {\n [k in keyof E]?: EventHandler<E[k]>\n }\n | undefined\n\n hasSubscribers(event: keyof E): boolean {\n return this.eventHandlers?.[event]?.hasSubscribers ?? false\n }\n\n register<N extends keyof E>(\n event: N,\n fn: E[N],\n atTheBeginning = false\n ): IDisposer {\n if (!this.eventHandlers) {\n this.eventHandlers = {}\n }\n let handler = this.eventHandlers[event]\n if (!handler) {\n handler = this.eventHandlers[event] = new EventHandler()\n }\n return handler.register(fn, atTheBeginning)\n }\n\n has<N extends keyof E>(event: N, fn: E[N]): boolean {\n return this.eventHandlers?.[event]?.has(fn) ?? false\n }\n\n unregister<N extends keyof E>(event: N, fn: E[N]) {\n const handler = this.eventHandlers?.[event]\n if (handler) {\n handler.unregister(fn)\n }\n }\n\n clear<N extends keyof E>(event: N) {\n if (this.eventHandlers) {\n delete this.eventHandlers[event]\n }\n }\n\n clearAll() {\n this.eventHandlers = undefined\n }\n\n emit<N extends keyof E>(event: N, ...args: ArgumentTypes<E[N]>) {\n const handler = this.eventHandlers?.[event]\n if (handler) {\n handler.emit(...args)\n }\n }\n}\n\n/**\n * @internal\n * @hidden\n */\nexport function warnError(msg: string) {\n console.warn(new Error(`[mobx-state-tree] ${msg}`))\n}\nlet _typeChecking: boolean | undefined\n\n/**\n * Forces full run-time type-checking on or off, overriding the dev-mode and\n * `ENABLE_TYPE_CHECK` env-var defaults. Pass `true` to get better error messages\n * in production builds without relying on an environment variable, `false` to\n * force it off, or `undefined` to restore the default behavior.\n */\nexport function setTypeChecking(enabled: boolean | undefined) {\n _typeChecking = enabled\n}\n\n// the ENABLE_TYPE_CHECK env var is fixed at process start, so read it once:\n// process.env access is a comparatively expensive lookup and isTypeCheckingEnabled\n// runs on every create() / typed write. The setTypeChecking() override and\n// dev-mode default stay live below.\nconst _envTypeCheck =\n typeof process !== \"undefined\" && process.env?.ENABLE_TYPE_CHECK === \"true\"\n\n/**\n * @internal\n * @hidden\n */\nexport function isTypeCheckingEnabled() {\n // an explicit setTypeChecking() override (incl. `false`) wins over the\n // dev-mode / env-var default, hence ?? rather than ||\n return _typeChecking ?? (devMode() || _envTypeCheck)\n}\n\nlet _devMode = process.env.NODE_ENV !== \"production\"\n\n/**\n * @internal\n * @hidden\n */\nexport function devMode() {\n return _devMode\n}\n\n/**\n * @internal\n * @hidden\n */\nexport function setDevMode(value: boolean) {\n _devMode = value\n}\n\n/**\n * @internal\n * @hidden\n */\nexport function assertArg<T>(\n value: T,\n fn: (value: T) => boolean,\n typeName: string,\n argNumber: number | number[]\n) {\n if (devMode()) {\n if (!fn(value)) {\n // istanbul ignore next\n throw fail(\n `expected ${typeName} as argument ${asArray(argNumber).join(\" or \")}, got ${value} instead`\n )\n }\n }\n}\n\n/**\n * @internal\n * @hidden\n */\nexport function assertIsFunction(\n value: (...args: any[]) => any,\n argNumber: number | number[]\n) {\n assertArg(value, fn => typeof fn === \"function\", \"function\", argNumber)\n}\n\n/**\n * @internal\n * @hidden\n */\nexport function assertIsNumber(\n value: number,\n argNumber: number | number[],\n min?: number,\n max?: number\n) {\n assertArg(value, n => typeof n === \"number\", \"number\", argNumber)\n if (min !== undefined) {\n assertArg(value, n => n >= min, `number greater than ${min}`, argNumber)\n }\n if (max !== undefined) {\n assertArg(value, n => n <= max, `number lesser than ${max}`, argNumber)\n }\n}\n\n/**\n * @internal\n * @hidden\n */\nexport function assertIsString(\n value: string,\n argNumber: number | number[],\n canBeEmpty = true\n) {\n assertArg(value, s => typeof s === \"string\", \"string\", argNumber)\n if (!canBeEmpty) {\n assertArg(value, s => s !== \"\", \"not empty string\", argNumber)\n }\n}\n","import { fail } from \"../utils.ts\"\nimport {\n getCurrentActionContext,\n getNextActionId,\n getParentActionContext,\n runWithActionContext\n} from \"./action.ts\"\n\nimport type { FunctionWithFlag, IMiddlewareEventType } from \"./action.ts\"\n\n/**\n * @hidden\n */\nexport type FlowReturn<R> = R extends Promise<infer T> ? T : R\n\n/**\n * See [asynchronous actions](concepts/async-actions.md).\n *\n * @returns The flow as a promise.\n */\nexport function flow<R, Args extends any[]>(\n generator: (...args: Args) => Generator<PromiseLike<any>, R, any>\n): (...args: Args) => Promise<FlowReturn<R>> {\n return createFlowSpawner(generator.name, generator) as any\n}\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 */\nexport function castFlowReturn<T>(val: T): T {\n return val\n}\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<number> { ... }\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 */\nexport function toGeneratorFunction<R, Args extends any[]>(\n p: (...args: Args) => Promise<R>\n) {\n return function* (...args: Args) {\n return (yield p(...args)) as R\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<number> { ... }\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 */\nexport function* toGenerator<R>(p: Promise<R>) {\n return (yield p) as R\n}\n\nfunction createFlowSpawner(name: string, generator: FunctionWithFlag) {\n const spawner = function flowSpawner(this: any, ...flowArgs: any[]) {\n // Implementation based on https://github.com/tj/co/blob/master/index.js\n const runId = getNextActionId()\n // no `!`: the guard below is the point, and asserting non-null first made it\n // dead to the checker while leaving it live at runtime\n const parentContext = getCurrentActionContext()\n if (!parentContext) {\n throw fail(\"a mst flow must always have a parent context\")\n }\n const parentActionContext = getParentActionContext(parentContext)\n if (!parentActionContext) {\n throw fail(\"a mst flow must always have a parent action context\")\n }\n\n const contextBase = {\n name,\n id: runId,\n tree: parentContext.tree,\n context: parentContext.context,\n parentId: parentContext.id,\n allParentIds: [...parentContext.allParentIds, parentContext.id],\n rootId: parentContext.rootId,\n parentEvent: parentContext,\n parentActionEvent: parentActionContext\n }\n\n const spawnerWithMw = spawner as FunctionWithFlag\n\n function wrap(fn: FunctionWithFlag, type: IMiddlewareEventType, arg: any) {\n fn.$mst_middleware = spawnerWithMw.$mst_middleware // pick up any middleware attached to the flow\n return runWithActionContext(\n {\n ...contextBase,\n type,\n args: [arg]\n },\n fn\n )\n }\n\n return new Promise(function (resolve, reject) {\n let gen: Generator<PromiseLike<unknown>, unknown, unknown>\n const init = function asyncActionInit(...initArgs: any[]) {\n gen = generator(...initArgs)\n onFulfilled(undefined) // kick off the flow\n } as FunctionWithFlag\n init.$mst_middleware = spawnerWithMw.$mst_middleware\n\n runWithActionContext(\n {\n ...contextBase,\n type: \"flow_spawn\",\n args: flowArgs\n },\n init\n )\n\n function onFulfilled(res: any) {\n let ret\n try {\n // prettier-ignore\n const cancelError: any = wrap((_r: any) => { ret = gen.next(_r) }, \"flow_resume\", res)\n if (cancelError instanceof Error) {\n ret = gen.throw(cancelError)\n }\n } catch (e) {\n // prettier-ignore\n queueMicrotask(() => {\n wrap((_r: any) => { reject(e) }, \"flow_throw\", e)\n })\n return\n }\n next(ret)\n return\n }\n\n function onRejected(err: any) {\n let ret\n try {\n // prettier-ignore\n wrap((_r: any) => { ret = gen.throw(_r) }, \"flow_resume_error\", err) // or yieldError?\n } catch (e) {\n // prettier-ignore\n queueMicrotask(() => {\n wrap((_r: any) => { reject(e) }, \"flow_throw\", e)\n })\n return\n }\n next(ret)\n }\n\n function next(ret: any) {\n if (ret.done) {\n // prettier-ignore\n queueMicrotask(() => {\n wrap((r: any) => { resolve(r) }, \"flow_return\", ret.value)\n })\n return\n }\n // TODO: support more type of values? See https://github.com/tj/co/blob/249bbdc72da24ae44076afd716349d2089b31c4c/index.js#L100\n if (!ret.value || typeof ret.value.then !== \"function\") {\n // istanbul ignore next\n throw fail(`Only promises can be yielded to \\`async\\`, got: ${ret}`)\n }\n return ret.value.then(onFulfilled, onRejected)\n }\n })\n }\n ;(spawner as FunctionWithFlag)._isFlowAction = true\n return spawner\n}\n","import { fail } from \"../internal.ts\"\n\n/**\n * https://tools.ietf.org/html/rfc6902\n * http://jsonpatch.com/\n */\nexport interface IJsonPatch {\n readonly op: \"replace\" | \"add\" | \"remove\"\n readonly path: string\n readonly value?: any\n}\n\nexport interface IReversibleJsonPatch extends IJsonPatch {\n readonly oldValue: any // This goes beyond JSON-patch, but makes sure each patch can be inverse applied\n}\n\n/**\n * @internal\n * @hidden\n */\nexport function splitPatch(\n patch: IReversibleJsonPatch\n): [IJsonPatch, IJsonPatch] {\n if (!(\"oldValue\" in patch)) {\n throw fail(`Patches without \\`oldValue\\` field cannot be inversed`)\n }\n return [stripPatch(patch), invertPatch(patch)]\n}\n\nfunction stripPatch(patch: IReversibleJsonPatch): IJsonPatch {\n // strips `oldvalue` information from the patch, so that it becomes a patch conform the json-patch spec\n // this removes the ability to undo the patch\n switch (patch.op) {\n case \"add\":\n return { op: \"add\", path: patch.path, value: patch.value }\n case \"remove\":\n return { op: \"remove\", path: patch.path }\n case \"replace\":\n return { op: \"replace\", path: patch.path, value: patch.value }\n }\n}\n\nfunction invertPatch(patch: IReversibleJsonPatch): IJsonPatch {\n switch (patch.op) {\n case \"add\":\n return {\n op: \"remove\",\n path: patch.path\n }\n case \"remove\":\n return {\n op: \"add\",\n path: patch.path,\n value: patch.oldValue\n }\n case \"replace\":\n return {\n op: \"replace\",\n path: patch.path,\n value: patch.oldValue\n }\n }\n}\n\n/**\n * Escape slashes and backslashes.\n *\n * http://tools.ietf.org/html/rfc6901\n */\nexport function escapeJsonPath(path: string): string {\n if (!path.includes(\"/\") && !path.includes(\"~\")) {\n return path\n }\n return path.replace(/~/g, \"~0\").replace(/\\//g, \"~1\")\n}\n\n/**\n * Unescape slashes and backslashes.\n */\nexport function unescapeJsonPath(path: string): string {\n // every escape sequence starts with `~`, so bail before the two regex passes\n // for the overwhelmingly common unescaped part (mirrors escapeJsonPath above)\n if (!path.includes(\"~\")) {\n return path\n }\n return path.replace(/~1/g, \"/\").replace(/~0/g, \"~\")\n}\n\n/**\n * Generates a json-path compliant json path from path parts.\n *\n * @param path\n * @returns\n */\nexport function joinJsonPath(path: string[]): string {\n // `/` refers to property with an empty name, while `` refers to root itself!\n if (path.length === 0) {\n return \"\"\n }\n\n const getPathStr = (p: string[]) => p.map(escapeJsonPath).join(\"/\")\n if (path[0] === \".\" || path[0] === \"..\") {\n // relative\n return getPathStr(path)\n } else {\n // absolute\n return `/${getPathStr(path)}`\n }\n}\n\n/**\n * Splits and decodes a json path into several parts.\n *\n * @param path\n * @returns\n */\nexport function splitJsonPath(path: string): string[] {\n // `/` refers to property with an empty name, while `` refers to root itself!\n const parts = path.split(\"/\").map(unescapeJsonPath)\n\n const valid =\n path === \"\" ||\n path === \".\" ||\n path === \"..\" ||\n path.startsWith(\"/\") ||\n path.startsWith(\"./\") ||\n path.startsWith(\"../\")\n if (!valid) {\n throw fail(\n `a json path must be either rooted, empty or relative, but got '${path}'`\n )\n }\n\n // '/a/b/c' -> [\"a\", \"b\", \"c\"]\n // '../../b/c' -> [\"..\", \"..\", \"b\", \"c\"]\n // '' -> []\n // '/' -> ['']\n // './a' -> [\".\", \"a\"]\n // /./a' -> [\".\", \"a\"] equivalent to './a'\n\n if (parts[0] === \"\") {\n parts.shift()\n }\n return parts\n}\n","import {\n type AnyObjectNode,\n BaseType,\n ComplexType,\n type ExtractNodeType,\n type IAnyType,\n type Instance,\n type IType,\n type IValidationContext,\n type IValidationResult,\n ObjectNode,\n TypeFlags,\n assertIsType,\n devMode,\n fail,\n getSnapshot,\n isStateTreeNode,\n isType,\n isUnionType,\n typeCheckFailure\n} from \"../../internal.ts\"\n\n/** @hidden */\ndeclare const $mstNotCustomized: unique symbol\n\n/** @hidden */\nconst $preProcessorFailed: unique symbol = Symbol(\"$preProcessorFailed\")\n\n/** @hidden */\nexport interface _NotCustomized {\n // only for typings\n readonly [$mstNotCustomized]: undefined\n}\n/** @hidden */\nexport type _CustomOrOther<Custom, Other> = Custom extends _NotCustomized\n ? Other\n : Custom\n\nclass SnapshotProcessor<IT extends IAnyType, CustomC, CustomS> extends BaseType<\n _CustomOrOther<CustomC, IT[\"CreationType\"]>,\n _CustomOrOther<CustomS, IT[\"SnapshotType\"]>,\n IT[\"TypeWithoutSTN\"],\n ExtractNodeType<IT>\n> {\n private _flags?: TypeFlags\n\n // memoized once stable; see the guard on Union.flags\n get flags(): TypeFlags {\n const cached = this._flags\n if (cached !== undefined) {\n return cached\n }\n const result = this._subtype.flags | TypeFlags.SnapshotProcessor\n if (!(result & TypeFlags.Late)) {\n this._flags = result\n }\n return result\n }\n\n constructor(\n private readonly _subtype: IT,\n private readonly _processors: ISnapshotProcessors<IT, CustomC, CustomS>,\n name?: string\n ) {\n // `|| undefined`, so an empty name still falls through to the subtype's, as\n // it did when this read `name || _subtype.name`. Passing `\"\"` straight to\n // `super` would keep it: `_name ??= computeName()` only fills a nullish one.\n super(name || undefined)\n }\n\n protected override computeName(): string {\n return this._subtype.name\n }\n\n override describe() {\n return `snapshotProcessor(${this._subtype.describe()})`\n }\n\n private preProcessSnapshot(sn: this[\"C\"]): IT[\"CreationType\"] {\n if (this._processors.preProcessor) {\n return this._processors.preProcessor.call(null, sn)\n }\n return sn\n }\n\n private preProcessSnapshotSafe(\n sn: this[\"C\"]\n ): IT[\"CreationType\"] | typeof $preProcessorFailed {\n try {\n return this.preProcessSnapshot(sn)\n } catch (_e) {\n return $preProcessorFailed\n }\n }\n\n private postProcessSnapshot(\n sn: IT[\"SnapshotType\"],\n node: this[\"N\"]\n ): this[\"S\"] {\n if (this._processors.postProcessor) {\n return this._processors.postProcessor.call(\n null,\n sn,\n node.storedValue\n ) as any\n }\n return sn\n }\n\n private _fixNode(node: this[\"N\"]): void {\n // the node's type is the *inner* type, so `getType(instance).create(...)`\n // would bypass the processors — point it at ours instead\n const nodeType = node.type as { create: (...args: any[]) => any }\n nodeType.create = this.create.bind(this)\n\n if (node instanceof ObjectNode) {\n node.hasSnapshotPostProcessor = !!this._processors.postProcessor\n }\n const oldGetSnapshot = node.getSnapshot\n node.getSnapshot = () =>\n this.postProcessSnapshot(oldGetSnapshot.call(node), node) as any\n // getSnapshot was just rewritten; refresh any snapshot already memoized for\n // this node (e.g. it was serialized before being moved under this processor)\n if (node instanceof ObjectNode) {\n node.refreshMemoizedSnapshot()\n }\n if (!isUnionType(this._subtype)) {\n node.getReconciliationType = () => {\n return this\n }\n }\n }\n\n instantiate(\n parent: AnyObjectNode | null,\n subpath: string,\n environment: any,\n initialValue: this[\"C\"] | this[\"T\"]\n ): this[\"N\"] {\n const processedInitialValue = isStateTreeNode(initialValue)\n ? initialValue\n : this.preProcessSnapshot(initialValue)\n const node = this._subtype.instantiate(\n parent,\n subpath,\n environment,\n processedInitialValue\n ) as any\n this._fixNode(node)\n return node\n }\n\n reconcile(\n current: this[\"N\"],\n newValue: this[\"C\"] | this[\"T\"],\n parent: AnyObjectNode,\n subpath: string\n ): this[\"N\"] {\n const node = this._subtype.reconcile(\n current,\n isStateTreeNode(newValue) ? newValue : this.preProcessSnapshot(newValue),\n parent,\n subpath\n ) as any\n if (node !== current) {\n this._fixNode(node)\n }\n return node\n }\n\n override getSnapshot(node: this[\"N\"], applyPostProcess = true): this[\"S\"] {\n const sn = this._subtype.getSnapshot(node)\n return applyPostProcess ? this.postProcessSnapshot(sn, node) : sn\n }\n\n isValidSnapshot(\n value: this[\"C\"],\n context: IValidationContext\n ): IValidationResult {\n const processedSn = this.preProcessSnapshotSafe(value)\n if (processedSn === $preProcessorFailed) {\n return typeCheckFailure(context, value, \"Failed to preprocess value\")\n }\n return this._subtype.validate(processedSn, context)\n }\n\n getSubTypes() {\n return this._subtype\n }\n\n override is(thing: unknown): thing is any {\n const value = isType(thing)\n ? this._subtype\n : isStateTreeNode(thing)\n ? getSnapshot(thing, false)\n : this.preProcessSnapshotSafe(thing as this[\"C\"])\n if (value === $preProcessorFailed) {\n return false\n }\n return (\n this._subtype.validate(value, [{ path: \"\", type: this._subtype }])\n .length === 0\n )\n }\n\n override isAssignableFrom(type: IAnyType): boolean {\n return this._subtype.isAssignableFrom(type)\n }\n\n isMatchingSnapshotId(current: this[\"N\"], snapshot: this[\"C\"]): boolean {\n if (!(this._subtype instanceof ComplexType)) {\n return false\n }\n const processedSn = this.preProcessSnapshot(snapshot)\n return this._subtype.isMatchingSnapshotId(current as any, processedSn)\n }\n}\n\n// public API\n\n/**\n * A type that has its snapshots processed.\n */\nexport interface ISnapshotProcessor<\n IT extends IAnyType,\n CustomC,\n CustomS\n> extends IType<\n _CustomOrOther<CustomC, IT[\"CreationType\"]>,\n _CustomOrOther<CustomS, IT[\"SnapshotType\"]>,\n IT[\"TypeWithoutSTN\"]\n> {}\n\n/**\n * Snapshot processors.\n */\nexport interface ISnapshotProcessors<IT extends IAnyType, CustomC, CustomS> {\n /**\n * Function that transforms an input snapshot.\n *\n * The processor may return the loose input (`CustomC`) as well as the strict\n * creation type: migrations commonly massage an untyped legacy record and\n * rely on MST's runtime revalidation/defaults to fill the rest. This mirrors\n * the lenient return type of `IModelType.preProcessSnapshot`.\n */\n preProcessor?(snapshot: CustomC): IT[\"CreationType\"] | CustomC\n /**\n * Function that transforms an output snapshot.\n * @param snapshot\n */\n postProcessor?(snapshot: IT[\"SnapshotType\"], node: Instance<IT>): CustomS\n}\n\n/**\n * `types.snapshotProcessor` - Runs a pre/post snapshot processor before/after serializing a given type.\n *\n * Example:\n * ```ts\n * const Todo1 = types.model({ text: types.string })\n * // in the backend the text type must be null when empty\n * interface BackendTodo {\n * text: string | null\n * }\n *\n * const Todo2 = types.snapshotProcessor(Todo1, {\n * // from snapshot to instance\n * preProcessor(snapshot: BackendTodo) {\n * return {\n * text: sn.text || \"\";\n * }\n * },\n *\n * // from instance to snapshot\n * postProcessor(snapshot, node): BackendTodo {\n * return {\n * text: !sn.text ? null : sn.text\n * }\n * }\n * })\n * ```\n *\n * @param type Type to run the processors over.\n * @param processors Processors to run.\n * @param name Type name, or undefined to inherit the inner type one.\n * @returns\n */\nexport function snapshotProcessor<\n IT extends IAnyType,\n CustomC = _NotCustomized,\n CustomS = _NotCustomized\n>(\n type: IT,\n processors: ISnapshotProcessors<IT, CustomC, CustomS>,\n name?: string\n): ISnapshotProcessor<IT, CustomC, CustomS> {\n assertIsType(type, 1)\n if (devMode()) {\n if (\n processors.postProcessor &&\n typeof processors.postProcessor !== \"function\"\n ) {\n // istanbul ignore next\n throw fail(\"postSnapshotProcessor must be a function\")\n }\n if (\n processors.preProcessor &&\n typeof processors.preProcessor !== \"function\"\n ) {\n // istanbul ignore next\n throw fail(\"preSnapshotProcessor must be a function\")\n }\n }\n\n return new SnapshotProcessor(type, processors, name)\n}\n","import {\n EMPTY_ARRAY,\n type IHooksGetter,\n addHiddenFinalProp,\n addHiddenWritableProp,\n createActionInvoker,\n devMode\n} from \"../../internal.ts\"\n\n/**\n * Shared backing for `types.array(...).hooks(fn)` / `types.map(...).hooks(fn)`:\n * both collection types keep a list of hook getters on the type and install the\n * returned lifecycle hooks as actions on each instance.\n *\n * @internal\n * @hidden\n */\nexport type HookInitializers<T> = ReadonlyArray<IHooksGetter<T>>\n\n/**\n * Append `hooks` to a collection type's initializer list. `EMPTY_ARRAY` is the\n * shared default, so a type that never calls `.hooks()` allocates nothing.\n *\n * @internal\n * @hidden\n */\nexport function appendHookInitializer<T>(\n current: HookInitializers<T>,\n hooks: IHooksGetter<T>\n): HookInitializers<T> {\n return current.length > 0 ? [...current, hooks] : [hooks]\n}\n\n/**\n * Install every hook the type's initializers produce onto `instance` as an MST\n * action, mirroring how a model's `.actions()` members are attached.\n *\n * @internal\n * @hidden\n */\nexport function installHookInitializers<T>(\n hookInitializers: HookInitializers<T>,\n instance: T\n): void {\n const addProp = !devMode() ? addHiddenFinalProp : addHiddenWritableProp\n for (const initializer of hookInitializers) {\n const hooks = initializer(instance)\n for (const name of Object.keys(hooks)) {\n const hook = hooks[name as keyof typeof hooks]!\n addProp(instance, name, createActionInvoker(instance, name, hook))\n }\n }\n}\n\n/**\n * The empty initializer list every collection type starts with.\n *\n * @internal\n * @hidden\n */\nexport const NO_HOOK_INITIALIZERS = EMPTY_ARRAY as HookInitializers<any>\n","import {\n type IInterceptor,\n type IKeyValueMap,\n type IMapDidChange,\n type IMapWillChange,\n type Lambda,\n ObservableMap,\n _interceptReads,\n action,\n intercept,\n observe,\n values\n} from \"mobx\"\n\nimport {\n type AnyNode,\n type AnyObjectNode,\n ComplexType,\n EMPTY_OBJECT,\n type ExtractCSTWithSTN,\n type HookInitializers,\n type IAnyModelType,\n type IAnyStateTreeNode,\n type IAnyType,\n type IChildNodesMap,\n type IHooksGetter,\n type IJsonPatch,\n type IType,\n type IValidationContext,\n type IValidationResult,\n ModelType,\n NO_HOOK_INITIALIZERS,\n ObjectNode,\n TypeFlags,\n appendHookInitializer,\n asArray,\n assertIsType,\n cannotDetermineSubtype,\n createObjectNode,\n devMode,\n escapeJsonPath,\n fail,\n getContextForPath,\n getSnapshot,\n getStateTreeNode,\n installHookInitializers,\n isMutable,\n isPlainObject,\n isStateTreeNode,\n isType,\n isValidIdentifier,\n normalizeIdentifier,\n popContext,\n typeCheckFailure,\n typeCheckSuccess,\n typecheckInternal\n} from \"../../internal.ts\"\n\n/** @hidden */\nexport interface IMapType<IT extends IAnyType> extends IType<\n IKeyValueMap<IT[\"CreationType\"]> | undefined,\n IKeyValueMap<IT[\"SnapshotType\"]>,\n IMSTMap<IT>\n> {\n hooks(hooks: IHooksGetter<IMSTMap<IT>>): IMapType<IT>\n /** the value type of the map */\n getChildType(): IAnyType\n}\n\n/**\n * The forms `merge` and `replace` accept, mirroring mobx's\n * `IObservableMapInitialValues` with MST's snapshot-or-instance value type.\n */\ntype IMSTMapInitialValues<IT extends IAnyType> =\n | IMSTMap<IType<any, any, IT[\"TypeWithoutSTN\"]>>\n | IKeyValueMap<ExtractCSTWithSTN<IT>>\n | Map<string | number, ExtractCSTWithSTN<IT>>\n | readonly (readonly [string | number, ExtractCSTWithSTN<IT>])[]\n\n/** @hidden */\nexport interface IMSTMap<IT extends IAnyType> {\n // bases on ObservableMap, but fine tuned to the auto snapshot conversion of MST\n\n clear(): void\n delete(key: string): boolean\n forEach(\n callbackfn: (value: IT[\"Type\"], key: string, map: this) => void,\n thisArg?: any\n ): void\n get(key: string | number): IT[\"Type\"] | undefined\n has(key: string | number): boolean\n set(key: string | number, value: ExtractCSTWithSTN<IT>): this\n readonly size: number\n put(value: ExtractCSTWithSTN<IT>): IT[\"Type\"]\n keys(): IterableIterator<string>\n values(): IterableIterator<IT[\"Type\"]>\n entries(): IterableIterator<[string, IT[\"Type\"]]>\n [Symbol.iterator](): IterableIterator<[string, IT[\"Type\"]]>\n /** Merge another object into this map, returns self. */\n merge(other?: IMSTMapInitialValues<IT>): this\n replace(values: IMSTMapInitialValues<IT>): this\n\n toJSON(): IKeyValueMap<IT[\"SnapshotType\"]>\n\n toString(): string\n [Symbol.toStringTag]: \"Map\"\n\n /**\n * Observes this object. Triggers for the events 'add', 'update' and 'delete'.\n * See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/observe\n * for callback details\n */\n observe(\n listener: (changes: IMapDidChange<string, IT[\"Type\"]>) => void,\n fireImmediately?: boolean\n ): Lambda\n intercept(handler: IInterceptor<IMapWillChange<string, IT[\"Type\"]>>): Lambda\n}\n\nconst needsIdentifierError = `Map.put can only be used to store complex values that have an identifier type attribute`\n\nfunction tryCollectModelTypes(\n type: IAnyType,\n modelTypes: Array<IAnyModelType>\n): boolean {\n const subtypes = type.getSubTypes()\n if (subtypes === cannotDetermineSubtype) {\n return false\n }\n if (subtypes) {\n const subtypesArray = asArray(subtypes)\n for (const subtype of subtypesArray) {\n if (!tryCollectModelTypes(subtype, modelTypes)) {\n return false\n }\n }\n }\n if (type instanceof ModelType) {\n modelTypes.push(type)\n }\n return true\n}\n\n/**\n * @internal\n * @hidden\n */\nexport enum MapIdentifierMode {\n UNKNOWN,\n YES,\n NO\n}\n\nclass MSTMap<IT extends IAnyType> extends ObservableMap<string, any> {\n override get(key: string): IT[\"Type\"] | undefined {\n // maybe this is over-enthousiastic? normalize numeric keys to strings\n return super.get(`${key}`)\n }\n\n override has(key: string) {\n return super.has(`${key}`)\n }\n\n override delete(key: string) {\n return super.delete(`${key}`)\n }\n\n override set(key: string, value: ExtractCSTWithSTN<IT>): this {\n return super.set(`${key}`, value)\n }\n\n put(value: ExtractCSTWithSTN<IT>): IT[\"Type\"] {\n if (!value) {\n throw fail(`Map.put cannot be used to set empty values`)\n }\n if (isStateTreeNode(value)) {\n const node = getStateTreeNode(value)\n if (devMode()) {\n if (!node.identifierAttribute) {\n throw fail(needsIdentifierError)\n }\n }\n if (node.identifier === null) {\n throw fail(needsIdentifierError)\n }\n this.set(node.identifier, value)\n return value\n } else if (!isMutable(value)) {\n throw fail(`Map.put can only be used to store complex values`)\n } else {\n const mapNode = getStateTreeNode(this)\n const mapType = mapNode.type as MapType<any>\n\n if (mapType.identifierMode !== MapIdentifierMode.YES) {\n throw fail(needsIdentifierError)\n }\n\n const idAttr = mapType.mapIdentifierAttribute!\n const id = (value as any)[idAttr]\n if (!isValidIdentifier(id)) {\n // try again but this time after creating a node for the value\n // since it might be an optional identifier\n const newNode = this.put(\n mapType.getChildType().create(value, mapNode.environment)\n )\n return this.put(getSnapshot(newNode))\n }\n const key = normalizeIdentifier(id)\n this.set(key, value)\n return this.get(key)\n }\n }\n}\n\n/**\n * @internal\n * @hidden\n */\nexport class MapType<IT extends IAnyType> extends ComplexType<\n IKeyValueMap<IT[\"CreationType\"]> | undefined,\n IKeyValueMap<IT[\"SnapshotType\"]>,\n IMSTMap<IT>\n> {\n identifierMode: MapIdentifierMode = MapIdentifierMode.UNKNOWN\n mapIdentifierAttribute: string | undefined = undefined\n readonly flags = TypeFlags.Map\n\n constructor(\n private readonly _subType: IAnyType,\n private readonly hookInitializers: HookInitializers<\n IMSTMap<IT>\n > = NO_HOOK_INITIALIZERS\n ) {\n super()\n this._determineIdentifierMode()\n }\n\n protected override computeName(): string {\n return `Map<string, ${this._subType.name}>`\n }\n\n hooks(hooks: IHooksGetter<IMSTMap<IT>>) {\n return new MapType(\n this._subType,\n appendHookInitializer(this.hookInitializers, hooks)\n )\n }\n\n instantiate(\n parent: AnyObjectNode | null,\n subpath: string,\n environment: any,\n initialValue: this[\"C\"] | this[\"T\"]\n ): this[\"N\"] {\n this._determineIdentifierMode()\n return createObjectNode(this, parent, subpath, environment, initialValue)\n }\n\n private _determineIdentifierMode() {\n if (this.identifierMode !== MapIdentifierMode.UNKNOWN) {\n return\n }\n\n const modelTypes: IAnyModelType[] = []\n if (tryCollectModelTypes(this._subType, modelTypes)) {\n const identifierAttribute: string | undefined = modelTypes.reduce(\n (current: IAnyModelType[\"identifierAttribute\"], type) => {\n if (!type.identifierAttribute) {\n return current\n }\n if (current && current !== type.identifierAttribute) {\n throw fail(\n `The objects in a map should all have the same identifier attribute, expected '${current}', but child of type '${type.name}' declared attribute '${type.identifierAttribute}' as identifier`\n )\n }\n return type.identifierAttribute\n },\n undefined as IAnyModelType[\"identifierAttribute\"]\n )\n\n if (identifierAttribute) {\n this.identifierMode = MapIdentifierMode.YES\n this.mapIdentifierAttribute = identifierAttribute\n } else {\n this.identifierMode = MapIdentifierMode.NO\n }\n }\n }\n\n initializeChildNodes(\n objNode: this[\"N\"],\n initialSnapshot: this[\"C\"] = {}\n ): IChildNodesMap {\n const subType = (objNode.type as this)._subType\n const result: IChildNodesMap = {}\n Object.keys(initialSnapshot).forEach(name => {\n result[name] = subType.instantiate(\n objNode,\n name,\n undefined,\n initialSnapshot[name]\n )\n })\n\n return result\n }\n\n createNewInstance(childNodes: IChildNodesMap): this[\"T\"] {\n // undefined is mobx's enhancer argument, left at its deep default\n return new MSTMap(childNodes, undefined, this.name) as any\n }\n\n finalizeNewInstance(\n node: this[\"N\"],\n instance: ObservableMap<string, any>\n ): void {\n _interceptReads(instance, node.unbox)\n\n installHookInitializers(\n (node.type as this).hookInitializers,\n instance as unknown as IMSTMap<IT>\n )\n\n intercept(instance, this.willChange)\n observe(instance, this.didChange)\n }\n\n getChildren(node: this[\"N\"]): ReadonlyArray<AnyNode> {\n // return (node.storedValue as ObservableMap<any>).values()\n return values(node.storedValue)\n }\n\n getChildNode(node: this[\"N\"], key: string): AnyNode {\n const childNode = node.storedValue.get(`${key}`)\n if (!childNode) {\n throw fail(`Not a child ${key}`)\n }\n return childNode\n }\n\n willChange(\n change: IMapWillChange<string, AnyNode>\n ): IMapWillChange<string, AnyNode> | null {\n const node = getStateTreeNode(change.object as IAnyStateTreeNode)\n const key = change.name\n node.assertWritable({ subpath: key })\n const mapType = node.type as this\n const subType = mapType._subType\n\n switch (change.type) {\n case \"update\":\n {\n const { newValue } = change\n const oldValue = change.object.get(key)\n if (newValue === oldValue) {\n return null\n }\n typecheckInternal(subType, newValue)\n change.newValue = subType.reconcile(\n node.getChildNode(key),\n change.newValue,\n node,\n key\n )\n mapType.processIdentifier(key, change.newValue)\n }\n break\n case \"add\":\n {\n typecheckInternal(subType, change.newValue)\n change.newValue = subType.instantiate(\n node,\n key,\n undefined,\n change.newValue\n )\n mapType.processIdentifier(key, change.newValue)\n }\n break\n }\n return change\n }\n\n private processIdentifier(expected: string, node: AnyNode): void {\n if (\n this.identifierMode === MapIdentifierMode.YES &&\n node instanceof ObjectNode\n ) {\n const identifier = node.identifier!\n if (identifier !== expected) {\n throw fail(\n `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 }\n\n override getSnapshot(node: this[\"N\"]): this[\"S\"] {\n const res: any = {}\n node.getChildren().forEach(childNode => {\n res[childNode.subpath] = childNode.snapshot\n })\n return res\n }\n\n processInitialSnapshot(childNodes: IChildNodesMap): this[\"S\"] {\n const processed: any = {}\n Object.keys(childNodes).forEach(key => {\n processed[key] = childNodes[key]!.getSnapshot()\n })\n return processed\n }\n\n didChange(change: IMapDidChange<string, AnyNode>): void {\n const node = getStateTreeNode(change.object as IAnyStateTreeNode)\n switch (change.type) {\n case \"update\":\n return void node.emitPatch(\n {\n op: \"replace\",\n path: escapeJsonPath(change.name),\n value: change.newValue.snapshot,\n oldValue: change.oldValue ? change.oldValue.snapshot : undefined\n },\n node\n )\n case \"add\":\n return void node.emitPatch(\n {\n op: \"add\",\n path: escapeJsonPath(change.name),\n value: change.newValue.snapshot,\n oldValue: undefined\n },\n node\n )\n case \"delete\":\n // a node got deleted, get the old snapshot and make the node die\n const oldSnapshot = change.oldValue.snapshot\n change.oldValue.die()\n // emit the patch\n return void node.emitPatch(\n {\n op: \"remove\",\n path: escapeJsonPath(change.name),\n oldValue: oldSnapshot\n },\n node\n )\n }\n }\n\n applyPatchLocally(node: this[\"N\"], subpath: string, patch: IJsonPatch): void {\n const target = node.storedValue\n switch (patch.op) {\n case \"add\":\n case \"replace\":\n target.set(subpath, patch.value)\n break\n case \"remove\":\n target.delete(subpath)\n break\n }\n }\n\n applySnapshot(node: this[\"N\"], snapshot: this[\"C\"]): void {\n typecheckInternal(this, snapshot)\n const target = node.storedValue\n // keys present before the apply, minus the ones the snapshot (re)sets — what\n // remains has to be deleted. A Set rather than a plain object: it needs no\n // sentinel values, no second pass to find the survivors, and it can hold keys\n // like \"__proto__\", which an object literal silently swallows.\n const staleKeys = new Set(target.keys())\n if (snapshot) {\n // Don't use target.replace, as it will throw away all existing items first\n for (const key in snapshot) {\n target.set(key, snapshot[key])\n staleKeys.delete(key)\n }\n }\n for (const key of staleKeys) {\n target.delete(key)\n }\n }\n\n getChildType(): IAnyType {\n return this._subType\n }\n\n isValidSnapshot(\n value: this[\"C\"],\n context: IValidationContext\n ): IValidationResult {\n if (!isPlainObject(value)) {\n return typeCheckFailure(context, value, \"Value is not a plain object\")\n }\n\n for (const key of Object.keys(value)) {\n getContextForPath(context, key, this._subType)\n const errors = this._subType.validate(value[key], context)\n popContext(context)\n if (errors.length > 0) {\n return errors\n }\n }\n return typeCheckSuccess()\n }\n\n getDefaultSnapshot(): this[\"C\"] {\n return EMPTY_OBJECT\n }\n\n removeChild(node: this[\"N\"], subpath: string) {\n node.storedValue.delete(subpath)\n }\n}\nMapType.prototype.applySnapshot = action(MapType.prototype.applySnapshot)\n\n/**\n * `types.map` - Creates a key based collection type who's children are all of a uniform declared type.\n * If the type stored in a map has an identifier, it is mandatory to store the child under that identifier in the map.\n *\n * This type will always produce [observable maps](https://mobx.js.org/api.html#observablemap)\n *\n * Example:\n * ```ts\n * const Todo = types.model({\n * id: types.identifier,\n * task: types.string\n * })\n *\n * const TodoStore = types.model({\n * todos: types.map(Todo)\n * })\n *\n * const s = TodoStore.create({ todos: {} })\n * unprotect(s)\n * s.todos.set(17, { task: \"Grab coffee\", id: 17 })\n * s.todos.put({ task: \"Grab cookie\", id: 18 }) // put will infer key from the identifier\n * console.log(s.todos.get(17).task) // prints: \"Grab coffee\"\n * ```\n *\n * @param subtype\n * @returns\n */\nexport function map<IT extends IAnyType>(subtype: IT): IMapType<IT> {\n assertIsType(subtype, 1)\n return new MapType<IT>(subtype)\n}\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 */\nexport function isMapType<Items extends IAnyType = IAnyType>(\n type: IAnyType\n): type is IMapType<Items> {\n return isType(type) && (type.flags & TypeFlags.Map) > 0\n}\n","import {\n type IArrayDidChange,\n type IArraySplice,\n type IArrayWillChange,\n type IArrayWillSplice,\n type IObservableArray,\n _getAdministration,\n action,\n intercept,\n observable,\n observe\n} from \"mobx\"\n\nimport {\n type AnyNode,\n type AnyObjectNode,\n ComplexType,\n EMPTY_ARRAY,\n EMPTY_OBJECT,\n type ExtractCSTWithSTN,\n type HookInitializers,\n type IAnyStateTreeNode,\n type IAnyType,\n type IChildNodesMap,\n type IHooksGetter,\n type IJsonPatch,\n type IStateTreeNode,\n type IType,\n type IValidationContext,\n type IValidationResult,\n NO_HOOK_INITIALIZERS,\n ObjectNode,\n TypeFlags,\n appendHookInitializer,\n assertIsType,\n convertChildNodesToArray,\n createObjectNode,\n fail,\n getContextForPath,\n getStateTreeNode,\n installHookInitializers,\n isArray,\n isNode,\n isPlainObject,\n isStateTreeNode,\n isType,\n ModelType,\n mobxShallow,\n normalizeIdentifier,\n popContext,\n typeCheckFailure,\n typeCheckSuccess,\n typecheckInternal\n} from \"../../internal.ts\"\n\n/** @hidden */\nexport interface IMSTArray<IT extends IAnyType> extends IObservableArray<\n IT[\"Type\"]\n> {\n // needs to be split or else it will complain about not being compatible with the array interface\n push(...items: IT[\"Type\"][]): number\n push(...items: ExtractCSTWithSTN<IT>[]): number\n\n concat(...items: ConcatArray<IT[\"Type\"]>[]): IT[\"Type\"][]\n concat(...items: ConcatArray<ExtractCSTWithSTN<IT>>[]): IT[\"Type\"][]\n\n concat(...items: (IT[\"Type\"] | ConcatArray<IT[\"Type\"]>)[]): IT[\"Type\"][]\n concat(\n ...items: (ExtractCSTWithSTN<IT> | ConcatArray<ExtractCSTWithSTN<IT>>)[]\n ): IT[\"Type\"][]\n\n splice(start: number, deleteCount?: number): IT[\"Type\"][]\n splice(\n start: number,\n deleteCount: number,\n ...items: IT[\"Type\"][]\n ): IT[\"Type\"][]\n splice(\n start: number,\n deleteCount: number,\n ...items: ExtractCSTWithSTN<IT>[]\n ): IT[\"Type\"][]\n\n unshift(...items: IT[\"Type\"][]): number\n unshift(...items: ExtractCSTWithSTN<IT>[]): number\n}\n\n/** @hidden */\nexport interface IArrayType<IT extends IAnyType> extends IType<\n readonly IT[\"CreationType\"][] | undefined,\n IT[\"SnapshotType\"][],\n IMSTArray<IT>\n> {\n hooks(hooks: IHooksGetter<IMSTArray<IAnyType>>): IArrayType<IT>\n /** the element type of the array */\n getChildType(): IAnyType\n}\n\n/**\n * @internal\n * @hidden\n */\nexport class ArrayType<IT extends IAnyType> extends ComplexType<\n readonly IT[\"CreationType\"][] | undefined,\n IT[\"SnapshotType\"][],\n IMSTArray<IT>\n> {\n readonly flags = TypeFlags.Array\n\n constructor(\n private readonly _subType: IT,\n private readonly hookInitializers: HookInitializers<\n IMSTArray<IT>\n > = NO_HOOK_INITIALIZERS\n ) {\n super()\n }\n\n protected override computeName(): string {\n return `${this._subType.name}[]`\n }\n\n hooks(hooks: IHooksGetter<IMSTArray<IT>>) {\n return new ArrayType(\n this._subType,\n appendHookInitializer(this.hookInitializers, hooks)\n )\n }\n\n instantiate(\n parent: AnyObjectNode | null,\n subpath: string,\n environment: any,\n initialValue: this[\"C\"] | this[\"T\"]\n ): this[\"N\"] {\n return createObjectNode(this, parent, subpath, environment, initialValue)\n }\n\n initializeChildNodes(\n objNode: this[\"N\"],\n snapshot: this[\"C\"] = []\n ): IChildNodesMap {\n const subType = (objNode.type as this)._subType\n const result: IChildNodesMap = {}\n snapshot.forEach((item, index) => {\n const subpath = `${index}`\n result[subpath] = subType.instantiate(objNode, subpath, undefined, item)\n })\n return result\n }\n\n createNewInstance(childNodes: IChildNodesMap): this[\"T\"] {\n const options = { ...mobxShallow, name: this.name }\n return observable.array(\n convertChildNodesToArray(childNodes) as AnyNode[],\n options\n ) as this[\"T\"]\n }\n\n finalizeNewInstance(node: this[\"N\"], instance: this[\"T\"]): void {\n _getAdministration(instance).dehancer = node.unbox\n\n installHookInitializers((node.type as this).hookInitializers, instance)\n\n intercept(instance as IObservableArray<AnyNode>, this.willChange)\n observe(instance as IObservableArray<AnyNode>, this.didChange)\n }\n\n getChildren(node: this[\"N\"]): AnyNode[] {\n return node.storedValue.slice()\n }\n\n getChildNode(node: this[\"N\"], key: string): AnyNode {\n const child = node.storedValue[Number(key)]\n if (child) {\n return child\n }\n throw fail(`Not a child: ${key}`)\n }\n\n willChange(\n change: IArrayWillChange<AnyNode> | IArrayWillSplice<AnyNode>\n ): IArrayWillChange<AnyNode> | IArrayWillSplice<AnyNode> | null {\n const node = getStateTreeNode(change.object as IStateTreeNode<this>)\n node.assertWritable({ subpath: `${change.index}` })\n const subType = (node.type as this)._subType\n\n switch (change.type) {\n case \"update\":\n {\n if (change.newValue === change.object[change.index]) {\n return null\n }\n\n const updatedNodes = reconcileArrayChildren(\n node,\n subType,\n // only the replaced child is reconciled, so read that one node\n // directly — `node.getChildren()` copies the whole backing array,\n // which made a single-element assignment cost O(array length)\n [node.getChildNode(`${change.index}`)],\n [change.newValue],\n change.index\n )\n if (!updatedNodes) {\n return null\n }\n change.newValue = updatedNodes[0]!\n }\n break\n case \"splice\":\n {\n const { index, removedCount, added } = change\n const childNodes = node.getChildren()\n\n const addedNodes = reconcileArrayChildren(\n node,\n subType,\n childNodes.slice(index, index + removedCount),\n added,\n index\n )\n if (!addedNodes) {\n return null\n }\n change.added = addedNodes\n\n // update paths of remaining items\n for (let i = index + removedCount; i < childNodes.length; i++) {\n childNodes[i]!.setParent(node, `${i + added.length - removedCount}`)\n }\n }\n break\n }\n return change\n }\n\n override getSnapshot(node: this[\"N\"]): this[\"S\"] {\n return node.getChildren().map(childNode => childNode.snapshot)\n }\n\n processInitialSnapshot(childNodes: IChildNodesMap): this[\"S\"] {\n const processed: this[\"S\"] = []\n Object.keys(childNodes).forEach(key => {\n processed.push(childNodes[key]!.getSnapshot())\n })\n return processed\n }\n\n didChange(change: IArrayDidChange<AnyNode> | IArraySplice<AnyNode>): void {\n const node = getStateTreeNode(change.object as IAnyStateTreeNode)\n switch (change.type) {\n case \"update\":\n return void node.emitPatch(\n {\n op: \"replace\",\n path: `${change.index}`,\n value: change.newValue.snapshot,\n oldValue: change.oldValue ? change.oldValue.snapshot : undefined\n },\n node\n )\n case \"splice\":\n for (let i = change.removedCount - 1; i >= 0; i--) {\n node.emitPatch(\n {\n op: \"remove\",\n path: `${change.index + i}`,\n oldValue: change.removed[i]!.snapshot\n },\n node\n )\n }\n for (let i = 0; i < change.addedCount; i++) {\n node.emitPatch(\n {\n op: \"add\",\n path: `${change.index + i}`,\n value: node.getChildNode(`${change.index + i}`).snapshot,\n oldValue: undefined\n },\n node\n )\n }\n return\n }\n }\n\n applyPatchLocally(node: this[\"N\"], subpath: string, patch: IJsonPatch): void {\n const target = node.storedValue\n const index = subpath === \"-\" ? target.length : Number(subpath)\n switch (patch.op) {\n case \"replace\":\n target[index] = patch.value\n break\n case \"add\":\n target.splice(index, 0, patch.value)\n break\n case \"remove\":\n target.splice(index, 1)\n break\n }\n }\n\n applySnapshot(node: this[\"N\"], snapshot: this[\"C\"]): void {\n typecheckInternal(this, snapshot)\n const target = node.storedValue\n target.replace(snapshot as any)\n }\n\n getChildType(): IAnyType {\n return this._subType\n }\n\n isValidSnapshot(\n value: this[\"C\"],\n context: IValidationContext\n ): IValidationResult {\n if (!isArray(value)) {\n return typeCheckFailure(context, value, \"Value is not an array\")\n }\n\n for (let i = 0; i < value.length; i++) {\n getContextForPath(context, `${i}`, this._subType)\n const errors = this._subType.validate(value[i], context)\n popContext(context)\n if (errors.length > 0) {\n return errors\n }\n }\n return typeCheckSuccess()\n }\n\n getDefaultSnapshot(): this[\"C\"] {\n return EMPTY_ARRAY\n }\n\n removeChild(node: this[\"N\"], subpath: string) {\n node.storedValue.splice(Number(subpath), 1)\n }\n}\nArrayType.prototype.applySnapshot = action(ArrayType.prototype.applySnapshot)\n\n/**\n * `types.array` - Creates an index based collection type who's children are all of a uniform declared type.\n *\n * This type will always produce [observable arrays](https://mobx.js.org/api.html#observablearray)\n *\n * Example:\n * ```ts\n * const Todo = types.model({\n * task: types.string\n * })\n *\n * const TodoStore = types.model({\n * todos: types.array(Todo)\n * })\n *\n * const s = TodoStore.create({ todos: [] })\n * unprotect(s) // needed to allow modifying outside of an action\n * s.todos.push({ task: \"Grab coffee\" })\n * console.log(s.todos[0]) // prints: \"Grab coffee\"\n * ```\n *\n * @param subtype\n * @returns\n */\nexport function array<IT extends IAnyType>(subtype: IT): IArrayType<IT> {\n assertIsType(subtype, 1)\n return new ArrayType<IT>(subtype)\n}\n\n/**\n * @param firstNewPath index the reconciled slice starts at; both call sites\n * hand over a contiguous run, so subpath `i` is simply `firstNewPath + i`\n */\nfunction reconcileArrayChildren<TT>(\n parent: AnyObjectNode,\n childType: IType<any, any, TT>,\n oldNodes: AnyNode[],\n newValues: TT[],\n firstNewPath: number\n): AnyNode[] | null {\n let nothingChanged = true\n\n // When the element type is a plain model with an identifier, index the old\n // nodes by id so a moved / replaced child is matched in O(1) instead of the\n // linear scan in the reorder branch below. This turns a full array\n // replacement (the common \"load new data\" case) from O(n^2) into O(n). Types\n // whose id extraction needs type-specific preprocessing (union,\n // snapshotProcessor, late, ...) are intentionally excluded: areSame must run\n // `is()` before their id check, so they stay on the scan path.\n // With at most one old node the scan below is already O(1), so building the\n // index would only add a Map allocation to every single-element write.\n let idIndex: { attr: string; byId: Map<string, AnyNode> } | undefined\n if (\n oldNodes.length > 1 &&\n childType instanceof ModelType &&\n childType.identifierAttribute\n ) {\n const byId = new Map<string, AnyNode>()\n for (const n of oldNodes) {\n if (n instanceof ObjectNode && n.identifier !== null) {\n byId.set(n.identifier, n)\n }\n }\n idIndex = { attr: childType.identifierAttribute, byId }\n }\n\n for (let i = 0; ; i++) {\n const hasNewNode = i <= newValues.length - 1\n const oldNode = oldNodes[i]\n let newValue = hasNewNode ? newValues[i] : undefined\n const newPath = `${firstNewPath + i}`\n\n // for some reason, instead of newValue we got a node, fallback to the storedValue\n // TODO: https://github.com/mobxjs/mobx-state-tree/issues/340#issuecomment-325581681\n if (isNode(newValue)) {\n newValue = newValue.storedValue\n }\n\n if (!oldNode && !hasNewNode) {\n // both are empty, end\n break\n } else if (oldNode && !hasNewNode) {\n // new one does not exists\n nothingChanged = false\n oldNodes.splice(i, 1)\n if (oldNode instanceof ObjectNode) {\n // since it is going to be returned by pop/splice/shift better create it before killing it\n // so it doesn't end up in an undead state\n oldNode.createObservableInstanceIfNeeded()\n }\n oldNode.die()\n i--\n } 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 (\n isStateTreeNode(newValue) &&\n getStateTreeNode(newValue).parent === parent\n ) {\n // this node is owned by this parent, but not in the reconcilable set, so it must be double\n throw fail(\n `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 '${\n parent.path\n }/${newPath}', but it lives already at '${getStateTreeNode(newValue).path}'`\n )\n }\n nothingChanged = false\n const 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: find a candidate old node to reuse\n let oldMatch = undefined\n\n if (idIndex && isPlainObject(newValue)) {\n // for an identified element type a plain-object snapshot can only match\n // by id (it is never a live node, and snapshot-reference equality still\n // implies the same id), so a miss means \"nothing to reuse\" without\n // scanning. areSame still verifies the single candidate.\n const candidate = idIndex.byId.get(\n normalizeIdentifier(newValue[idIndex.attr])\n )\n const j = candidate ? oldNodes.indexOf(candidate, i) : -1\n if (j >= i && areSame(oldNodes[j]!, newValue)) {\n oldMatch = oldNodes.splice(j, 1)[0]\n }\n } else {\n // find a possible candidate to reuse\n for (let 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\n nothingChanged = false\n const newNode = valueAsNode(\n childType,\n parent,\n newPath,\n newValue,\n oldMatch\n )\n oldNodes.splice(i, 0, newNode)\n }\n }\n\n return nothingChanged ? null : oldNodes\n}\n\n/**\n * Convert a value to a node at given parent and subpath. Attempts to reuse old node if possible and given.\n */\nfunction valueAsNode(\n childType: IAnyType,\n parent: AnyObjectNode,\n subpath: string,\n newValue: any,\n oldNode?: AnyNode\n) {\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 const childNode = getStateTreeNode(newValue)\n childNode.assertAlive(EMPTY_OBJECT)\n\n // the node lives here\n if (childNode.parent !== null && childNode.parent === parent) {\n childNode.setParent(parent, subpath)\n return childNode\n }\n }\n // there is old node and new one is a value/snapshot\n if (oldNode) {\n return childType.reconcile(oldNode, newValue, parent, subpath)\n }\n\n // nothing to do, create from scratch\n return childType.instantiate(parent, subpath, undefined, newValue)\n }\n\n const newNode = getNewNode()\n if (oldNode && oldNode !== newNode) {\n if (oldNode instanceof ObjectNode) {\n // since it is going to be returned by pop/splice/shift better create it before killing it\n // so it doesn't end up in an undead state\n oldNode.createObservableInstanceIfNeeded()\n }\n oldNode.die()\n }\n return newNode\n}\n\n/**\n * Reconciliation types that carry an identifier expose this; `getReconciliationType`\n * is declared as the general `IAnyType`, on which it isn't part of the surface.\n */\ninterface SnapshotIdMatcher {\n isMatchingSnapshotId(current: AnyNode, snapshot: any): boolean\n}\n\n/**\n * Check if a node holds a value.\n */\nfunction areSame(oldNode: AnyNode, newValue: any): boolean {\n // never consider dead old nodes for reconciliation\n if (!oldNode.isAlive) {\n return false\n }\n\n // the new value has the same node\n if (isStateTreeNode(newValue)) {\n const newNode = getStateTreeNode(newValue)\n return newNode.isAlive && newNode === oldNode\n }\n\n // the provided value is the snapshot of the old node\n if (oldNode.snapshot === newValue) {\n return true\n }\n\n // Non object nodes don't get reconciled\n if (!(oldNode instanceof ObjectNode)) {\n return false\n }\n\n if (\n oldNode.identifier === null ||\n !oldNode.identifierAttribute ||\n !isPlainObject(newValue)\n ) {\n return false\n }\n\n const oldNodeType = oldNode.getReconciliationType()\n // new value is a snapshot with the correct identifier\n return (\n oldNodeType.is(newValue) &&\n (oldNodeType as unknown as SnapshotIdMatcher).isMatchingSnapshotId(\n oldNode,\n newValue\n )\n )\n}\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 */\nexport function isArrayType<Items extends IAnyType = IAnyType>(\n type: IAnyType\n): type is IArrayType<Items> {\n return isType(type) && (type.flags & TypeFlags.Array) > 0\n}\n","import {\n type IObjectDidChange,\n type IObjectWillChange,\n _getAdministration,\n _interceptReads,\n action,\n computed,\n defineProperty,\n getAtom,\n type IAtom,\n intercept,\n isComputedProp,\n isObservableProp,\n makeObservable,\n observable,\n observe,\n set\n} from \"mobx\"\n\nimport {\n type AnyNode,\n type AnyObjectNode,\n ArrayType,\n ComplexType,\n EMPTY_ARRAY,\n EMPTY_OBJECT,\n type FunctionWithFlag,\n Hook,\n type IAnyStateTreeNode,\n type IAnyType,\n type IChildNodesMap,\n type IJsonPatch,\n type IType,\n type IValidationContext,\n type IValidationResult,\n type Instance,\n MapType,\n TypeFlags,\n type _CustomOrOther,\n type _NotCustomized,\n addHiddenFinalProp,\n addHiddenWritableProp,\n assertArg,\n assertIsString,\n createActionInvoker,\n createObjectNode,\n devMode,\n escapeJsonPath,\n fail,\n freeze,\n getContextForPath,\n getPrimitiveFactoryFromValue,\n getStateTreeNode,\n isPlainObject,\n isPrimitive,\n isStateTreeNode,\n isType,\n mobxShallow,\n optional,\n shouldStripChildFromSnapshot,\n popContext,\n typeCheckFailure,\n typeCheckSuccess,\n typecheckInternal\n} from \"../../internal.ts\"\n\nconst PRE_PROCESS_SNAPSHOT = \"preProcessSnapshot\"\nconst POST_PROCESS_SNAPSHOT = \"postProcessSnapshot\"\n\n/**\n * mobx's per-property `ObservableValue`: an atom we can `reportObserved()` plus\n * `raw()` to read the stored child node directly, bypassing the unboxing\n * interceptor installed in `finalizeNewInstance`. mobx types `getAtom` as the\n * bare `IDepTreeNode`, so the one narrowing cast lives here.\n */\ntype PropObservable = IAtom & {\n raw(): AnyNode | undefined\n /** the read interceptor `_interceptReads` installs; see finalizeNewInstance */\n dehancer?: (childNode: AnyNode | undefined) => AnyNode | undefined\n}\n\nfunction getPropObservable(storedValue: any, key: string): PropObservable {\n return getAtom(storedValue, key) as PropObservable\n}\n\n/**\n * All of an instance's per-property `ObservableValue`s in one map, or\n * `undefined` if this mobx does not expose them.\n *\n * `observable.object` returns a **Proxy**, and `getAtom(storedValue, key)`\n * probes it with four `isObservableArray/Set/Map/Object` guards plus a `$mobx`\n * read — each one a marker-property read that goes through the proxy's `get`\n * trap. Paying that per property made the trap machinery the bulk of a wide\n * model's `getSnapshot`; resolving the administration once and reading its\n * property map directly reduces the per-property cost to a `Map.get`.\n *\n * `values_` is mobx-internal, hence the undefined result: every caller keeps a\n * path built on supported API, so a mobx that drops it degrades to the old\n * speed rather than breaking.\n *\n * The map is complete for our instances. `getAtom` falls back to\n * `materializeLazy{Computed,Observable}_` because mobx defers constructing an\n * `ObservableValue` for *decorator* annotations; `createNewInstance` builds\n * these through `observable.object`, which populates `values_` eagerly for\n * every declared property.\n */\nfunction getPropObservables(\n storedValue: any\n): Map<string, PropObservable> | undefined {\n const adm = _getAdministration(storedValue) as {\n values_?: Map<string, PropObservable>\n }\n return adm.values_\n}\n\n/** @hidden */\nexport interface ModelProperties {\n [key: string]: IAnyType\n}\n\n/** @hidden */\nexport type ModelPrimitive = string | number | boolean | Date\n\n/** @hidden */\nexport interface ModelPropertiesDeclaration {\n [key: string]: ModelPrimitive | IAnyType\n}\n\n/**\n * Unmaps syntax property declarations to a map of { propName: IType }\n *\n * @hidden\n */\nexport type ModelPropertiesDeclarationToProperties<\n T extends ModelPropertiesDeclaration\n> = T extends { [k: string]: IAnyType } // optimization to reduce nesting\n ? T\n : {\n [K in keyof T]: T[K] extends IAnyType // keep IAnyType check on the top to reduce nesting\n ? T[K]\n : T[K] extends string\n ? IType<string | undefined, string, string>\n : T[K] extends number\n ? IType<number | undefined, number, number>\n : T[K] extends boolean\n ? IType<boolean | undefined, boolean, boolean>\n : T[K] extends Date\n ? IType<number | Date | undefined, number, Date>\n : never\n }\n\n/**\n * Checks if a value is optional (undefined, any or unknown).\n * @hidden\n *\n * Examples:\n * - string = false\n * - undefined = true\n * - string | undefined = true\n * - string & undefined = false, but we don't care\n * - any = true\n * - unknown = true\n */\ntype IsOptionalValue<C, TV, FV> = undefined extends C ? TV : FV\n\n// type _A = IsOptionalValue<string, true, false> // false\n// type _B = IsOptionalValue<undefined, true, false> // true\n// type _C = IsOptionalValue<string | undefined, true, false> // true\n// type _D = IsOptionalValue<string & undefined, true, false> // false, but we don't care\n// type _E = IsOptionalValue<any, true, false> // true\n// type _F = IsOptionalValue<unknown, true, false> // true\n\n/**\n * Name of the properties of an object that can't be set to undefined, any or unknown\n * @hidden\n */\ntype DefinablePropsNames<T> = {\n [K in keyof T]: IsOptionalValue<T[K], never, K>\n}[keyof T]\n\n// Weak brand applied to the truly-empty *creation* type so it doesn't structurally collapse to\n// `{}` (which TypeScript treats as \"any non-nullish value\"), which would let\n// `types.model().create({ anything })` through. It must be a weak type (only an optional prop) so\n// it can be intersected with `Partial<PC>` in ModelCreationType without rejecting valid props.\n//\n// Deliberately NOT applied to the snapshot type (see ModelSnapshotType): a weak brand there is a\n// \"no properties in common\" type that breaks substitutability of derived models with extra\n// optional props onto their base (issue #2186). Exported so TypeScript can name it in declaration\n// files (TS4058) when the creation type propagates into exported function signatures.\nexport interface $EmptyObjectBrand {\n readonly $__mstEmpty__?: never\n}\ntype EmptyObject = $EmptyObjectBrand\n\n/** @hidden */\nexport type MaybeEmpty<T> = keyof T extends never ? EmptyObject : T\n\n/** @hidden */\nexport type ExtractCFromProps<P extends ModelProperties> = {\n [k in keyof P]: P[k][\"CreationType\"]\n}\n\n/**\n * Merge two property bags with last-wins semantics, mirroring how `compose`\n * and `.props()` override props at runtime. A plain `PA & PB` intersects the\n * value types of shared keys, which collapses overridden discriminants (e.g.\n * `types.literal(\"Base\") & types.literal(\"Child\")`) to `never`.\n * @hidden\n */\nexport type _OverrideProps<\n PA extends ModelProperties,\n PB extends ModelProperties\n> = Omit<PA, keyof PB> & PB\n\n/** @hidden */\nexport type ModelCreationType<PC> = MaybeEmpty<{\n [P in DefinablePropsNames<PC>]: PC[P]\n}> &\n Partial<PC>\n\n/** @hidden */\nexport type ModelCreationType2<P extends ModelProperties, CustomC> = MaybeEmpty<\n _CustomOrOther<CustomC, ModelCreationType<ExtractCFromProps<P>>>\n>\n\n/** @hidden */\nexport type ModelSnapshotType<P extends ModelProperties> = {\n [K in keyof P]: P[K][\"SnapshotType\"]\n}\n\n/** @hidden */\nexport type ModelSnapshotType2<\n P extends ModelProperties,\n CustomS\n> = _CustomOrOther<CustomS, ModelSnapshotType<P>>\n\n/**\n * @hidden\n * we keep this separate from ModelInstanceType to shorten model instance types generated declarations\n */\nexport type ModelInstanceTypeProps<P extends ModelProperties> = {\n [K in keyof P]: P[K][\"Type\"]\n}\n\n/**\n * @hidden\n * do not transform this to an interface or model instance type generated declarations will be longer\n */\nexport type ModelInstanceType<\n P extends ModelProperties,\n O\n> = ModelInstanceTypeProps<P> & O\n\n/** @hidden */\nexport interface ModelActions {\n [key: string]: FunctionWithFlag\n}\n\nexport interface IModelType<\n PROPS extends ModelProperties,\n OTHERS,\n CustomC = _NotCustomized,\n CustomS = _NotCustomized\n> extends IType<\n ModelCreationType2<PROPS, CustomC>,\n ModelSnapshotType2<PROPS, CustomS>,\n ModelInstanceType<PROPS, OTHERS>\n> {\n readonly properties: PROPS\n\n named(newName: string): IModelType<PROPS, OTHERS, CustomC, CustomS>\n\n // warning: redefining props after a process snapshot is used ends up on the fixed (custom) C, S typings being overridden\n // so it is recommended to use pre/post process snapshot after all props have been defined\n props<PROPS2 extends ModelPropertiesDeclaration>(\n props: PROPS2\n ): IModelType<\n _OverrideProps<PROPS, ModelPropertiesDeclarationToProperties<PROPS2>>,\n OTHERS,\n CustomC,\n CustomS\n >\n\n views<V extends object>(\n fn: (self: Instance<this>) => V\n ): IModelType<PROPS, OTHERS & V, CustomC, CustomS>\n\n actions<A extends ModelActions>(\n fn: (self: Instance<this>) => A\n ): IModelType<PROPS, OTHERS & A, CustomC, CustomS>\n\n volatile<TP extends object>(\n fn: (self: Instance<this>) => TP\n ): IModelType<PROPS, OTHERS & TP, CustomC, CustomS>\n\n extend<\n A extends ModelActions = {},\n V extends object = {},\n VS extends object = {}\n >(\n fn: (self: Instance<this>) => { actions?: A; views?: V; state?: VS }\n ): IModelType<PROPS, OTHERS & A & V & VS, CustomC, CustomS>\n\n preProcessSnapshot<NewC = ModelCreationType2<PROPS, CustomC>>(\n // The preprocessor may return the loose input snapshot (`NewC`) as well as\n // the strict creation type: migrations commonly massage an untyped record\n // and rely on the model's property defaults to fill the rest. Note the\n // result keeps `CustomC` (not `NewC`) as the creation type, so annotating\n // the preprocessor's parameter to accept legacy snapshots does not loosen\n // the type that `.create()` callers must satisfy.\n fn: (snapshot: NewC) => ModelCreationType2<PROPS, CustomC> | NewC\n ): IModelType<PROPS, OTHERS, CustomC, CustomS>\n\n postProcessSnapshot<NewS = ModelSnapshotType2<PROPS, CustomS>>(\n fn: (snapshot: ModelSnapshotType2<PROPS, CustomS>) => NewS\n ): IModelType<PROPS, OTHERS, CustomC, NewS>\n}\n\n/**\n * Any model type.\n */\nexport interface IAnyModelType extends IModelType<any, any, any, any> {}\n\nfunction objectTypeToString(this: any) {\n return getStateTreeNode(this).toString()\n}\n\n/**\n * @internal\n * @hidden\n */\nexport interface ModelTypeConfig {\n name?: string\n properties?: ModelPropertiesDeclaration\n initializers?: ReadonlyArray<(instance: any) => any>\n preProcessor?: ((snapshot: any) => any) | undefined\n postProcessor?: ((snapshot: any) => any) | undefined\n /**\n * @internal Set by cloneAndEnhance when a chain step (`.actions()`,\n * `.views()`, `.volatile()`, …) adds no new properties: `properties` is then\n * the parent type's already-converted + frozen ModelProperties, so the\n * constructor can skip the toPropertiesObject/freeze reprocessing pass, and\n * `propertyNames`/`identifierAttribute` below are the parent's already-derived\n * values (identical, since the property set is unchanged).\n */\n propertiesArePreProcessed?: boolean\n /** @internal Carried with `propertiesArePreProcessed`; see above. */\n propertyNames?: string[]\n /** @internal Carried with `propertiesArePreProcessed`; see above. */\n identifierAttribute?: string | undefined\n /**\n * @internal Set by cloneAndEnhance when new props are added: `properties` is\n * the parent's already-converted+frozen bag merged with the (freshly\n * converted) delta, so every value is already a type. The constructor then\n * skips the toPropertiesObject pass but still freezes + rederives\n * propertyNames/identifierAttribute, since the key set changed.\n */\n propertiesAreConverted?: boolean\n}\n\nconst ANONYMOUS_MODEL_NAME = \"AnonymousModel\"\n\n/**\n * A plain loop rather than a callback per property, which allocated a closure\n * and made an indirect call. This runs once per `types.model()` over every\n * declared property, and jbrowse builds a ~40-slot schema per track.\n */\nfunction findIdentifierAttribute(\n properties: ModelProperties,\n propertyNames: string[]\n): string | undefined {\n let identifierAttribute: string | undefined = undefined\n for (const propName of propertyNames) {\n if (properties[propName]!.flags & TypeFlags.Identifier) {\n if (identifierAttribute) {\n throw fail(\n `Cannot define property '${propName}' as object identifier, property '${identifierAttribute}' is already defined as identifier property`\n )\n }\n identifierAttribute = propName\n }\n }\n return identifierAttribute\n}\n\nfunction toPropertiesObject(\n declaredProps: ModelPropertiesDeclaration\n): ModelProperties {\n // loop through properties and ensures that all items are types\n return Object.keys(declaredProps).reduce(\n (props, key) => {\n // warn if user intended a HOOK\n if (key in Hook) {\n throw fail(\n `Hook '${key}' was defined as property. Hooks should be defined as part of the actions`\n )\n }\n\n // the user intended to use a view\n const descriptor = Object.getOwnPropertyDescriptor(declaredProps, key)!\n if (\"get\" in descriptor) {\n throw fail(\n \"Getters are not supported as properties. Please use views instead\"\n )\n }\n // undefined and null are not valid\n const value = descriptor.value\n if (value === null || value === undefined) {\n throw fail(\n \"The default value of an attribute cannot be null or undefined as the type cannot be inferred. Did you mean `types.maybe(someType)`?\"\n )\n }\n // its a primitive, convert to its type\n else if (isPrimitive(value)) {\n props[key] = optional(getPrimitiveFactoryFromValue(value), value)\n }\n // map defaults to empty object automatically for models\n else if (value instanceof MapType) {\n props[key] = optional(value, {})\n } else if (value instanceof ArrayType) {\n props[key] = optional(value, [])\n }\n // its already a type\n else if (isType(value)) {\n // do nothing, it's already a type\n }\n // its a function, maybe the user wanted a view?\n else if (devMode() && typeof value === \"function\") {\n throw fail(\n `Invalid type definition for property '${key}', it looks like you passed a function. Did you forget to invoke it, or did you intend to declare a view / action?`\n )\n }\n // no other complex values\n else if (devMode() && typeof value === \"object\") {\n throw fail(\n `Invalid type definition for property '${key}', it looks like you passed an object. Try passing another model type or a types.frozen.`\n )\n } else {\n throw fail(\n `Invalid type definition for property '${key}', cannot infer a type from a value like '${value}' (${typeof value})`\n )\n }\n\n return props\n },\n // seeded with the raw declaration; every key is either replaced by its\n // converted type below, left alone because it already is one, or throws\n { ...declaredProps } as ModelProperties\n )\n}\n\n/**\n * @internal\n * @hidden\n */\nexport class ModelType<\n PROPS extends ModelProperties,\n OTHERS,\n CustomC,\n CustomS,\n MT extends IModelType<PROPS, OTHERS, CustomC, CustomS>\n>\n extends ComplexType<\n ModelCreationType2<PROPS, CustomC>,\n ModelSnapshotType2<PROPS, CustomS>,\n ModelInstanceType<PROPS, OTHERS>\n >\n implements IModelType<PROPS, OTHERS, CustomC, CustomS>\n{\n readonly flags = TypeFlags.Object\n\n /*\n * The original object definition\n */\n public readonly initializers: ReadonlyArray<(instance: any) => any>\n public readonly properties: PROPS\n\n readonly preProcessor?: ((snapshot: any) => any) | undefined\n readonly postProcessor?: ((snapshot: any) => any) | undefined\n readonly propertyNames: string[]\n // member/property name collisions are a property of the type, so we only need\n // to check the first instance we finalize (see finalizeNewInstance)\n private duplicateKeysChecked = false\n\n constructor(opts: ModelTypeConfig) {\n // `??`, not `||`: `types.model(\"\", {})` names the model \"\". The old\n // `Object.assign(this, defaults, opts)` below overwrote the `||` fallback\n // with opts.name afterwards, so that only worked by accident.\n super(opts.name ?? ANONYMOUS_MODEL_NAME)\n // Every field is assigned here, unconditionally and in a fixed order,\n // rather than by `Object.assign(this, defaultObjectOptions, opts)`. `opts`\n // carries a different key set at each of the three call sites — `model()`,\n // and cloneAndEnhance's preprocessed / converted paths — so copying it\n // wholesale gave ModelType three hidden classes, making every later read of\n // `type.properties` / `type.propertyNames` (getSnapshot's inner loop, among\n // others) polymorphic. It also left the internal `propertiesArePreProcessed`\n // / `propertiesAreConverted` plumbing on the type for its whole lifetime.\n this.initializers = opts.initializers ?? EMPTY_ARRAY\n this.preProcessor = opts.preProcessor\n this.postProcessor = opts.postProcessor\n\n const declaredProperties = (opts.properties ?? EMPTY_OBJECT) as PROPS\n if (opts.propertiesArePreProcessed) {\n // `properties` is a parent type's already-converted + frozen output\n // (chain step with no new props), so its derived propertyNames and\n // identifierAttribute are identical to the parent's — reuse them verbatim\n // (cloneAndEnhance passed them in) instead of re-running Object.keys and\n // the per-prop identifier scan, both O(props), on every step.\n this.properties = declaredProperties\n this.propertyNames = opts.propertyNames!\n this.identifierAttribute = opts.identifierAttribute\n } else {\n // `propertiesAreConverted` (set by cloneAndEnhance when props are added)\n // means every value is already a type — the parent's converted bag merged\n // with a freshly converted delta — so skip re-converting. Only raw entry\n // points (`model()`) still need the full toPropertiesObject pass.\n const properties = (\n opts.propertiesAreConverted\n ? declaredProperties\n : toPropertiesObject(declaredProperties)\n ) as PROPS\n this.properties = properties\n freeze(properties) // make sure nobody messes with it\n const propertyNames = Object.keys(properties)\n this.propertyNames = propertyNames\n this.identifierAttribute = findIdentifierAttribute(\n properties,\n propertyNames\n )\n }\n }\n\n cloneAndEnhance(opts: ModelTypeConfig): IAnyModelType {\n // Fast path: a chain step that adds no new properties (.actions/.views/\n // .volatile/.named/pre-postProcessor) reuses this type's already-converted +\n // frozen properties (and their derived names/identifier) verbatim.\n const hasNewProps =\n opts.properties !== undefined && Object.keys(opts.properties).length > 0\n if (!hasNewProps) {\n return new ModelType({\n name: opts.name || this.name,\n properties: this.properties,\n propertiesArePreProcessed: true,\n // safe to share: propertyNames is never mutated after construction\n propertyNames: this.propertyNames,\n identifierAttribute: this.identifierAttribute,\n initializers: this.initializers.concat(opts.initializers || []),\n preProcessor: opts.preProcessor || this.preProcessor,\n postProcessor: opts.postProcessor || this.postProcessor\n })\n }\n // Adding props: this type's `properties` is already converted+frozen, so only\n // the delta needs conversion. compose passes already-converted props\n // (cur.properties) and flags them; `.props()` passes a raw declaration. Either\n // way the merged bag is fully converted, so the constructor skips re-converting\n // the (potentially large) inherited set — the previous hot spot in compose.\n const convertedNewProps = opts.propertiesAreConverted\n ? opts.properties!\n : toPropertiesObject(opts.properties!)\n return new ModelType({\n name: opts.name || this.name,\n properties: Object.assign({}, this.properties, convertedNewProps),\n propertiesAreConverted: true,\n initializers: this.initializers.concat(opts.initializers || []),\n preProcessor: opts.preProcessor || this.preProcessor,\n postProcessor: opts.postProcessor || this.postProcessor\n })\n }\n\n actions<A extends ModelActions>(fn: (self: Instance<this>) => A) {\n const actionInitializer = (self: Instance<this>) => {\n this.instantiateActions(self, fn(self))\n return self\n }\n return this.cloneAndEnhance({ initializers: [actionInitializer] })\n }\n\n private instantiateActions(self: this[\"T\"], actions: ModelActions): void {\n // check if return is correct\n if (!isPlainObject(actions)) {\n throw fail(\n `actions initializer should return a plain object containing actions`\n )\n }\n\n // bind actions to the object created\n Object.keys(actions).forEach(name => {\n // warn if preprocessor was given\n if (name === PRE_PROCESS_SNAPSHOT) {\n throw fail(\n `Cannot define action '${PRE_PROCESS_SNAPSHOT}', it should be defined using 'type.preProcessSnapshot(fn)' instead`\n )\n }\n // warn if postprocessor was given\n if (name === POST_PROCESS_SNAPSHOT) {\n throw fail(\n `Cannot define action '${POST_PROCESS_SNAPSHOT}', it should be defined using 'type.postProcessSnapshot(fn)' instead`\n )\n }\n\n let action2 = actions[name]!\n\n // apply hook composition\n const baseAction = (self as any)[name]\n if (name in Hook && baseAction) {\n const specializedAction = action2\n action2 = function (...args: any[]) {\n baseAction(...args)\n specializedAction(...args)\n }\n }\n\n // the goal of this is to make sure actions using \"this\" can call themselves,\n // while still allowing the middlewares to register them\n const boundAction = action2.bind(actions)\n boundAction._isFlowAction = action2._isFlowAction ?? false\n boundAction.$mst_middleware = action2.$mst_middleware\n const actionInvoker = createActionInvoker(self as any, name, boundAction)\n actions[name] = actionInvoker\n\n // See #646, allow models to be mocked\n ;(!devMode() ? addHiddenFinalProp : addHiddenWritableProp)(\n self,\n name,\n actionInvoker\n )\n })\n }\n\n declare named: MT[\"named\"]\n\n declare props: MT[\"props\"]\n\n volatile<TP extends object>(fn: (self: Instance<this>) => TP) {\n if (typeof fn !== \"function\") {\n throw fail(\n `You passed an ${typeof fn} to volatile state as an argument, when function is expected`\n )\n }\n const stateInitializer = (self: Instance<this>) => {\n this.instantiateVolatileState(self, fn(self))\n return self\n }\n return this.cloneAndEnhance({ initializers: [stateInitializer] })\n }\n\n private instantiateVolatileState(\n self: this[\"T\"],\n state: {\n [key: string]: any\n }\n ): void {\n // check views return\n if (!isPlainObject(state)) {\n throw fail(\n `volatile state initializer should return a plain object containing state`\n )\n }\n set(self, state)\n }\n\n extend<\n A extends ModelActions = {},\n V extends object = {},\n VS extends object = {}\n >(fn: (self: Instance<this>) => { actions?: A; views?: V; state?: VS }) {\n const initializer = (self: Instance<this>) => {\n this.applyExtension(self, fn(self), \"The `extend` function\")\n return self\n }\n return this.cloneAndEnhance({ initializers: [initializer] })\n }\n\n views<V extends object>(fn: (self: Instance<this>) => V) {\n const viewInitializer = (self: Instance<this>) => {\n this.instantiateViews(self, fn(self))\n return self\n }\n return this.cloneAndEnhance({ initializers: [viewInitializer] })\n }\n\n /**\n * @internal\n * @hidden\n * Materializes an additional actions/views/state extension onto an\n * already-created instance, using the same machinery as `.extend()` runs at\n * creation time. Powers {@link extendInstance}; callers must ensure the writes\n * are permitted (see extendInstance, which runs this in an action context).\n */\n applyExtensionToInstance(\n self: this[\"T\"],\n extension: { actions?: ModelActions; views?: object; state?: object }\n ): void {\n this.applyExtension(self, extension, \"extendInstance\")\n }\n\n /**\n * Materializes an `{ actions, views, state }` bundle onto an instance. Shared\n * by `.extend()` (at creation time) and `applyExtensionToInstance` (on a live\n * instance); `subject` only names the caller in the invalid-key error.\n */\n private applyExtension(\n self: this[\"T\"],\n extension: { actions?: ModelActions; views?: object; state?: object },\n subject: string\n ): void {\n const { actions, views, state, ...rest } = extension\n for (const key in rest) {\n throw fail(\n `${subject} should return an object with a subset of the fields 'actions', 'views' and 'state'. Found invalid key '${key}'`\n )\n }\n if (state) {\n this.instantiateVolatileState(self, state)\n }\n if (views) {\n this.instantiateViews(self, views)\n }\n if (actions) {\n this.instantiateActions(self, actions)\n }\n }\n\n private instantiateViews(self: this[\"T\"], views: object): void {\n // check views return\n if (!isPlainObject(views)) {\n throw fail(\n `views initializer should return a plain object containing views`\n )\n }\n Object.getOwnPropertyNames(views).forEach(key => {\n // is this a computed property?\n const descriptor = Object.getOwnPropertyDescriptor(views, key)!\n if (\"get\" in descriptor) {\n defineProperty(self, key, descriptor)\n makeObservable(self, { [key]: computed } as any)\n } else if (typeof descriptor.value === \"function\") {\n // this is a view function, merge as is!\n // See #646, allow models to be mocked\n ;(!devMode() ? addHiddenFinalProp : addHiddenWritableProp)(\n self,\n key,\n descriptor.value\n )\n } else {\n throw fail(\n `A view member should either be a function or getter based property`\n )\n }\n })\n }\n\n declare preProcessSnapshot: MT[\"preProcessSnapshot\"]\n\n declare postProcessSnapshot: MT[\"postProcessSnapshot\"]\n\n instantiate(\n parent: AnyObjectNode | null,\n subpath: string,\n environment: any,\n initialValue: this[\"C\"] | this[\"T\"]\n ): this[\"N\"] {\n const value = isStateTreeNode(initialValue)\n ? initialValue\n : this.applySnapshotPreProcessor(initialValue)\n return createObjectNode(this, parent, subpath, environment, value)\n // Optimization: record all prop- view- and action names after first construction, and generate an optimal base class\n // that pre-reserves all these fields for fast object-member lookups\n }\n\n initializeChildNodes(\n objNode: this[\"N\"],\n initialSnapshot: any = {}\n ): IChildNodesMap {\n const type = objNode.type as this\n const properties = type.properties\n const result: IChildNodesMap = {}\n for (const name of type.propertyNames) {\n result[name] = properties[name]!.instantiate(\n objNode,\n name,\n undefined,\n initialSnapshot[name]\n )\n }\n return result\n }\n\n createNewInstance(childNodes: IChildNodesMap): this[\"T\"] {\n const options = { ...mobxShallow, name: this.name }\n return observable.object(childNodes, EMPTY_OBJECT, options) as any\n }\n\n finalizeNewInstance(node: this[\"N\"], instance: this[\"T\"]): void {\n addHiddenFinalProp(instance, \"toString\", objectTypeToString)\n\n // `_interceptReads(instance, name, ...)` assigns exactly this `dehancer`,\n // but reaches the ObservableValue via getAtom — several proxy-trap reads\n // per property (see getPropObservables). Resolve the map once instead.\n const observables = getPropObservables(instance)\n if (observables) {\n for (const name of this.propertyNames) {\n observables.get(name)!.dehancer = node.unbox\n }\n } else {\n for (const name of this.propertyNames) {\n _interceptReads(instance, name, node.unbox)\n }\n }\n\n this.initializers.reduce((self, fn) => fn(self), instance)\n\n // views, actions and volatile share the instance namespace with properties,\n // so a view/action reusing a property name silently clobbers that property's\n // observable value. It's a type-level mistake (identical for every instance),\n // so we check just the first one we finalize: a healthy property stays a\n // plain observable, a shadowing getter becomes a computed, and a shadowing\n // function/value stops being observable at all. The flag is only set on\n // success so a broken type keeps throwing on every create.\n if (!this.duplicateKeysChecked) {\n for (const name of this.propertyNames) {\n if (\n isComputedProp(instance, name) ||\n !isObservableProp(instance, name)\n ) {\n throw fail(`${name} property is declared twice`)\n }\n }\n this.duplicateKeysChecked = true\n }\n\n intercept(instance, this.willChange)\n observe(instance, this.didChange)\n }\n\n private willChange(change: IObjectWillChange): IObjectWillChange | null {\n const node = getStateTreeNode(change.object)\n const subpath = change.name as string\n node.assertWritable({ subpath })\n // MST's removeChild sets the property to undefined rather than deleting it,\n // so mobx only ever delivers \"update\"/\"add\" changes here, never \"remove\".\n if (change.type !== \"remove\") {\n const childType = (node.type as this).properties[subpath]\n // only properties are typed, state are stored as-is references\n if (childType) {\n typecheckInternal(childType, change.newValue)\n change.newValue = childType.reconcile(\n node.getChildNode(subpath),\n change.newValue,\n node,\n subpath\n )\n }\n }\n return change\n }\n\n private didChange(change: IObjectDidChange) {\n const childNode = getStateTreeNode(change.object)\n const childType = (childNode.type as this).properties[change.name as string]\n // skip volatile state (no childType) and never-actually-occurring \"remove\" changes\n if (childType && change.type !== \"remove\") {\n const oldChildValue =\n change.type === \"update\" ? change.oldValue.snapshot : undefined\n childNode.emitPatch(\n {\n op: \"replace\",\n path: escapeJsonPath(change.name as string),\n value: change.newValue.snapshot,\n oldValue: oldChildValue\n },\n childNode\n )\n }\n }\n\n getChildren(node: this[\"N\"]): ReadonlyArray<AnyNode> {\n const names = this.propertyNames\n const storedValue = node.storedValue\n const observables = getPropObservables(storedValue)\n const res: AnyNode[] = new Array(names.length)\n for (let i = 0; i < names.length; i++) {\n const name = names[i]!\n const childNode = (\n observables\n ? observables.get(name)\n : getPropObservable(storedValue, name)\n )?.raw()\n if (!childNode) {\n throw fail(`Node not available for property ${name}`)\n }\n res[i] = childNode\n }\n return res\n }\n\n getChildNode(node: this[\"N\"], key: string): AnyNode {\n if (!(key in this.properties)) {\n throw fail(`Not a value property: ${key}`)\n }\n const childNode = getPropObservable(node.storedValue, key).raw()\n if (!childNode) {\n throw fail(`Node not available for property ${key}`)\n }\n return childNode\n }\n\n override getSnapshot(node: this[\"N\"], applyPostProcess = true): this[\"S\"] {\n const res = {} as any\n const storedValue = node.storedValue\n const properties = this.properties\n const observables = getPropObservables(storedValue)\n for (const name of this.propertyNames) {\n // One mobx lookup serves both purposes: reportObserved so the snapshot\n // computed recomputes when the child is reassigned (raw() below does not\n // track), and raw() to read the child node. Going through getChildNode\n // would repeat the same lookup for every property.\n const observable = observables\n ? observables.get(name)\n : getPropObservable(storedValue, name)\n observable?.reportObserved()\n const childNode = observable?.raw()\n if (!childNode) {\n throw fail(`Node not available for property ${name}`)\n }\n const snapshot = childNode.snapshot\n // strip-default optionals omit their key when equal to the default\n if (!shouldStripChildFromSnapshot(properties[name]!, snapshot)) {\n res[name] = snapshot\n }\n }\n if (applyPostProcess) {\n return this.applySnapshotPostProcessor(res)\n }\n return res\n }\n\n processInitialSnapshot(childNodes: IChildNodesMap): this[\"S\"] {\n const processed = {} as any\n Object.keys(childNodes).forEach(key => {\n const snapshot = childNodes[key]!.getSnapshot()\n // strip-default optionals omit their key when equal to the default; this\n // mirrors getSnapshot for nodes serialized before they become observable\n // instances (e.g. array/map children that were never accessed)\n if (!shouldStripChildFromSnapshot(this.properties[key]!, snapshot)) {\n processed[key] = snapshot\n }\n })\n return this.applySnapshotPostProcessor(processed)\n }\n\n applyPatchLocally(node: this[\"N\"], subpath: string, patch: IJsonPatch): void {\n if (!(patch.op === \"replace\" || patch.op === \"add\")) {\n throw fail(`object does not support operation ${patch.op}`)\n }\n ;(node.storedValue as any)[subpath] = patch.value\n }\n\n applySnapshot(node: this[\"N\"], snapshot: this[\"C\"]): void {\n typecheckInternal(this, snapshot)\n const preProcessedSnapshot = this.applySnapshotPreProcessor(snapshot)\n for (const name of this.propertyNames) {\n ;(node.storedValue as any)[name] = preProcessedSnapshot[name]\n }\n }\n\n applySnapshotPreProcessor(snapshot: any) {\n const processor = this.preProcessor\n return processor ? processor.call(null, snapshot) : snapshot\n }\n\n applySnapshotPostProcessor(snapshot: any) {\n const postProcessor = this.postProcessor\n if (postProcessor) {\n return postProcessor.call(null, snapshot)\n }\n return snapshot\n }\n\n getChildType(propertyName: string): IAnyType {\n assertIsString(propertyName, 1)\n\n return this.properties[propertyName]!\n }\n\n isValidSnapshot(\n value: this[\"C\"],\n context: IValidationContext\n ): IValidationResult {\n const snapshot = this.applySnapshotPreProcessor(value)\n\n if (!isPlainObject(snapshot)) {\n return typeCheckFailure(context, snapshot, \"Value is not a plain object\")\n }\n\n for (const key of this.propertyNames) {\n const propType = this.properties[key]!\n getContextForPath(context, key, propType)\n const errors = propType.validate(snapshot[key], context)\n popContext(context)\n if (errors.length > 0) {\n return errors\n }\n }\n return typeCheckSuccess()\n }\n\n override describe() {\n // optimization: cache\n return `{ ${this.propertyNames\n .map(key => `${key}: ${this.properties[key]!.describe()}`)\n .join(\"; \")} }`\n }\n\n getDefaultSnapshot(): this[\"C\"] {\n return EMPTY_OBJECT as this[\"C\"]\n }\n\n removeChild(node: this[\"N\"], subpath: string) {\n ;(node.storedValue as any)[subpath] = undefined\n }\n}\nModelType.prototype.applySnapshot = action(ModelType.prototype.applySnapshot)\n\ntype ModelTypeSelf = ModelType<\n ModelProperties,\n unknown,\n unknown,\n unknown,\n IAnyModelType\n>\n\n// Chain steps shared by every model type; see the field declarations in the\n// class for why they are not own slots.\nObject.assign(ModelType.prototype as object, {\n named(this: ModelTypeSelf, name: string) {\n return this.cloneAndEnhance({ name })\n },\n props(this: ModelTypeSelf, properties: ModelPropertiesDeclaration) {\n return this.cloneAndEnhance({ properties })\n },\n preProcessSnapshot(\n this: ModelTypeSelf,\n preProcessor: (snapshot: unknown) => unknown\n ) {\n const currentPreprocessor = this.preProcessor\n if (!currentPreprocessor) {\n return this.cloneAndEnhance({ preProcessor })\n } else {\n return this.cloneAndEnhance({\n preProcessor: snapshot => currentPreprocessor(preProcessor(snapshot))\n })\n }\n },\n postProcessSnapshot(\n this: ModelTypeSelf,\n postProcessor: (snapshot: unknown) => unknown\n ) {\n const currentPostprocessor = this.postProcessor\n if (!currentPostprocessor) {\n return this.cloneAndEnhance({ postProcessor })\n } else {\n return this.cloneAndEnhance({\n postProcessor: snapshot => postProcessor(currentPostprocessor(snapshot))\n })\n }\n }\n})\n\nexport function model<P extends ModelPropertiesDeclaration = {}>(\n name: string,\n properties?: P\n): IModelType<ModelPropertiesDeclarationToProperties<P>, {}>\nexport function model<P extends ModelPropertiesDeclaration = {}>(\n properties?: P\n): IModelType<ModelPropertiesDeclarationToProperties<P>, {}>\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 */\nexport function model(...args: any[]): any {\n if (devMode() && typeof args[0] !== \"string\" && args[1]) {\n throw fail(\n \"Model creation failed. First argument must be a string when two arguments are provided\"\n )\n }\n\n const name = typeof args[0] === \"string\" ? args.shift() : ANONYMOUS_MODEL_NAME\n const properties = args.shift() || {}\n return new ModelType({ name, properties })\n}\n\n/** @hidden */\nexport type _CustomJoin<A, B> = A extends _NotCustomized ? B : A & B\n\n// generated with C:\\VSProjects\\github\\mobx-state-tree-upstream\\packages\\mobx-state-tree\\scripts\\generate-compose-type.js\n// prettier-ignore\nexport function compose<PA extends ModelProperties, OA, FCA, FSA, PB extends ModelProperties, OB, FCB, FSB>(name: string, A: IModelType<PA, OA, FCA, FSA>, B: IModelType<PB, OB, FCB, FSB>): IModelType<_OverrideProps<PA, PB>, OA & OB, _CustomJoin<FCA, FCB>, _CustomJoin<FSA, FSB>>\n// prettier-ignore\nexport function compose<PA extends ModelProperties, OA, FCA, FSA, PB extends ModelProperties, OB, FCB, FSB>(A: IModelType<PA, OA, FCA, FSA>, B: IModelType<PB, OB, FCB, FSB>): IModelType<_OverrideProps<PA, PB>, OA & OB, _CustomJoin<FCA, FCB>, _CustomJoin<FSA, FSB>>\n// prettier-ignore\nexport function compose<PA extends ModelProperties, OA, FCA, FSA, PB extends ModelProperties, OB, FCB, FSB, PC extends ModelProperties, OC, FCC, FSC>(name: string, A: IModelType<PA, OA, FCA, FSA>, B: IModelType<PB, OB, FCB, FSB>, C: IModelType<PC, OC, FCC, FSC>): IModelType<_OverrideProps<_OverrideProps<PA, PB>, PC>, OA & OB & OC, _CustomJoin<FCA, _CustomJoin<FCB, FCC>>, _CustomJoin<FSA, _CustomJoin<FSB, FSC>>>\n// prettier-ignore\nexport function compose<PA extends ModelProperties, OA, FCA, FSA, PB extends ModelProperties, OB, FCB, FSB, PC extends ModelProperties, OC, FCC, FSC>(A: IModelType<PA, OA, FCA, FSA>, B: IModelType<PB, OB, FCB, FSB>, C: IModelType<PC, OC, FCC, FSC>): IModelType<_OverrideProps<_OverrideProps<PA, PB>, PC>, OA & OB & OC, _CustomJoin<FCA, _CustomJoin<FCB, FCC>>, _CustomJoin<FSA, _CustomJoin<FSB, FSC>>>\n// prettier-ignore\nexport function compose<PA extends ModelProperties, OA, FCA, FSA, PB extends ModelProperties, OB, FCB, FSB, PC extends ModelProperties, OC, FCC, FSC, PD extends ModelProperties, OD, FCD, FSD>(name: string, A: IModelType<PA, OA, FCA, FSA>, B: IModelType<PB, OB, FCB, FSB>, C: IModelType<PC, OC, FCC, FSC>, D: IModelType<PD, OD, FCD, FSD>): IModelType<_OverrideProps<_OverrideProps<_OverrideProps<PA, PB>, PC>, PD>, OA & OB & OC & OD, _CustomJoin<FCA, _CustomJoin<FCB, _CustomJoin<FCC, FCD>>>, _CustomJoin<FSA, _CustomJoin<FSB, _CustomJoin<FSC, FSD>>>>\n// prettier-ignore\nexport function compose<PA extends ModelProperties, OA, FCA, FSA, PB extends ModelProperties, OB, FCB, FSB, PC extends ModelProperties, OC, FCC, FSC, PD extends ModelProperties, OD, FCD, FSD>(A: IModelType<PA, OA, FCA, FSA>, B: IModelType<PB, OB, FCB, FSB>, C: IModelType<PC, OC, FCC, FSC>, D: IModelType<PD, OD, FCD, FSD>): IModelType<_OverrideProps<_OverrideProps<_OverrideProps<PA, PB>, PC>, PD>, OA & OB & OC & OD, _CustomJoin<FCA, _CustomJoin<FCB, _CustomJoin<FCC, FCD>>>, _CustomJoin<FSA, _CustomJoin<FSB, _CustomJoin<FSC, FSD>>>>\n// prettier-ignore\nexport function compose<PA extends ModelProperties, OA, FCA, FSA, PB extends ModelProperties, OB, FCB, FSB, PC extends ModelProperties, OC, FCC, FSC, PD extends ModelProperties, OD, FCD, FSD, PE extends ModelProperties, OE, FCE, FSE>(name: string, A: IModelType<PA, OA, FCA, FSA>, B: IModelType<PB, OB, FCB, FSB>, C: IModelType<PC, OC, FCC, FSC>, D: IModelType<PD, OD, FCD, FSD>, E: IModelType<PE, OE, FCE, FSE>): IModelType<_OverrideProps<_OverrideProps<_OverrideProps<_OverrideProps<PA, PB>, PC>, PD>, PE>, OA & OB & OC & OD & OE, _CustomJoin<FCA, _CustomJoin<FCB, _CustomJoin<FCC, _CustomJoin<FCD, FCE>>>>, _CustomJoin<FSA, _CustomJoin<FSB, _CustomJoin<FSC, _CustomJoin<FSD, FSE>>>>>\n// prettier-ignore\nexport function compose<PA extends ModelProperties, OA, FCA, FSA, PB extends ModelProperties, OB, FCB, FSB, PC extends ModelProperties, OC, FCC, FSC, PD extends ModelProperties, OD, FCD, FSD, PE extends ModelProperties, OE, FCE, FSE>(A:\n IModelType<PA, OA, FCA, FSA>, B: IModelType<PB, OB, FCB, FSB>, C: IModelType<PC, OC, FCC, FSC>, D: IModelType<PD, OD, FCD, FSD>, E: IModelType<PE, OE, FCE, FSE>): IModelType<_OverrideProps<_OverrideProps<_OverrideProps<_OverrideProps<PA, PB>, PC>, PD>, PE>, OA & OB & OC & OD & OE, _CustomJoin<FCA,\n _CustomJoin<FCB, _CustomJoin<FCC, _CustomJoin<FCD, FCE>>>>, _CustomJoin<FSA, _CustomJoin<FSB, _CustomJoin<FSC, _CustomJoin<FSD, FSE>>>>>\n// prettier-ignore\nexport function compose<PA extends ModelProperties, OA, FCA, FSA, PB extends ModelProperties, OB, FCB, FSB, PC extends ModelProperties, OC, FCC, FSC, PD extends ModelProperties, OD, FCD, FSD, PE extends ModelProperties, OE, FCE, FSE, PF\n extends ModelProperties, OF, FCF, FSF>(name: string, A: IModelType<PA, OA, FCA, FSA>, B: IModelType<PB, OB, FCB, FSB>, C: IModelType<PC, OC, FCC, FSC>, D: IModelType<PD, OD, FCD, FSD>, E: IModelType<PE, OE, FCE, FSE>, F: IModelType<PF, OF, FCF, FSF>): IModelType<_OverrideProps<_OverrideProps<_OverrideProps<_OverrideProps<_OverrideProps<PA, PB>, PC>, PD>, PE>, PF>, OA & OB & OC & OD & OE & OF, _CustomJoin<FCA, _CustomJoin<FCB, _CustomJoin<FCC, _CustomJoin<FCD, _CustomJoin<FCE, FCF>>>>>, _CustomJoin<FSA, _CustomJoin<FSB, _CustomJoin<FSC, _CustomJoin<FSD, _CustomJoin<FSE, FSF>>>>>>\n// prettier-ignore\nexport function compose<PA extends ModelProperties, OA, FCA, FSA, PB extends ModelProperties, OB, FCB, FSB, PC extends ModelProperties, OC, FCC, FSC, PD extends ModelProperties, OD, FCD, FSD, PE extends ModelProperties, OE, FCE, FSE, PF\n extends ModelProperties, OF, FCF, FSF>(A: IModelType<PA, OA, FCA, FSA>, B: IModelType<PB, OB, FCB, FSB>, C: IModelType<PC, OC, FCC, FSC>, D: IModelType<PD, OD, FCD, FSD>, E: IModelType<PE, OE, FCE, FSE>, F: IModelType<PF, OF, FCF, FSF>): IModelType<_OverrideProps<_OverrideProps<_OverrideProps<_OverrideProps<_OverrideProps<PA, PB>, PC>, PD>, PE>, PF>, OA & OB & OC & OD & OE & OF, _CustomJoin<FCA, _CustomJoin<FCB, _CustomJoin<FCC, _CustomJoin<FCD, _CustomJoin<FCE, FCF>>>>>, _CustomJoin<FSA, _CustomJoin<FSB, _CustomJoin<FSC, _CustomJoin<FSD, _CustomJoin<FSE, FSF>>>>>>\n// prettier-ignore\nexport function compose<PA extends ModelProperties, OA, FCA, FSA, PB extends ModelProperties, OB, FCB, FSB, PC extends ModelProperties, OC, FCC, FSC, PD extends ModelProperties, OD, FCD, FSD, PE extends ModelProperties, OE, FCE, FSE, PF\n extends ModelProperties, OF, FCF, FSF, PG extends ModelProperties, OG, FCG, FSG>(name: string, A: IModelType<PA, OA, FCA, FSA>, B: IModelType<PB, OB, FCB, FSB>, C: IModelType<PC, OC, FCC, FSC>, D: IModelType<PD, OD, FCD, FSD>, E: IModelType<PE, OE, FCE, FSE>, F: IModelType<PF, OF, FCF, FSF>, G: IModelType<PG, OG, FCG, FSG>): IModelType<_OverrideProps<_OverrideProps<_OverrideProps<_OverrideProps<_OverrideProps<_OverrideProps<PA, PB>, PC>, PD>, PE>, PF>, PG>, OA & OB & OC & OD & OE & OF & OG, _CustomJoin<FCA, _CustomJoin<FCB, _CustomJoin<FCC, _CustomJoin<FCD, _CustomJoin<FCE, _CustomJoin<FCF, FCG>>>>>>, _CustomJoin<FSA, _CustomJoin<FSB, _CustomJoin<FSC, _CustomJoin<FSD, _CustomJoin<FSE, _CustomJoin<FSF, FSG>>>>>>>\n// prettier-ignore\nexport function compose<PA extends ModelProperties, OA, FCA, FSA, PB extends ModelProperties, OB, FCB, FSB, PC extends ModelProperties, OC, FCC, FSC, PD extends ModelProperties, OD, FCD, FSD, PE extends ModelProperties, OE, FCE, FSE, PF\n extends ModelProperties, OF, FCF, FSF, PG extends ModelProperties, OG, FCG, FSG>(A: IModelType<PA, OA, FCA, FSA>, B: IModelType<PB, OB, FCB, FSB>, C: IModelType<PC, OC, FCC, FSC>, D: IModelType<PD, OD, FCD, FSD>, E: IModelType<PE, OE, FCE, FSE>, F: IModelType<PF, OF, FCF, FSF>, G: IModelType<PG, OG, FCG, FSG>): IModelType<_OverrideProps<_OverrideProps<_OverrideProps<_OverrideProps<_OverrideProps<_OverrideProps<PA, PB>, PC>, PD>, PE>, PF>, PG>, OA & OB & OC & OD & OE & OF & OG, _CustomJoin<FCA, _CustomJoin<FCB, _CustomJoin<FCC, _CustomJoin<FCD, _CustomJoin<FCE, _CustomJoin<FCF, FCG>>>>>>, _CustomJoin<FSA, _CustomJoin<FSB, _CustomJoin<FSC, _CustomJoin<FSD, _CustomJoin<FSE, _CustomJoin<FSF, FSG>>>>>>>\n// prettier-ignore\nexport function compose<PA extends ModelProperties, OA, FCA, FSA, PB extends ModelProperties, OB, FCB, FSB, PC extends ModelProperties, OC, FCC, FSC, PD extends ModelProperties, OD, FCD, FSD, PE extends ModelProperties, OE, FCE, FSE, PF\n extends ModelProperties, OF, FCF, FSF, PG extends ModelProperties, OG, FCG, FSG, PH extends ModelProperties, OH, FCH, FSH>(name: string, A: IModelType<PA, OA, FCA, FSA>, B: IModelType<PB, OB, FCB, FSB>, C: IModelType<PC, OC, FCC, FSC>, D: IModelType<PD, OD, FCD, FSD>, E: IModelType<PE, OE, FCE, FSE>, F: IModelType<PF, OF, FCF, FSF>, G: IModelType<PG, OG, FCG, FSG>, H: IModelType<PH, OH, FCH, FSH>): IModelType<_OverrideProps<_OverrideProps<_OverrideProps<_OverrideProps<_OverrideProps<_OverrideProps<_OverrideProps<PA, PB>, PC>, PD>, PE>, PF>, PG>, PH>, OA & OB & OC & OD & OE & OF & OG & OH, _CustomJoin<FCA, _CustomJoin<FCB, _CustomJoin<FCC, _CustomJoin<FCD, _CustomJoin<FCE, _CustomJoin<FCF, _CustomJoin<FCG, FCH>>>>>>>, _CustomJoin<FSA, _CustomJoin<FSB, _CustomJoin<FSC, _CustomJoin<FSD, _CustomJoin<FSE, _CustomJoin<FSF, _CustomJoin<FSG, FSH>>>>>>>>\n// prettier-ignore\nexport function compose<PA extends ModelProperties, OA, FCA, FSA, PB extends ModelProperties, OB, FCB, FSB, PC extends ModelProperties, OC, FCC, FSC, PD extends ModelProperties, OD, FCD, FSD, PE extends ModelProperties, OE, FCE, FSE, PF\n extends ModelProperties, OF, FCF, FSF, PG extends ModelProperties, OG, FCG, FSG, PH extends ModelProperties, OH, FCH, FSH>(A: IModelType<PA, OA, FCA, FSA>, B: IModelType<PB, OB, FCB, FSB>, C: IModelType<PC, OC, FCC, FSC>, D: IModelType<PD, OD, FCD, FSD>, E: IModelType<PE, OE, FCE, FSE>, F: IModelType<PF, OF, FCF, FSF>, G: IModelType<PG, OG, FCG, FSG>, H: IModelType<PH, OH, FCH, FSH>): IModelType<_OverrideProps<_OverrideProps<_OverrideProps<_OverrideProps<_OverrideProps<_OverrideProps<_OverrideProps<PA, PB>, PC>, PD>, PE>, PF>, PG>, PH>, OA & OB & OC & OD & OE & OF & OG & OH, _CustomJoin<FCA, _CustomJoin<FCB, _CustomJoin<FCC, _CustomJoin<FCD, _CustomJoin<FCE, _CustomJoin<FCF, _CustomJoin<FCG, FCH>>>>>>>, _CustomJoin<FSA, _CustomJoin<FSB, _CustomJoin<FSC, _CustomJoin<FSD, _CustomJoin<FSE, _CustomJoin<FSF, _CustomJoin<FSG, FSH>>>>>>>>\n// prettier-ignore\nexport function compose<PA extends ModelProperties, OA, FCA, FSA, PB extends ModelProperties, OB, FCB, FSB, PC extends ModelProperties, OC, FCC, FSC, PD extends ModelProperties, OD, FCD, FSD, PE extends ModelProperties, OE, FCE, FSE, PF\n extends ModelProperties, OF, FCF, FSF, PG extends ModelProperties, OG, FCG, FSG, PH extends ModelProperties, OH, FCH, FSH, PI extends ModelProperties, OI, FCI, FSI>(name: string, A: IModelType<PA, OA, FCA, FSA>, B: IModelType<PB, OB, FCB, FSB>, C: IModelType<PC, OC, FCC, FSC>, D: IModelType<PD, OD, FCD, FSD>, E: IModelType<PE, OE, FCE, FSE>, F: IModelType<PF, OF, FCF, FSF>, G: IModelType<PG, OG, FCG, FSG>, H: IModelType<PH, OH, FCH, FSH>, I: IModelType<PI, OI, FCI, FSI>): IModelType<_OverrideProps<_OverrideProps<_OverrideProps<_OverrideProps<_OverrideProps<_OverrideProps<_OverrideProps<_OverrideProps<PA, PB>, PC>, PD>, PE>, PF>, PG>, PH>, PI>, OA & OB & OC & OD & OE & OF & OG & OH & OI, _CustomJoin<FCA, _CustomJoin<FCB, _CustomJoin<FCC, _CustomJoin<FCD, _CustomJoin<FCE, _CustomJoin<FCF, _CustomJoin<FCG, _CustomJoin<FCH, FCI>>>>>>>>, _CustomJoin<FSA, _CustomJoin<FSB, _CustomJoin<FSC, _CustomJoin<FSD, _CustomJoin<FSE, _CustomJoin<FSF, _CustomJoin<FSG, _CustomJoin<FSH, FSI>>>>>>>>>\n// prettier-ignore\nexport function compose<PA extends ModelProperties, OA, FCA, FSA, PB extends ModelProperties, OB, FCB, FSB, PC extends ModelProperties, OC, FCC, FSC, PD extends ModelProperties, OD, FCD, FSD, PE extends ModelProperties, OE, FCE, FSE, PF\n extends ModelProperties, OF, FCF, FSF, PG extends ModelProperties, OG, FCG, FSG, PH extends ModelProperties, OH, FCH, FSH, PI extends ModelProperties, OI, FCI, FSI>(A: IModelType<PA, OA, FCA, FSA>, B: IModelType<PB, OB, FCB, FSB>, C: IModelType<PC, OC, FCC, FSC>, D: IModelType<PD, OD, FCD, FSD>, E: IModelType<PE, OE, FCE, FSE>, F: IModelType<PF, OF, FCF, FSF>, G: IModelType<PG, OG, FCG, FSG>, H: IModelType<PH, OH, FCH, FSH>, I: IModelType<PI, OI, FCI, FSI>): IModelType<_OverrideProps<_OverrideProps<_OverrideProps<_OverrideProps<_OverrideProps<_OverrideProps<_OverrideProps<_OverrideProps<PA, PB>, PC>, PD>, PE>, PF>, PG>, PH>, PI>, OA & OB & OC & OD & OE & OF & OG & OH & OI, _CustomJoin<FCA, _CustomJoin<FCB, _CustomJoin<FCC, _CustomJoin<FCD, _CustomJoin<FCE, _CustomJoin<FCF, _CustomJoin<FCG, _CustomJoin<FCH, FCI>>>>>>>>, _CustomJoin<FSA, _CustomJoin<FSB, _CustomJoin<FSC, _CustomJoin<FSD, _CustomJoin<FSE, _CustomJoin<FSF, _CustomJoin<FSG, _CustomJoin<FSH, FSI>>>>>>>>>\n// prettier-ignore\nexport function compose<PA extends ModelProperties, OA, FCA, FSA, PB extends ModelProperties, OB, FCB, FSB, PC extends ModelProperties, OC, FCC, FSC, PD extends ModelProperties, OD, FCD, FSD, PE extends ModelProperties, OE, FCE, FSE, PF extends ModelProperties, OF, FCF, FSF, PG extends ModelProperties, OG, FCG, FSG, PH extends ModelProperties, OH, FCH, FSH, PI extends ModelProperties, OI, FCI, FSI, PJ extends ModelProperties, OJ, FCJ, FSJ>(name: string, A: IModelType<PA, OA, FCA, FSA>, B: IModelType<PB, OB, FCB, FSB>, C: IModelType<PC, OC, FCC, FSC>, D: IModelType<PD, OD, FCD, FSD>, E: IModelType<PE, OE, FCE, FSE>, F: IModelType<PF, OF, FCF, FSF>, G: IModelType<PG, OG, FCG, FSG>, H: IModelType<PH, OH, FCH, FSH>, I: IModelType<PI, OI, FCI, FSI>, J: IModelType<PJ, OJ, FCJ, FSJ>): IModelType<_OverrideProps<_OverrideProps<_OverrideProps<_OverrideProps<_OverrideProps<_OverrideProps<_OverrideProps<_OverrideProps<_OverrideProps<PA, PB>, PC>, PD>, PE>, PF>, PG>, PH>, PI>, PJ>, OA & OB & OC & OD & OE & OF & OG & OH & OI & OJ, _CustomJoin<FCA, _CustomJoin<FCB, _CustomJoin<FCC, _CustomJoin<FCD, _CustomJoin<FCE, _CustomJoin<FCF, _CustomJoin<FCG, _CustomJoin<FCH, _CustomJoin<FCI, FCJ>>>>>>>>>, _CustomJoin<FSA, _CustomJoin<FSB, _CustomJoin<FSC, _CustomJoin<FSD, _CustomJoin<FSE, _CustomJoin<FSF, _CustomJoin<FSG, _CustomJoin<FSH, _CustomJoin<FSI, FSJ>>>>>>>>>>\n// prettier-ignore\nexport function compose<PA extends ModelProperties, OA, FCA, FSA, PB extends ModelProperties, OB, FCB, FSB, PC extends ModelProperties, OC, FCC, FSC, PD extends ModelProperties, OD, FCD, FSD, PE extends ModelProperties, OE, FCE, FSE, PF extends ModelProperties, OF, FCF, FSF, PG extends ModelProperties, OG, FCG, FSG, PH extends ModelProperties, OH, FCH, FSH, PI extends ModelProperties, OI, FCI, FSI, PJ extends ModelProperties, OJ, FCJ, FSJ>(A: IModelType<PA, OA, FCA, FSA>, B: IModelType<PB, OB, FCB, FSB>, C: IModelType<PC, OC, FCC, FSC>, D: IModelType<PD, OD, FCD, FSD>, E: IModelType<PE, OE, FCE, FSE>, F: IModelType<PF, OF, FCF, FSF>, G: IModelType<PG, OG, FCG, FSG>, H: IModelType<PH, OH, FCH, FSH>, I: IModelType<PI, OI, FCI, FSI>, J: IModelType<PJ, OJ, FCJ, FSJ>): IModelType<_OverrideProps<_OverrideProps<_OverrideProps<_OverrideProps<_OverrideProps<_OverrideProps<_OverrideProps<_OverrideProps<_OverrideProps<PA, PB>, PC>, PD>, PE>, PF>, PG>, PH>, PI>, PJ>, OA & OB & OC & OD & OE & OF & OG & OH & OI & OJ, _CustomJoin<FCA, _CustomJoin<FCB, _CustomJoin<FCC, _CustomJoin<FCD, _CustomJoin<FCE, _CustomJoin<FCF, _CustomJoin<FCG, _CustomJoin<FCH, _CustomJoin<FCI, FCJ>>>>>>>>>, _CustomJoin<FSA, _CustomJoin<FSB, _CustomJoin<FSC, _CustomJoin<FSD, _CustomJoin<FSE, _CustomJoin<FSF, _CustomJoin<FSG, _CustomJoin<FSH, _CustomJoin<FSI, FSJ>>>>>>>>>>\n// prettier-ignore\nexport function compose<PA extends ModelProperties, OA, FCA, FSA, PB extends ModelProperties, OB, FCB, FSB, PC extends ModelProperties, OC, FCC, FSC, PD extends ModelProperties, OD, FCD, FSD, PE extends ModelProperties, OE, FCE, FSE, PF extends ModelProperties, OF, FCF, FSF, PG extends ModelProperties, OG, FCG, FSG, PH extends ModelProperties, OH, FCH, FSH, PI extends ModelProperties, OI, FCI, FSI, PJ extends ModelProperties, OJ, FCJ, FSJ, PK extends ModelProperties, OK, FCK, FSK>(name: string, A: IModelType<PA, OA, FCA, FSA>, B: IModelType<PB, OB, FCB, FSB>, C: IModelType<PC, OC, FCC, FSC>, D: IModelType<PD, OD, FCD, FSD>, E: IModelType<PE, OE, FCE, FSE>, F: IModelType<PF, OF, FCF, FSF>, G: IModelType<PG, OG, FCG, FSG>, H: IModelType<PH, OH, FCH, FSH>, I: IModelType<PI, OI, FCI, FSI>, J: IModelType<PJ, OJ, FCJ, FSJ>, K: IModelType<PK, OK, FCK, FSK>): IModelType<_OverrideProps<_OverrideProps<_OverrideProps<_OverrideProps<_OverrideProps<_OverrideProps<_OverrideProps<_OverrideProps<_OverrideProps<_OverrideProps<PA, PB>, PC>, PD>, PE>, PF>, PG>, PH>, PI>, PJ>, PK>, OA & OB & OC & OD & OE & OF & OG & OH & OI & OJ & OK, _CustomJoin<FCA, _CustomJoin<FCB, _CustomJoin<FCC, _CustomJoin<FCD, _CustomJoin<FCE, _CustomJoin<FCF, _CustomJoin<FCG, _CustomJoin<FCH, _CustomJoin<FCI, _CustomJoin<FCJ, FCK>>>>>>>>>>, _CustomJoin<FSA, _CustomJoin<FSB, _CustomJoin<FSC, _CustomJoin<FSD, _CustomJoin<FSE, _CustomJoin<FSF, _CustomJoin<FSG, _CustomJoin<FSH, _CustomJoin<FSI, _CustomJoin<FSJ, FSK>>>>>>>>>>>\n// prettier-ignore\nexport function compose<PA extends ModelProperties, OA, FCA, FSA, PB extends ModelProperties, OB, FCB, FSB, PC extends ModelProperties, OC, FCC, FSC, PD extends ModelProperties, OD, FCD, FSD, PE extends ModelProperties, OE, FCE, FSE, PF extends ModelProperties, OF, FCF, FSF, PG extends ModelProperties, OG, FCG, FSG, PH extends ModelProperties, OH, FCH, FSH, PI extends ModelProperties, OI, FCI, FSI, PJ extends ModelProperties, OJ, FCJ, FSJ, PK extends ModelProperties, OK, FCK, FSK>(A: IModelType<PA, OA, FCA, FSA>, B: IModelType<PB, OB, FCB, FSB>, C: IModelType<PC, OC, FCC, FSC>, D: IModelType<PD, OD, FCD, FSD>, E: IModelType<PE, OE, FCE, FSE>, F: IModelType<PF, OF, FCF, FSF>, G: IModelType<PG, OG, FCG, FSG>, H: IModelType<PH, OH, FCH, FSH>, I: IModelType<PI, OI, FCI, FSI>, J: IModelType<PJ, OJ, FCJ, FSJ>, K: IModelType<PK, OK, FCK, FSK>): IModelType<_OverrideProps<_OverrideProps<_OverrideProps<_OverrideProps<_OverrideProps<_OverrideProps<_OverrideProps<_OverrideProps<_OverrideProps<_OverrideProps<PA, PB>, PC>, PD>, PE>, PF>, PG>, PH>, PI>, PJ>, PK>, OA & OB & OC & OD & OE & OF & OG & OH & OI & OJ & OK, _CustomJoin<FCA, _CustomJoin<FCB, _CustomJoin<FCC, _CustomJoin<FCD, _CustomJoin<FCE, _CustomJoin<FCF, _CustomJoin<FCG, _CustomJoin<FCH, _CustomJoin<FCI, _CustomJoin<FCJ, FCK>>>>>>>>>>, _CustomJoin<FSA, _CustomJoin<FSB, _CustomJoin<FSC, _CustomJoin<FSD, _CustomJoin<FSE, _CustomJoin<FSF, _CustomJoin<FSG, _CustomJoin<FSH, _CustomJoin<FSI, _CustomJoin<FSJ, FSK>>>>>>>>>>>\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 */\nexport function compose(...args: any[]): any {\n // TODO: just join the base type names if no name is provided\n const hasTypename = typeof args[0] === \"string\"\n const typeName: string = hasTypename ? args[0] : ANONYMOUS_MODEL_NAME\n if (hasTypename) {\n args.shift()\n }\n\n // check all parameters\n if (devMode()) {\n args.forEach((type, i) => {\n assertArg(\n type,\n isModelType,\n \"mobx-state-tree model type\",\n hasTypename ? i + 2 : i + 1\n )\n })\n }\n\n return args\n .reduce((prev, cur) =>\n prev.cloneAndEnhance({\n name: `${prev.name}_${cur.name}`,\n properties: cur.properties,\n // cur.properties is another ModelType's already-converted+frozen bag\n propertiesAreConverted: true,\n initializers: cur.initializers,\n preProcessor: (snapshot: any) =>\n cur.applySnapshotPreProcessor(\n prev.applySnapshotPreProcessor(snapshot)\n ),\n postProcessor: (snapshot: any) =>\n cur.applySnapshotPostProcessor(\n prev.applySnapshotPostProcessor(snapshot)\n )\n })\n )\n .named(typeName)\n}\n\n/**\n * Returns if a given value represents a model type.\n *\n * @param type\n * @returns\n */\nexport function isModelType<IT extends IAnyModelType = IAnyModelType>(\n type: IAnyType\n): type is IT {\n return isType(type) && (type.flags & TypeFlags.Object) > 0\n}\n\n/**\n * `extendInstance` - attaches additional actions, views and volatile state to an\n * already-created model instance, using the same instantiation machinery as\n * `.extend()`. This enables lazily loading a model's views/actions chain: create\n * the model with only its base props (plus any critical-path members), then attach\n * the rest at runtime — e.g. from a dynamically imported module — without rebuilding\n * the type or re-hydrating the tree.\n *\n * The extension is applied inside an action context, so it works on protected trees.\n * Attached views are computeds (reactive, memoized) and attached actions get a full\n * MST action context, exactly like members declared in the original chain.\n *\n * Note: the attached members are NOT part of the instance's *static* type. If you\n * need them typed, declare the augmented shape separately (an `import type` of the\n * chain's return type is erased at build time, so it costs nothing in the bundle).\n *\n * @param instance a live model instance\n * @param fn receives the instance and returns `{ actions?, views?, state? }`\n * @returns the same instance\n */\nexport function extendInstance<T extends IAnyStateTreeNode>(\n instance: T,\n fn: (self: T) => { actions?: ModelActions; views?: object; state?: object }\n): T {\n if (!isStateTreeNode(instance)) {\n throw fail(\"extendInstance expects a mobx-state-tree node\")\n }\n const type = getStateTreeNode(instance).type\n if (!isModelType(type)) {\n throw fail(\"extendInstance can only be used on model instances\")\n }\n // Views/actions/volatile are installed via defineProperty + makeObservable — the\n // same \"add\" operations the initializers perform at creation, before the\n // write-protection interceptor is attached (see finalizeNewInstance). On a live\n // instance that interceptor is already active, so run the attach inside an action\n // context: isRunningAction() then short-circuits assertWritable.\n const modelType = type as unknown as ModelType<\n any,\n any,\n any,\n any,\n IAnyModelType\n >\n const attach = createActionInvoker(instance, \"@@extendInstance\", (() => {\n modelType.applyExtensionToInstance(instance, fn(instance))\n }) as FunctionWithFlag)\n attach()\n return instance\n}\n","import {\n SimpleType,\n TypeFlags,\n createScalarNode,\n fail,\n identity,\n isFinite,\n isFloat,\n isInteger,\n isPrimitive,\n isType,\n typeCheckFailure,\n typeCheckSuccess\n} from \"../internal.ts\"\n\nimport type {\n AnyNode,\n AnyObjectNode,\n IAnyType,\n ISimpleType,\n IType,\n IValidationContext,\n IValidationResult\n} from \"../internal.ts\"\n\n// TODO: implement CoreType using types.custom ?\n/**\n * @internal\n * @hidden\n */\nexport class CoreType<C, S, T> extends SimpleType<C, S, T> {\n constructor(\n name: string,\n readonly flags: TypeFlags,\n private readonly checker: (value: C) => boolean,\n private readonly initializer: (v: C) => T = identity\n ) {\n super(name)\n }\n\n instantiate(\n parent: AnyObjectNode | null,\n subpath: string,\n environment: any,\n initialValue: C\n ): this[\"N\"] {\n return createScalarNode(this, parent, subpath, environment, initialValue)\n }\n\n override createNewInstance(snapshot: C) {\n return this.initializer(snapshot)\n }\n\n isValidSnapshot(value: C, context: IValidationContext): IValidationResult {\n if (isPrimitive(value) && this.checker(value)) {\n return typeCheckSuccess()\n }\n const typeName =\n this.name === \"Date\" ? \"Date or a unix milliseconds timestamp\" : this.name\n return typeCheckFailure(context, value, `Value is not a ${typeName}`)\n }\n}\n\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 */\nexport const string: ISimpleType<string> = new CoreType<string, string, string>(\n \"string\",\n TypeFlags.String,\n v => typeof v === \"string\"\n)\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 */\nexport const number: ISimpleType<number> = new CoreType<number, number, number>(\n \"number\",\n TypeFlags.Number,\n v => typeof v === \"number\"\n)\n\n/**\n * `types.integer` - Creates a type that can only contain an integer value.\n *\n * Example:\n * ```ts\n * const Size = types.model({\n * width: types.integer,\n * height: 10\n * })\n * ```\n */\nexport const integer: ISimpleType<number> = new CoreType<\n number,\n number,\n number\n>(\"integer\", TypeFlags.Integer, v => isInteger(v))\n\n/**\n * `types.float` - Creates a type that can only contain an float value.\n *\n * Example:\n * ```ts\n * const Size = types.model({\n * width: types.float,\n * height: 10\n * })\n * ```\n */\nexport const float: ISimpleType<number> = new CoreType<number, number, number>(\n \"float\",\n TypeFlags.Float,\n v => isFloat(v)\n)\n\n/**\n * `types.finite` - Creates a type that can only contain an finite value.\n *\n * Example:\n * ```ts\n * const Size = types.model({\n * width: types.finite,\n * height: 10\n * })\n * ```\n */\nexport const finite: ISimpleType<number> = new CoreType<number, number, number>(\n \"finite\",\n TypeFlags.Finite,\n v => isFinite(v)\n)\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 */\nexport const boolean: ISimpleType<boolean> = new CoreType<\n boolean,\n boolean,\n boolean\n>(\"boolean\", TypeFlags.Boolean, v => typeof v === \"boolean\")\n\n/**\n * `types.null` - The type of the value `null`\n */\nexport const nullType: ISimpleType<null> = new CoreType<null, null, null>(\n \"null\",\n TypeFlags.Null,\n v => v === null\n)\n\n/**\n * `types.undefined` - The type of the value `undefined`\n */\nexport const undefinedType: ISimpleType<undefined> = new CoreType<\n undefined,\n undefined,\n undefined\n>(\"undefined\", TypeFlags.Undefined, v => v === undefined)\n\nconst _DatePrimitive = new CoreType<number | Date, number, Date>(\n \"Date\",\n TypeFlags.Date,\n v => typeof v === \"number\" || v instanceof Date,\n v => (v instanceof Date ? v : new Date(v))\n)\n_DatePrimitive.getSnapshot = function (node: AnyNode) {\n return node.storedValue.getTime()\n}\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 */\nexport const DatePrimitive: IType<number | Date, number, Date> = _DatePrimitive\n\n/**\n * @internal\n * @hidden\n */\nexport function getPrimitiveFactoryFromValue(value: any): ISimpleType<any> {\n switch (typeof value) {\n case \"string\":\n return string\n case \"number\":\n return number // In the future, isInteger(value) ? integer : number would be interesting, but would be too breaking for now\n case \"boolean\":\n return boolean\n case \"object\":\n if (value instanceof Date) {\n return DatePrimitive\n }\n }\n throw fail(`Cannot determine primitive type from value ${value}`)\n}\n\n/**\n * Returns if a given value represents a primitive type.\n *\n * Returns a plain `boolean`, not a `type is IT` predicate: with the parameter\n * typed as `IT`, narrowing to `IT` was a no-op in the positive branch while\n * collapsing the negative one to `never`, so `if (!isX(t)) { t.name }` failed\n * to compile. Guards with a distinct narrowing target (`isArrayType`,\n * `isMapType`, `isModelType`) keep their predicate.\n *\n * @param type\n * @returns\n */\nexport function isPrimitiveType(type: IAnyType): boolean {\n return (\n isType(type) &&\n (type.flags &\n (TypeFlags.String |\n TypeFlags.Number |\n TypeFlags.Integer |\n TypeFlags.Float |\n TypeFlags.Finite |\n TypeFlags.Boolean |\n TypeFlags.Date)) >\n 0\n )\n}\n","import {\n type AnyObjectNode,\n type IAnyType,\n type ISimpleType,\n type IValidationContext,\n type IValidationResult,\n type Primitives,\n SimpleType,\n TypeFlags,\n createScalarNode,\n isPrimitive,\n isType,\n typeCheckFailure,\n typeCheckSuccess\n} from \"../../internal.ts\"\nimport { assertArg } from \"../../utils.ts\"\n\n/**\n * @internal\n * @hidden\n */\nexport class Literal<T> extends SimpleType<T, T, T> {\n readonly value: T\n readonly flags = TypeFlags.Literal\n\n constructor(value: T) {\n super()\n this.value = value\n }\n\n protected override computeName(): string {\n return JSON.stringify(this.value)\n }\n\n instantiate(\n parent: AnyObjectNode | null,\n subpath: string,\n environment: any,\n initialValue: this[\"C\"]\n ): this[\"N\"] {\n return createScalarNode(this, parent, subpath, environment, initialValue)\n }\n\n isValidSnapshot(\n value: this[\"C\"],\n context: IValidationContext\n ): IValidationResult {\n if (isPrimitive(value) && value === this.value) {\n return typeCheckSuccess()\n }\n return typeCheckFailure(\n context,\n value,\n `Value is not a literal ${JSON.stringify(this.value)}`\n )\n }\n}\n\n/**\n * A literal type, which additionally publishes the exact value it matches.\n * `getUnionSubtypes` of an enumeration returns these, so the members can be\n * mapped back to their values without a hand-declared interface.\n */\nexport interface ILiteralType<S extends Primitives> extends ISimpleType<S> {\n readonly value: S\n}\n\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 */\nexport function literal<S extends Primitives>(value: S): ILiteralType<S> {\n // check that the given value is a primitive\n assertArg(value, isPrimitive, \"primitive\", 1)\n\n return new Literal<S>(value)\n}\n\n/**\n * Returns if a given value represents a literal type.\n *\n * Returns a plain `boolean`, not a `type is IT` predicate: with the parameter\n * typed as `IT`, narrowing to `IT` was a no-op in the positive branch while\n * collapsing the negative one to `never`, so `if (!isX(t)) { t.name }` failed\n * to compile. Guards with a distinct narrowing target (`isArrayType`,\n * `isMapType`, `isModelType`) keep their predicate.\n *\n * @param type\n * @returns\n */\nexport function isLiteralType(type: IAnyType): boolean {\n return isType(type) && (type.flags & TypeFlags.Literal) > 0\n}\n","import {\n type AnyObjectNode,\n BaseType,\n type ExtractNodeType,\n type IAnyType,\n type IValidationContext,\n type IValidationResult,\n TypeFlags,\n assertIsType,\n getStateTreeNode,\n isStateTreeNode,\n isType,\n typeCheckFailure,\n typeCheckSuccess\n} from \"../../internal.ts\"\nimport { assertIsFunction, assertIsString } from \"../../utils.ts\"\n\nclass Refinement<IT extends IAnyType> extends BaseType<\n IT[\"CreationType\"],\n IT[\"SnapshotType\"],\n IT[\"TypeWithoutSTN\"],\n ExtractNodeType<IT>\n> {\n get flags() {\n return this._subtype.flags | TypeFlags.Refinement\n }\n\n constructor(\n name: string,\n private readonly _subtype: IT,\n private readonly _predicate: (v: IT[\"CreationType\"]) => boolean,\n private readonly _message: (v: IT[\"CreationType\"]) => string\n ) {\n super(name)\n }\n\n instantiate(\n parent: AnyObjectNode | null,\n subpath: string,\n environment: any,\n initialValue: this[\"C\"] | this[\"T\"]\n ): this[\"N\"] {\n // create the child type\n return this._subtype.instantiate(\n parent,\n subpath,\n environment,\n initialValue\n ) as any\n }\n\n override isAssignableFrom(type: IAnyType) {\n return this._subtype.isAssignableFrom(type)\n }\n\n isValidSnapshot(\n value: this[\"C\"],\n context: IValidationContext\n ): IValidationResult {\n const subtypeErrors = this._subtype.validate(value, context)\n if (subtypeErrors.length > 0) {\n return subtypeErrors\n }\n\n const snapshot = isStateTreeNode(value)\n ? getStateTreeNode(value).snapshot\n : value\n\n if (!this._predicate(snapshot)) {\n return typeCheckFailure(context, value, this._message(value))\n }\n\n return typeCheckSuccess()\n }\n\n reconcile(\n current: this[\"N\"],\n newValue: this[\"C\"] | this[\"T\"],\n parent: AnyObjectNode,\n subpath: string\n ): this[\"N\"] {\n return this._subtype.reconcile(current, newValue, parent, subpath) as any\n }\n\n getSubTypes() {\n return this._subtype\n }\n}\n\nexport function refinement<IT extends IAnyType>(\n name: string,\n type: IT,\n predicate: (snapshot: IT[\"CreationType\"]) => boolean,\n message?: string | ((v: IT[\"CreationType\"]) => string)\n): IT\nexport function refinement<IT extends IAnyType>(\n type: IT,\n predicate: (snapshot: IT[\"CreationType\"]) => boolean,\n message?: string | ((v: IT[\"CreationType\"]) => string)\n): IT\n\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 */\nexport function refinement(...args: any[]): IAnyType {\n const name =\n typeof args[0] === \"string\"\n ? args.shift()\n : isType(args[0])\n ? args[0].name\n : null\n const type = args[0]\n const predicate = args[1]\n const message = args[2]\n ? args[2]\n : (_v: any) => \"Value does not respect the refinement predicate\"\n // ensures all parameters are correct\n assertIsType(type, [1, 2])\n assertIsString(name, 1)\n assertIsFunction(predicate, [2, 3])\n assertIsFunction(message, [3, 4])\n\n return new Refinement(name, type, predicate, message)\n}\n\n/**\n * Returns if a given value is a refinement type.\n *\n * Returns a plain `boolean`, not a `type is IT` predicate: with the parameter\n * typed as `IT`, narrowing to `IT` was a no-op in the positive branch while\n * collapsing the negative one to `never`, so `if (!isX(t)) { t.name }` failed\n * to compile. Guards with a distinct narrowing target (`isArrayType`,\n * `isMapType`, `isModelType`) keep their predicate.\n *\n * @param type\n * @returns\n */\nexport function isRefinementType(type: IAnyType): boolean {\n return isType(type) && (type.flags & TypeFlags.Refinement) > 0\n}\n","import {\n type ISimpleType,\n assertIsString,\n devMode,\n literal,\n union\n} from \"../../internal.ts\"\n\n/** @hidden */\nexport type UnionStringArray<T extends readonly string[]> = T[number]\n\n// strongly typed enumeration forms for plain and readonly string arrays (when passed directly to the function).\n// with these overloads, we get correct typing for native TS string enums when we use Object.values(Enum) as Enum[] as options.\n// these overloads also allow both mutable and immutable arrays, making types.enumeration<Enum>(Object.values(Enum)) possible.\n// the only case where this doesn't work is when passing to the function an array variable with a mutable type constraint;\n// for these cases, it will just fallback and assume the type is a generic string.\nexport function enumeration<T extends readonly string[]>(\n options: T\n): ISimpleType<UnionStringArray<T>>\nexport function enumeration<T extends string>(\n name: string,\n options: T[]\n): ISimpleType<UnionStringArray<T[]>>\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 */\nexport function enumeration(\n name: string | string[],\n options?: any\n): ISimpleType<string> {\n const realOptions: string[] = typeof name === \"string\" ? options! : name\n // check all options\n if (devMode()) {\n realOptions.forEach((option, i) => {\n assertIsString(option, i + 1)\n })\n }\n const type = union(...realOptions.map(option => literal(`${option}`)))\n if (typeof name === \"string\") {\n type.name = name\n }\n return type\n}\n","import {\n type AnyObjectNode,\n BaseType,\n formatValidationErrorLines,\n type IAnyType,\n type IType,\n type IValidationContext,\n type IValidationResult,\n Literal,\n ModelType,\n TypeFlags,\n type _NotCustomized,\n assertArg,\n assertIsType,\n devMode,\n fail,\n isPlainObject,\n isStateTreeNode,\n isType,\n isTypeCheckingEnabled,\n typeCheckFailure,\n typeCheckSuccess\n} from \"../../internal.ts\"\n\nexport type ITypeDispatcher = (snapshot: any) => IAnyType\n\nexport interface UnionOptions {\n eager?: boolean\n dispatcher?: ITypeDispatcher\n // Late-bound membership: the union re-reads this thunk on every operation, so\n // members registered after construction participate in dispatch, validation\n // and — critically — reference resolution (`isAssignableFrom` is how the\n // identifier cache decides whether a node can satisfy a reference). Cannot be\n // combined with positional member types. See DynamicUnion below.\n members?: () => IAnyType[]\n // With `members` the folded name would be a moving target, so a stable\n // explicit name is offered; it is honored on any options union.\n name?: string\n}\n\n// Drill through single-subtype wrappers — optional(), refinement(),\n// snapshotProcessor(), late() — to the underlying ModelType. Discriminated-\n// union scoping keys on a member's literal `type` property, but real-world\n// members are rarely bare models (jbrowse config schemas, for instance, are\n// always optional(model) or optional(snapshotProcessor(model))). Without this\n// the scoping never engages and every failure prints every member's full\n// structure. Wrappers expose their child as `_subtype` (optional/refinement/\n// snapshotProcessor) or via `getSubType()` (late); bounded to avoid cycles.\n// Only *successful* resolutions are cached. A wrapper chain's shape is fixed at\n// construction, so once a member resolves to a ModelType it always will; but a\n// `late` member reports no subtype until its definition evaluates, and that\n// miss must stay retryable.\nconst resolvedModelTypes = new WeakMap<\n IAnyType,\n ModelType<any, any, any, any, any>\n>()\n\nfunction resolveModelType(\n type: IAnyType | undefined\n): ModelType<any, any, any, any, any> | undefined {\n if (!type) {\n return undefined\n }\n const cached = resolvedModelTypes.get(type)\n if (cached) {\n return cached\n }\n let current: IAnyType | undefined = type\n for (let depth = 0; current && depth < 20; depth++) {\n if (current instanceof ModelType) {\n resolvedModelTypes.set(type, current)\n return current\n }\n const wrapper = current as {\n _subtype?: IAnyType\n getSubType?: (mustSucceed: boolean) => IAnyType | undefined\n }\n current = wrapper._subtype ?? wrapper.getSubType?.(false)\n }\n return undefined\n}\n\n// The quick-match paths below already know a type carries TypeFlags.Literal,\n// but `is()` still routes through BaseType.validate — a context array, an entry\n// object and a `$treenode` probe per property, per candidate member. A real\n// `Literal` stores its primitive, and its isValidSnapshot is exactly value\n// equality against it, so compare directly. The `instanceof` gate is load\n// bearing: wrappers (optional, refinement, snapshotProcessor, late, union)\n// inherit the Literal flag from what they wrap and must keep the full check.\nfunction matchesLiteral(type: IAnyType, value: unknown): boolean {\n return type instanceof Literal ? type.value === value : type.is(value)\n}\n\n/**\n * @internal\n * @hidden\n */\nexport class Union extends BaseType<any, any, any> {\n // These, plus `_discriminatorCache` and `_allMembersDiscriminated` below,\n // live on the prototype and only become own slots on the union that needs\n // one. An eager, dispatcher-less union that is never instantiated and never\n // fails a typecheck carries none of them — which is every union jbrowse\n // builds per config slot, tens of thousands per session load. Same reasoning\n // as `BaseType.isType`; see agent-docs/adr/0003.\n declare private readonly _dispatcher?: ITypeDispatcher\n declare private readonly _eager: boolean\n\n private _flags?: TypeFlags\n\n // Memoized, but only once the fold is known to be stable. A `types.late`\n // member reports 0 for its subtype until its definition resolves, so a union\n // containing one must keep recomputing — and every wrapper ORs its subtype's\n // flags upward, so `Late` in the *result* is an exact test for \"some member\n // may still change\" however deeply it is nested. A resolved late still\n // reports Late, so such a union simply never caches; that is conservative in\n // the safe direction and no real-world union is built out of late members.\n //\n // This reverses an earlier decision to leave it uncached, which was sized at\n // ~4% \"on union creation alone\". That understated it: the reads are what\n // cost, not the creation. `ModelType._getIdentifierAttribute` folds every\n // property's flags on each `types.model()`, and jbrowse's config slots are\n // unions under a stripDefault, so building one schema re-folded every slot's\n // union. See agent-docs/adr/0003.\n get flags(): TypeFlags {\n const cached = this._flags\n if (cached !== undefined) {\n return cached\n }\n let result: TypeFlags = TypeFlags.Union\n for (const type of this.members()) {\n result |= type.flags\n }\n if (!(result & TypeFlags.Late)) {\n this._flags = result\n }\n return result\n }\n\n protected override computeName(): string {\n return `(${this.members()\n .map(type => type.name)\n .join(\" | \")})`\n }\n\n constructor(\n private readonly _types: IAnyType[],\n options?: UnionOptions\n ) {\n super()\n // read the options directly rather than spreading defaults into a fresh\n // object: this constructor runs once per config slot in jbrowse, and the\n // merged object was allocated only to be read twice and dropped\n if (options !== undefined) {\n if (options.dispatcher !== undefined) {\n this._dispatcher = options.dispatcher\n }\n if (options.eager === false) {\n this._eager = false\n }\n if (options.name !== undefined) {\n this.name = options.name\n }\n }\n }\n\n // The one point membership is read through, so DynamicUnion can substitute\n // its thunk without duplicating any of the scanning logic below.\n protected members(): IAnyType[] {\n return this._types\n }\n\n override isAssignableFrom(type: IAnyType) {\n return this.members().some(subType => subType.isAssignableFrom(type))\n }\n\n override describe() {\n return `(${this.members()\n .map(factory => factory.describe())\n .join(\" | \")})`\n }\n\n instantiate(\n parent: AnyObjectNode | null,\n subpath: string,\n environment: any,\n initialValue: this[\"C\"] | this[\"T\"]\n ): this[\"N\"] {\n const type = this.determineType(initialValue, undefined)\n if (!type) {\n throw fail(this.noMatchMessage(initialValue))\n } // can happen in prod builds\n return type.instantiate(parent, subpath, environment, initialValue)\n }\n\n reconcile(\n current: this[\"N\"],\n newValue: this[\"C\"] | this[\"T\"],\n parent: AnyObjectNode,\n subpath: string\n ): this[\"N\"] {\n const type = this.determineType(newValue, current.getReconciliationType())\n if (!type) {\n throw fail(this.noMatchMessage(newValue))\n } // can happen in prod builds\n return type.reconcile(current, newValue, parent, subpath)\n }\n\n private noMatchMessage(value: unknown): string {\n const base = `No matching type for union ${this.name}`\n if (!isPlainObject(value)) {\n return base\n }\n const discriminator = (value as { type?: unknown }).type\n if (typeof discriminator !== \"string\") {\n return base\n }\n const baseWithDiscriminator = `${base} for snapshot with type \"${discriminator}\"`\n // If exactly one union member has a literal `type` property matching the\n // snapshot's discriminator, run its validate() so we can append the\n // property-level reasons it didn't match. This converts the bare prod-build\n // \"no matching type\" into something diagnosable (e.g. which field was the\n // wrong type, which required field was missing) without re-bloating the\n // message back to every-member's full describe() output.\n const candidate = this._findCandidateByTypeDiscriminator(discriminator)\n if (!candidate) {\n return baseWithDiscriminator\n }\n const errors = candidate.validate(value as any, [\n { path: \"\", type: candidate }\n ])\n if (errors.length === 0) {\n return baseWithDiscriminator\n }\n return `${baseWithDiscriminator}:\\n ${formatValidationErrorLines(\n errors\n ).join(\"\\n \")}`\n }\n\n // Memoizes the discriminator -> member scan below. Union membership is fixed\n // at construction, so the result for a given `type` string never changes.\n // Without this, validating a config with many elements drawn from a wide\n // pluggable union (e.g. jbrowse's 30+ track/adapter types) re-scans every\n // member — and calls resolveModelType + literal.is() on each — once per\n // element. With it, each distinct discriminator scans once; the rest are\n // O(1) map hits. `undefined` (no match OR ambiguous) is cached too.\n declare private _discriminatorCache?: Map<string, IAnyType | undefined>\n protected _findCandidateByTypeDiscriminator(\n discriminator: string\n ): IAnyType | undefined {\n const cache = (this._discriminatorCache ??= new Map())\n if (cache.has(discriminator)) {\n return cache.get(discriminator)\n }\n const found = this._scanForTypeDiscriminator(discriminator)\n cache.set(discriminator, found)\n return found\n }\n\n protected _scanForTypeDiscriminator(\n discriminator: string\n ): IAnyType | undefined {\n let found: IAnyType | undefined\n for (const t of this.members()) {\n const model = resolveModelType(t)\n if (!model) {\n continue\n }\n const typeProp = (\n model.properties as Record<string, IAnyType | undefined>\n )[\"type\"]\n if (\n !typeProp ||\n !(typeProp.flags & TypeFlags.Literal) ||\n !matchesLiteral(typeProp, discriminator)\n ) {\n continue\n }\n if (found) {\n // Ambiguous (two members declare the same `type` literal). Fall back\n // to the short message rather than picking arbitrarily.\n return undefined\n }\n // Return the original (possibly wrapped) member, not the unwrapped\n // model, so validate()/is() still apply optional defaults and any\n // snapshotProcessor pre-processing.\n found = t\n }\n return found\n }\n\n // True when every member resolves to a model carrying a literal `type`\n // discriminator — i.e. a fully discriminated union, where a snapshot's `type`\n // uniquely identifies the intended member and no untagged catch-all member\n // could also accept it. Cached: membership is fixed at construction.\n declare private _allMembersDiscriminated?: boolean\n protected allMembersDiscriminated(): boolean {\n if (this._allMembersDiscriminated === undefined) {\n this._allMembersDiscriminated = this.computeAllMembersDiscriminated()\n }\n return this._allMembersDiscriminated\n }\n\n protected computeAllMembersDiscriminated(): boolean {\n return this.members().every(t => {\n const model = resolveModelType(t)\n const typeProp =\n model &&\n (model.properties as Record<string, IAnyType | undefined>)[\"type\"]\n return !!typeProp && (typeProp.flags & TypeFlags.Literal) !== 0\n })\n }\n\n determineType(\n value: this[\"C\"] | this[\"T\"],\n reconcileCurrentType: IAnyType | undefined\n ): IAnyType | undefined {\n // try the dispatcher, if defined\n if (this._dispatcher) {\n return this._dispatcher(value)\n }\n\n // fast path: when type checking is disabled, try quick structural matching\n // first. This skips full recursive validation of every property value, a\n // meaningful win for wide model members (e.g. jbrowse config schemas).\n if (!isTypeCheckingEnabled()) {\n const quickMatch = this.tryQuickMatch(value, reconcileCurrentType)\n if (quickMatch) {\n return quickMatch\n }\n }\n\n // find the most accomodating type\n // if we are using reconciliation try the current node type first (fix for #1045)\n if (reconcileCurrentType) {\n if (reconcileCurrentType.is(value)) {\n return reconcileCurrentType\n }\n return this.members().find(\n type => type !== reconcileCurrentType && type.is(value)\n )\n }\n return this.members().find(type => type.is(value))\n }\n\n private tryQuickMatch(\n value: any,\n reconcileCurrentType: IAnyType | undefined\n ): IAnyType | undefined {\n // state tree nodes need full type compatibility checking\n // (e.g., A.is(B.create()) must return false even if snapshots are compatible)\n if (isStateTreeNode(value)) {\n return undefined\n }\n\n // for non-object values, try primitive matching\n if (!isPlainObject(value)) {\n return this.tryMatchPrimitive(value)\n }\n\n // for objects, try structural matching against model types, preferring the\n // reconciliation type (checked first, then skipped in the main pass) so a\n // reconcile keeps its current member when it still fits — without building\n // the reordered candidate list this used to allocate on every call\n if (\n reconcileCurrentType &&\n this.snapshotLooksLikeType(value, reconcileCurrentType)\n ) {\n return reconcileCurrentType\n }\n for (const type of this.members()) {\n if (\n type !== reconcileCurrentType &&\n this.snapshotLooksLikeType(value, type)\n ) {\n return type\n }\n }\n return undefined\n }\n\n private tryMatchPrimitive(value: any): IAnyType | undefined {\n const valueType = typeof value\n for (const type of this.members()) {\n const flags = type.flags\n if (\n (valueType === \"string\" && flags & TypeFlags.String) ||\n (valueType === \"number\" &&\n flags &\n (TypeFlags.Number |\n TypeFlags.Integer |\n TypeFlags.Float |\n TypeFlags.Finite)) ||\n (valueType === \"boolean\" && flags & TypeFlags.Boolean) ||\n (value === null && flags & TypeFlags.Null) ||\n (value === undefined && flags & TypeFlags.Undefined)\n ) {\n return type\n }\n // for literals, check exact value match\n if (flags & TypeFlags.Literal) {\n if (matchesLiteral(type, value)) {\n return type\n }\n }\n }\n return undefined\n }\n\n private snapshotLooksLikeType(value: any, type: IAnyType): boolean {\n // for model types, check if snapshot has all the required property keys\n // and that any literal-typed properties match exactly. Unwrap optional() /\n // snapshotProcessor() / refinement() / late() so wrapped members (e.g.\n // jbrowse config schemas, which are always optional(model)) still match.\n const model = resolveModelType(type)\n if (model) {\n const props = model.properties\n // use cached propertyNames from ModelType instead of Object.keys()\n for (const key of model.propertyNames) {\n const propType = props[key]!\n // `flags` is a recomputed getter on the wrapper types (optional,\n // snapshotProcessor, late, union), so read it once per property\n const flags = propType.flags\n const propValue = value[key]\n\n // check required properties exist and are not undefined\n // (unless the type accepts undefined, which Optional types do)\n if (!(flags & TypeFlags.Optional)) {\n if (!(key in value) || propValue === undefined) {\n return false\n }\n }\n\n // for literal types, verify the value matches exactly\n // this is critical for discriminated unions\n if (flags & TypeFlags.Literal) {\n if (!matchesLiteral(propType, propValue)) {\n return false\n }\n }\n }\n return true\n }\n return false\n }\n\n isValidSnapshot(\n value: this[\"C\"],\n context: IValidationContext\n ): IValidationResult {\n if (this._dispatcher) {\n return this._dispatcher(value).validate(value, context)\n }\n\n // For plain-object snapshots carrying a `type` discriminator, validate only\n // the single member whose literal `type` matches.\n // - Clean validation short-circuits to success only when it is sound to skip\n // the other members: an eager union (first match wins) or a fully\n // discriminated one (no untagged catch-all could also match). A non-eager\n // union with a catch-all must still fall through so ambiguity is counted.\n // - A failure is the definitive, scoped error only when every member is\n // discriminated; otherwise a catch-all could still accept the value, so\n // fall through to full validation.\n const isSnapshotObject = isPlainObject(value) && !isStateTreeNode(value)\n if (isSnapshotObject) {\n const discriminator = (value as { type?: unknown }).type\n if (typeof discriminator === \"string\") {\n const candidate = this._findCandidateByTypeDiscriminator(discriminator)\n if (candidate) {\n const errors = candidate.validate(value, context)\n const cleanAndUnique = errors.length === 0 && this._eager\n if (cleanAndUnique || this.allMembersDiscriminated()) {\n return errors\n }\n }\n }\n }\n\n // for plain-object snapshots, prefer union members whose literal-typed\n // discriminator properties match the value (e.g. {type: \"MsaView\"})\n // so error output is scoped to the intended branch instead of every member\n const members = this.members()\n const candidates = isSnapshotObject\n ? members.filter(t => this.snapshotLooksLikeType(value, t))\n : []\n const typesToValidate = candidates.length > 0 ? candidates : members\n\n const allErrors: IValidationResult[] = []\n let applicableTypes = 0\n for (const type of typesToValidate) {\n const errors = type.validate(value, context)\n if (errors.length === 0) {\n if (this._eager) {\n return typeCheckSuccess()\n } else {\n applicableTypes++\n }\n } else {\n allErrors.push(errors)\n }\n }\n\n if (applicableTypes === 1) {\n return typeCheckSuccess()\n }\n return typeCheckFailure(\n context,\n value,\n \"No type is applicable for the union\"\n ).concat(allErrors.flat())\n }\n\n getSubTypes() {\n return this.members()\n }\n}\n\n// Defaults shared by every union; see the field declarations at the top of the\n// class for why they are not own slots.\nObject.assign(Union.prototype as object, {\n _dispatcher: undefined,\n _eager: true,\n _discriminatorCache: undefined,\n _allMembersDiscriminated: undefined\n})\n\n/**\n * @internal\n * @hidden\n *\n * A union whose membership is read fresh from a thunk on every operation, so\n * members that come into existence after the union was built — a registry of\n * pluggable types whose modules load on demand — still dispatch, validate, and\n * satisfy references. That last one is the reason this exists: reference\n * resolution asks the target type `isAssignableFrom(node.type)` through the\n * identifier cache, and a membership list frozen at construction would reject\n * every late-loaded member's instances.\n *\n * Every membership-derived cache the base class keeps is bypassed here: flags\n * and the folded name are recomputed per read, and the discriminator scan is\n * uncached so a miss stays retryable once the missing member registers. A hit\n * for a given discriminator is assumed stable — registering two members with\n * the same `type` literal at different times can leave a stale unambiguous\n * answer where the base class would have reported ambiguity.\n */\nclass DynamicUnion extends Union {\n private readonly _members: () => IAnyType[]\n\n // `declare` + the setter below, not a field: a field initializer would run\n // after super() and clobber the name the Union constructor assigns through\n // the overridden setter.\n declare private _explicitName?: string\n\n constructor(members: () => IAnyType[], options: UnionOptions) {\n super([], options)\n this._members = members\n }\n\n protected override members() {\n return this._members()\n }\n\n override get flags(): TypeFlags {\n let result: TypeFlags = TypeFlags.Union\n for (const type of this.members()) {\n result |= type.flags\n }\n return result\n }\n\n override get name(): string {\n return this._explicitName !== undefined\n ? this._explicitName\n : this.computeName()\n }\n\n override set name(value: string) {\n this._explicitName = value\n }\n\n protected override _findCandidateByTypeDiscriminator(discriminator: string) {\n return this._scanForTypeDiscriminator(discriminator)\n }\n\n protected override allMembersDiscriminated() {\n return this.computeAllMembersDiscriminated()\n }\n}\n\n// Structurally identical unions are the same object. A union built without\n// options is a pure function of its member list — `_types` is the members,\n// `_flags`, `_name`, `_discriminatorCache` and `_allMembersDiscriminated` are\n// all folds over them, and `_dispatcher`/`_eager` come only from the options\n// overload, which is never interned because a dispatcher closure is not\n// comparable. Types carry no parent, so one object can serve every use.\n//\n// jbrowse builds a union per config slot — ~20k per session load — from a\n// handful of module-level singletons, so the member tuples number in the\n// dozens. A trie of WeakMaps keyed on member identity keeps dynamically built\n// members collectable: a node is reachable only through its own key, and the\n// union it terminates is reachable only through the node.\ninterface UnionInternNode {\n union?: Union\n next?: WeakMap<IAnyType, UnionInternNode>\n}\n\nconst unionInternRoot: UnionInternNode = {}\n\nfunction internUnion(types: IAnyType[]): Union {\n let node = unionInternRoot\n for (const type of types) {\n const level = (node.next ??= new WeakMap())\n const existing = level.get(type)\n if (existing) {\n node = existing\n } else {\n node = {}\n level.set(type, node)\n }\n }\n return (node.union ??= new Union(types))\n}\n\n/**\n * Transform _NotCustomized | _NotCustomized... to _NotCustomized, _NotCustomized | A | B to A | B\n * @hidden\n */\nexport type _CustomCSProcessor<T> =\n Exclude<T, _NotCustomized> extends never\n ? _NotCustomized\n : Exclude<T, _NotCustomized>\n\n/** @hidden */\nexport interface ITypeUnion<C, S, T> extends IType<\n _CustomCSProcessor<C>,\n _CustomCSProcessor<S>,\n T\n> {}\n\n// Variadic-tuple signatures in place of the 2-to-9-member overload block that\n// `scripts/generate-union-types.js` used to emit: the member types are captured\n// as a tuple, so the result stays precise past nine members instead of falling\n// through to the `IAnyType` signature below.\n//\n// The member projections go through a mapped tuple indexed by `number` rather\n// than the direct `Types[number][\"CreationType\"]`. Both describe the same set,\n// but the direct form is one indexed access over a *union* of type parameters,\n// which TypeScript leaves deferred; mapping first resolves each member in its\n// own tuple position, so the result reduces to a plain union.\n/** @hidden */\nexport type _UnionMembersCreationType<Types extends readonly IAnyType[]> = {\n [K in keyof Types]: Types[K][\"CreationType\"]\n}[number]\n/** @hidden */\nexport type _UnionMembersSnapshotType<Types extends readonly IAnyType[]> = {\n [K in keyof Types]: Types[K][\"SnapshotType\"]\n}[number]\n/** @hidden */\nexport type _UnionMembersTypeWithoutSTN<Types extends readonly IAnyType[]> = {\n [K in keyof Types]: Types[K][\"TypeWithoutSTN\"]\n}[number]\n\n// The two-member form keeps one type parameter per member, ahead of the\n// variadic signatures. Reducing the mapped tuple still leaves each member's C/S/T\n// as an indexed access, and when a member is itself a bare type parameter —\n// `union(reference(schema), schema)` inside a generic function, which is how\n// jbrowse's `ConfigurationReference` is written — `S[\"CreationType\"]` is a\n// deferred lookup that TypeScript will not relate to the `SnapshotIn<S>` such a\n// function declares as its return. Inferring C/S/T through `IType` reads them\n// off the argument's constraint instead of deferring a lookup, so the result is\n// a type the checker can relate — at the cost of a member that is itself a bare\n// parameter contributing its constraint's C/S/T rather than its own. Two members\n// is where such call sites sit (`maybe`/`maybeNull` included); wider unions keep\n// the variadic precision.\nexport function union<CA, SA, TA, CB, SB, TB>(\n A: IType<CA, SA, TA>,\n B: IType<CB, SB, TB>\n): ITypeUnion<CA | CB, SA | SB, TA | TB>\nexport function union<Types extends [IAnyType, ...IAnyType[]]>(\n ...types: Types\n): ITypeUnion<\n _UnionMembersCreationType<Types>,\n _UnionMembersSnapshotType<Types>,\n _UnionMembersTypeWithoutSTN<Types>\n>\nexport function union<Types extends [IAnyType, ...IAnyType[]]>(\n options: UnionOptions,\n ...types: Types\n): ITypeUnion<\n _UnionMembersCreationType<Types>,\n _UnionMembersSnapshotType<Types>,\n _UnionMembersTypeWithoutSTN<Types>\n>\nexport function union<Types extends readonly IAnyType[]>(\n options: UnionOptions & { members: () => Types }\n): ITypeUnion<\n _UnionMembersCreationType<Types>,\n _UnionMembersSnapshotType<Types>,\n _UnionMembersTypeWithoutSTN<Types>\n>\n\n// manually written\nexport function union(...types: IAnyType[]): IAnyType\nexport function union(\n dispatchOrType: UnionOptions | IAnyType,\n ...otherTypes: IAnyType[]\n): IAnyType\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 * Passing `members: () => Type[]` in the options (with no positional member\n * types) creates a union whose membership is re-read from the thunk on every\n * operation, so types registered after construction — e.g. from a lazily\n * loaded module — participate in dispatch, validation and reference\n * resolution. Pair it with a `dispatcher` for snapshot dispatch and a `name`\n * for stable error messages.\n *\n * @param optionsOrType\n * @param otherTypes\n * @returns\n */\nexport function union(...args: (UnionOptions | IAnyType)[]): IAnyType {\n // One rest array, handed straight to the Union in the common case. Splitting\n // the leading argument out — whether by a `(first, ...rest)` signature that\n // rebuilds `[first, ...rest]`, or by `rest.unshift(first)` — allocates a\n // second array per union, and jbrowse builds one union per config slot. (The\n // `unshift` form is worse still: V8 inlines the spread and calls out to the\n // builtin, so it measured 3x the spread on a two-member union.) Only the\n // options overload, which nothing hot uses, pays for a copy.\n const firstIsType = isType(args[0])\n const options = firstIsType ? undefined : (args[0] as UnionOptions)\n const types = (firstIsType ? args : args.slice(1)) as IAnyType[]\n // the name is folded from the members on demand — see Union.computeName\n\n // check all options\n if (devMode()) {\n if (options) {\n assertArg(\n options,\n o => isPlainObject(o),\n \"object { eager?: boolean, dispatcher?: Function, members?: Function, name?: string }\",\n 1\n )\n }\n types.forEach((type, i) => {\n assertIsType(type, options ? i + 2 : i + 1)\n })\n }\n if (options?.members !== undefined) {\n if (types.length > 0) {\n throw fail(\n \"union(): the members option cannot be combined with positional member types\"\n )\n }\n return new DynamicUnion(options.members, options)\n }\n return options === undefined ? internUnion(types) : new Union(types, options)\n}\n\n/**\n * Returns if a given value represents a union type.\n *\n * Returns a plain `boolean`, not a `type is IT` predicate: with the parameter\n * typed as `IT`, narrowing to `IT` was a no-op in the positive branch while\n * collapsing the negative one to `never`, so `if (!isX(t)) { t.name }` failed\n * to compile. Guards with a distinct narrowing target (`isArrayType`,\n * `isMapType`, `isModelType`) keep their predicate.\n *\n * @param type\n * @returns\n */\nexport function isUnionType(type: IAnyType): boolean {\n return isType(type) && (type.flags & TypeFlags.Union) > 0\n}\n\n/**\n * Returns the member types of a union.\n *\n * Wrapper types (`optional`, `refinement`, `late`) inherit the union flag from\n * the type they wrap, so `isUnionType` is true for e.g. an optional-of-union,\n * but their `getSubTypes()` reports the single wrapped type rather than the\n * union's members. This drills through those wrappers until the union's member\n * array surfaces.\n *\n * @param type a type for which `isUnionType` is true\n * @returns the array of member types of the underlying union\n */\nexport function getUnionSubtypes(type: IAnyType): IAnyType[] {\n if (!isUnionType(type)) {\n throw fail(\"expected a union type\")\n }\n let subtypes = type.getSubTypes()\n while (\n typeof subtypes === \"object\" &&\n subtypes !== null &&\n !Array.isArray(subtypes)\n ) {\n subtypes = subtypes.getSubTypes()\n }\n if (!Array.isArray(subtypes)) {\n throw fail(\"could not extract subtypes from union type\")\n }\n return subtypes\n}\n","import {\n type AnyObjectNode,\n BaseType,\n type ExtractCSTWithSTN,\n type IAnyType,\n type IType,\n type IValidationContext,\n type IValidationResult,\n ModelType,\n TypeFlags,\n assertIsType,\n devMode,\n fail,\n isStateTreeNode,\n isType,\n typeCheckSuccess,\n typecheckInternal\n} from \"../../internal.ts\"\n\ntype IFunctionReturn<T> = () => T\n\ntype IOptionalValue<C, T> = C | IFunctionReturn<C | T>\n\n/** @hidden */\nexport type ValidOptionalValue = string | boolean | number | null | undefined\n\n/** @hidden */\nexport type ValidOptionalValues = [ValidOptionalValue, ...ValidOptionalValue[]]\n\n/**\n * @hidden\n * @internal\n */\nexport class OptionalValue<\n IT extends IAnyType,\n OptionalVals extends ValidOptionalValues\n> extends BaseType<\n IT[\"CreationType\"] | OptionalVals[number],\n IT[\"SnapshotType\"],\n IT[\"TypeWithoutSTN\"]\n> {\n private _flags?: TypeFlags\n\n // memoized once stable; see the same guard on Union.flags for why `Late` in\n // the folded result is the exact test for \"may still change\"\n get flags(): TypeFlags {\n const cached = this._flags\n if (cached !== undefined) {\n return cached\n }\n const result = this._subtype.flags | TypeFlags.Optional\n if (!(result & TypeFlags.Late)) {\n this._flags = result\n }\n return result\n }\n\n constructor(\n private readonly _subtype: IT,\n private readonly _defaultValue: IOptionalValue<\n IT[\"CreationType\"],\n IT[\"Type\"]\n >,\n readonly optionalValues: OptionalVals\n ) {\n // no name argument: reading `_subtype.name` here would force the name of\n // whatever is wrapped, and jbrowse wraps a union per config slot\n super()\n }\n\n protected override computeName(): string {\n return this._subtype.name\n }\n\n override describe() {\n return `${this._subtype.describe()}?`\n }\n\n instantiate(\n parent: AnyObjectNode | null,\n subpath: string,\n environment: any,\n initialValue: this[\"C\"] | this[\"T\"]\n ): this[\"N\"] {\n if (this.optionalValues.includes(initialValue)) {\n const defaultInstanceOrSnapshot = this.getDefaultInstanceOrSnapshot()\n return this._subtype.instantiate(\n parent,\n subpath,\n environment,\n defaultInstanceOrSnapshot\n )\n }\n return this._subtype.instantiate(parent, subpath, environment, initialValue)\n }\n\n reconcile(\n current: this[\"N\"],\n newValue: this[\"C\"] | this[\"T\"],\n parent: AnyObjectNode,\n subpath: string\n ): this[\"N\"] {\n return this._subtype.reconcile(\n current,\n !this.optionalValues.includes(newValue) && this._subtype.is(newValue)\n ? newValue\n : this.getDefaultInstanceOrSnapshot(),\n parent,\n subpath\n )\n }\n\n getDefaultInstanceOrSnapshot(): this[\"C\"] | this[\"T\"] {\n const defaultValue = this._defaultValue\n if (typeof defaultValue !== \"function\") {\n // static values are already snapshots, checked once by types.optional\n return defaultValue\n }\n const generated = (defaultValue as IFunctionReturn<this[\"C\"] | this[\"T\"]>)()\n // generator functions must always be rechecked just in case\n typecheckInternal(this, generated)\n return generated\n }\n\n isValidSnapshot(\n value: this[\"C\"],\n context: IValidationContext\n ): IValidationResult {\n // defaulted values can be skipped\n if (this.optionalValues.includes(value)) {\n return typeCheckSuccess()\n }\n // bounce validation to the sub-type\n return this._subtype.validate(value, context)\n }\n\n override isAssignableFrom(type: IAnyType) {\n return this._subtype.isAssignableFrom(type)\n }\n\n getSubTypes() {\n return this._subtype\n }\n}\n\n/** @hidden */\nexport type OptionalDefaultValueOrFunction<IT extends IAnyType> =\n | IT[\"CreationType\"]\n | IT[\"SnapshotType\"]\n | (() => ExtractCSTWithSTN<IT>)\n\n/** @hidden */\nexport interface IOptionalIType<\n IT extends IAnyType = IAnyType,\n OptionalVals extends ValidOptionalValues = ValidOptionalValues\n> extends IType<\n IT[\"CreationType\"] | OptionalVals[number],\n IT[\"SnapshotType\"],\n IT[\"TypeWithoutSTN\"]\n> {\n getDefaultInstanceOrSnapshot(): IT[\"CreationType\"] | IT[\"SnapshotType\"]\n}\n\nfunction checkOptionalPreconditions<IT extends IAnyType>(\n type: IAnyType,\n defaultValueOrFunction: OptionalDefaultValueOrFunction<IT>\n) {\n // make sure we never pass direct instances. A node is always an object, so\n // the typeof narrows first: most defaults are primitives, and reading\n // `$treenode` off a string or a number is a megamorphic miss that this runs\n // once per config slot.\n if (\n typeof defaultValueOrFunction === \"object\" &&\n isStateTreeNode(defaultValueOrFunction)\n ) {\n throw fail(\n \"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 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\nexport function optional<IT extends IAnyType>(\n type: IT,\n defaultValueOrFunction: OptionalDefaultValueOrFunction<IT>\n): IOptionalIType<IT, [undefined]>\nexport function optional<\n IT extends IAnyType,\n OptionalVals extends ValidOptionalValues\n>(\n type: IT,\n defaultValueOrFunction: OptionalDefaultValueOrFunction<IT>,\n optionalValues: OptionalVals\n): IOptionalIType<IT, OptionalVals>\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 */\nexport function optional<\n IT extends IAnyType,\n OptionalVals extends ValidOptionalValues\n>(\n type: IT,\n defaultValueOrFunction: OptionalDefaultValueOrFunction<IT>,\n optionalValues?: OptionalVals\n): IOptionalIType<IT, OptionalVals> {\n checkOptionalPreconditions(type, defaultValueOrFunction)\n\n return new OptionalValue(\n type,\n defaultValueOrFunction,\n optionalValues ? optionalValues : undefinedAsOptionalValues\n )\n}\n\nconst undefinedAsOptionalValues: [undefined] = [undefined]\n\n/**\n * Returns if a value represents an optional type.\n *\n * Returns a plain `boolean`, not a `type is IT` predicate: with the parameter\n * typed as `IT`, narrowing to `IT` was a no-op in the positive branch while\n * collapsing the negative one to `never`, so `if (!isX(t)) { t.name }` failed\n * to compile. Guards with a distinct narrowing target (`isArrayType`,\n * `isMapType`, `isModelType`) keep their predicate.\n *\n * @param type\n * @returns\n */\nexport function isOptionalType(type: IAnyType): boolean {\n return isType(type) && (type.flags & TypeFlags.Optional) > 0\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null\n}\n\n/**\n * The identifier attribute of the model a stripDefault ultimately wraps, or\n * `null` when there is none. Drills through the single-subtype wrappers the way\n * `resolveModelType` in union.ts does — that one is module-private there, and\n * this file may not reach into it.\n *\n * `null` is also the answer for an unresolved `types.late`, which only costs the\n * short-circuit, never correctness: the full structural walk still runs.\n */\nfunction resolveIdentifierAttribute(type: IAnyType): string | null {\n let current: IAnyType | undefined = type\n for (let depth = 0; current && depth < 20; depth++) {\n if (current instanceof ModelType) {\n return current.identifierAttribute ? current.identifierAttribute : null\n }\n const wrapper = current as {\n _subtype?: IAnyType\n getSubType?: (mustSucceed: boolean) => IAnyType | undefined\n }\n current = wrapper._subtype ?? wrapper.getSubType?.(false)\n }\n return null\n}\n\n/**\n * Compare a child snapshot to a stripped-default's reference snapshot: identity\n * for primitives, structural for objects/arrays.\n *\n * Walks the two snapshots in parallel and bails at the first difference. The\n * previous implementation compared `JSON.stringify(a) === JSON.stringify(b)`\n * behind a size guard, which is O(whole snapshot) on both sides — plus two\n * string allocations — even when the very first key differs. That is the normal\n * case for an identified sub-model: its snapshot has exactly the same shape as\n * the default and differs only in the identifier, so the size guard never fires\n * and every `getSnapshot` of the parent serialized both trees just to answer\n * \"no\".\n *\n * Snapshots are frozen, acyclic, JSON-ish plain data, so a plain recursive walk\n * is safe. Key order is compared too, matching what stringify comparison did:\n * the point is to answer \"is this still the default\", and the only unsafe answer\n * is a false positive (a key gets dropped from the snapshot that shouldn't be),\n * so where this can't reproduce stringify exactly — `{a: undefined}` vs\n * `{b: undefined}`, or `NaN` nested in a frozen value, both of which stringify\n * flattened into equal text — it errs toward \"not equal\" and simply keeps the\n * key. Neither shape is reachable from a model snapshot, whose key set and order\n * are fixed by its type.\n */\nfunction defaultSnapshotEquals(a: unknown, b: unknown): boolean {\n if (a === b) {\n return true\n }\n if (\n typeof a !== \"object\" ||\n a === null ||\n typeof b !== \"object\" ||\n b === null\n ) {\n return false\n }\n const aIsArray = Array.isArray(a)\n if (aIsArray !== Array.isArray(b)) {\n return false\n }\n if (aIsArray) {\n const arrayA = a as unknown[]\n const arrayB = b as unknown[]\n if (arrayA.length !== arrayB.length) {\n return false\n }\n for (let i = 0; i < arrayA.length; i++) {\n if (!defaultSnapshotEquals(arrayA[i], arrayB[i])) {\n return false\n }\n }\n return true\n }\n const objectA = a as Record<string, unknown>\n const objectB = b as Record<string, unknown>\n const keysA = Object.keys(objectA)\n const keysB = Object.keys(objectB)\n if (keysA.length !== keysB.length) {\n return false\n }\n for (let i = 0; i < keysA.length; i++) {\n const key = keysA[i]!\n if (\n key !== keysB[i] ||\n !defaultSnapshotEquals(objectA[key], objectB[key])\n ) {\n return false\n }\n }\n return true\n}\n\n/**\n * An optional type that additionally omits its key from a parent model's\n * snapshot when the value equals the (snapshotted) default. The comparison is\n * against the default *snapshot* — i.e. the subtype is instantiated with the\n * default once and its post-processed snapshot is cached — so a default whose\n * normalized form gains fields (e.g. a fileLocation gaining `locationType`)\n * still strips correctly.\n *\n * @hidden\n * @internal\n */\nexport class StripDefaultValue<\n IT extends IAnyType,\n OptionalVals extends ValidOptionalValues\n> extends OptionalValue<IT, OptionalVals> {\n // all three live on the prototype until a strip actually happens; jbrowse\n // builds one of these per config slot and most are never serialized. See\n // `BaseType.isType`.\n declare private _defaultSnapshot?: { value: IT[\"SnapshotType\"] }\n declare private _identifierAttribute?: string | null\n declare private _equalsDefaultCache?: WeakMap<object, boolean>\n\n private equalsDefault(snapshot: unknown, defaultSnapshot: unknown): boolean {\n let identifierAttribute = this._identifierAttribute\n if (identifierAttribute === undefined) {\n identifierAttribute = resolveIdentifierAttribute(this.getSubTypes())\n this._identifierAttribute = identifierAttribute\n }\n // an identified model's snapshot normally has the same shape as the default\n // and differs only here, so answering from one key beats walking every key\n // (including nested objects) until the walk reaches it\n return identifierAttribute !== null &&\n isRecord(snapshot) &&\n isRecord(defaultSnapshot) &&\n snapshot[identifierAttribute] !== defaultSnapshot[identifierAttribute]\n ? false\n : defaultSnapshotEquals(snapshot, defaultSnapshot)\n }\n\n shouldStripFromSnapshot(snapshot: IT[\"SnapshotType\"]): boolean {\n if (!this._defaultSnapshot) {\n // instantiate the subtype detached with the default and read the node's\n // snapshot, which normalizes (fills model defaults, applies the subtype's\n // own postProcess). Cached on the (singleton) type after first use.\n const node = this.getSubTypes().instantiate(\n null,\n \"\",\n undefined,\n this.getDefaultInstanceOrSnapshot()\n )\n this._defaultSnapshot = { value: node.snapshot }\n }\n const defaultSnapshot = this._defaultSnapshot.value\n let result: boolean\n if (isRecord(snapshot)) {\n // a child node's snapshot is a keepAlive computed, so a stable reference\n // means unchanged content: the same object always gets the same answer\n let cache = this._equalsDefaultCache\n if (!cache) {\n cache = new WeakMap()\n this._equalsDefaultCache = cache\n }\n const cached = cache.get(snapshot)\n if (cached === undefined) {\n result = this.equalsDefault(snapshot, defaultSnapshot)\n cache.set(snapshot, result)\n } else {\n result = cached\n }\n } else {\n result = defaultSnapshotEquals(snapshot, defaultSnapshot)\n }\n return result\n }\n}\n\nObject.assign(StripDefaultValue.prototype as object, {\n _defaultSnapshot: undefined,\n _identifierAttribute: undefined,\n _equalsDefaultCache: undefined\n})\n\n/**\n * Whether `type` is a strip-default optional whose current child `snapshot`\n * equals its default and should therefore be omitted from the parent model's\n * snapshot. Used by `ModelType.getSnapshot`.\n *\n * @hidden\n * @internal\n */\nexport function shouldStripChildFromSnapshot(\n type: IAnyType,\n snapshot: unknown\n): boolean {\n return (\n type instanceof StripDefaultValue && type.shouldStripFromSnapshot(snapshot)\n )\n}\n\n/**\n * `types.stripDefault` - Like `types.optional`, but the property is omitted from\n * a parent model's snapshot entirely when its value equals the default (instead\n * of being serialized with the default value). Lets a model produce minimal\n * snapshots without a bespoke `postProcessSnapshot`.\n *\n * @param type\n * @param defaultValueOrFunction\n * @returns\n */\nexport function stripDefault<IT extends IAnyType>(\n type: IT,\n defaultValueOrFunction: OptionalDefaultValueOrFunction<IT>\n): IOptionalIType<IT, [undefined]> {\n checkOptionalPreconditions(type, defaultValueOrFunction)\n return new StripDefaultValue(\n type,\n defaultValueOrFunction,\n undefinedAsOptionalValues\n )\n}\n","import {\n type IAnyType,\n type IType,\n assertIsType,\n nullType,\n optional,\n undefinedType,\n union\n} from \"../../internal.ts\"\n\nconst optionalUndefinedType = optional(undefinedType, undefined)\nconst optionalNullType = optional(nullType, null)\n\n/** @hidden */\nexport interface IMaybeIType<IT extends IAnyType, C, O> extends IType<\n IT[\"CreationType\"] | C,\n IT[\"SnapshotType\"] | O,\n IT[\"TypeWithoutSTN\"] | O\n> {}\n\n/** @hidden */\nexport interface IMaybe<IT extends IAnyType> extends IMaybeIType<\n IT,\n undefined,\n undefined\n> {}\n\n/** @hidden */\nexport interface IMaybeNull<IT extends IAnyType> extends IMaybeIType<\n IT,\n null | undefined,\n null\n> {}\n\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 */\nexport function maybe<IT extends IAnyType>(type: IT): IMaybe<IT> {\n assertIsType(type, 1)\n\n return union(type, optionalUndefinedType)\n}\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 */\nexport function maybeNull<IT extends IAnyType>(type: IT): IMaybeNull<IT> {\n assertIsType(type, 1)\n\n return union(type, optionalNullType)\n}\n","import {\n type AnyObjectNode,\n BaseType,\n type ExtractNodeType,\n type IAnyType,\n type IValidationContext,\n type IValidationResult,\n TypeFlags,\n cannotDetermineSubtype,\n devMode,\n fail,\n isType,\n typeCheckSuccess\n} from \"../../internal.ts\"\n\nclass Late<IT extends IAnyType> extends BaseType<\n IT[\"CreationType\"],\n IT[\"SnapshotType\"],\n IT[\"TypeWithoutSTN\"],\n ExtractNodeType<IT>\n> {\n private _subType?: IT\n\n get flags() {\n return (this._subType ? this._subType.flags : 0) | TypeFlags.Late\n }\n\n getSubType(mustSucceed: true): IT\n getSubType(mustSucceed: false): IT | undefined\n getSubType(mustSucceed: boolean): IT | undefined {\n if (!this._subType) {\n let t = undefined\n try {\n t = this._definition()\n } catch (e) {\n if (\n e instanceof ReferenceError\n ) // can happen in strict ES5 code when a definition is self refering\n {\n t = undefined\n } else {\n throw e\n }\n }\n if (mustSucceed && t === undefined) {\n throw fail(\n \"Late type seems to be used too early, the definition (still) returns undefined\"\n )\n }\n if (t) {\n if (devMode() && !isType(t)) {\n throw fail(\n \"Failed to determine subtype, make sure types.late returns a type definition.\"\n )\n }\n this._subType = t\n }\n }\n return this._subType\n }\n\n constructor(\n name: string,\n private readonly _definition: () => IT\n ) {\n super(name)\n }\n\n instantiate(\n parent: AnyObjectNode | null,\n subpath: string,\n environment: any,\n initialValue: this[\"C\"] | this[\"T\"]\n ): this[\"N\"] {\n return this.getSubType(true).instantiate(\n parent,\n subpath,\n environment,\n initialValue\n ) as any\n }\n\n reconcile(\n current: this[\"N\"],\n newValue: this[\"C\"] | this[\"T\"],\n parent: AnyObjectNode,\n subpath: string\n ): this[\"N\"] {\n return this.getSubType(true).reconcile(\n current,\n newValue,\n parent,\n subpath\n ) as any\n }\n\n override describe() {\n const t = this.getSubType(false)\n return t ? t.name : \"<uknown late type>\"\n }\n\n isValidSnapshot(\n value: this[\"C\"],\n context: IValidationContext\n ): IValidationResult {\n const t = this.getSubType(false)\n if (!t) {\n // See #916; the variable the definition closure is pointing to wasn't defined yet, so can't be evaluted yet here\n return typeCheckSuccess()\n }\n return t.validate(value, context)\n }\n\n override isAssignableFrom(type: IAnyType) {\n const t = this.getSubType(false)\n return t ? t.isAssignableFrom(type) : false\n }\n\n getSubTypes() {\n const subtype = this.getSubType(false)\n return subtype ? subtype : cannotDetermineSubtype\n }\n}\n\nexport function late<T extends IAnyType>(type: () => T): T\nexport function late<T extends IAnyType>(name: string, type: () => T): T\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<typeof Node>\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 */\nexport function late(nameOrType: any, maybeType?: () => IAnyType): IAnyType {\n const name =\n typeof nameOrType === \"string\"\n ? nameOrType\n : `late(${nameOrType.toString()})`\n const type = typeof nameOrType === \"string\" ? maybeType : nameOrType\n // checks that the type is actually a late type\n if (devMode()) {\n if (!(typeof type === \"function\" && type.length === 0)) {\n throw fail(\n `Invalid late type, expected a function with zero arguments that returns a type, got: ${\n type\n }`\n )\n }\n }\n return new Late(name, type)\n}\n\n/**\n * Returns if a given value represents a late type.\n *\n * Returns a plain `boolean`, not a `type is IT` predicate: with the parameter\n * typed as `IT`, narrowing to `IT` was a no-op in the positive branch while\n * collapsing the negative one to `never`, so `if (!isX(t)) { t.name }` failed\n * to compile. Guards with a distinct narrowing target (`isArrayType`,\n * `isMapType`, `isModelType`) keep their predicate.\n *\n * @param type\n * @returns\n */\nexport function isLateType(type: IAnyType): boolean {\n return isType(type) && (type.flags & TypeFlags.Late) > 0\n}\n","import { type IObservableArray, action, observable, when } from \"mobx\"\n\nimport {\n type AnyNode,\n type AnyObjectNode,\n type IAnyType,\n type IType,\n type IValidationContext,\n type IValidationResult,\n SimpleType,\n TypeFlags,\n createScalarNode,\n deepFreeze,\n isSerializable,\n typeCheckFailure,\n typeCheckSuccess\n} from \"../../internal.ts\"\n\ninterface LazyOptions<T extends IType<any, any, any>, U> {\n loadType: () => Promise<T>\n shouldLoadPredicate: (parent: U) => boolean\n}\n\nexport function lazy<T extends IType<any, any, any>, U>(\n name: string,\n options: LazyOptions<T, U>\n): T {\n // TODO: fix this unknown casting to be stricter\n return new Lazy(name, options) as unknown as T\n}\n\n/**\n * @internal\n * @hidden\n */\nexport class Lazy<T extends IType<any, any, any>, U> extends SimpleType<\n T,\n T,\n T\n> {\n readonly flags = TypeFlags.Lazy\n\n private loadedType: T | null = null\n private pendingNodeList: IObservableArray<AnyNode> = observable.array()\n\n constructor(\n name: string,\n private readonly options: LazyOptions<T, U>\n ) {\n super(name)\n\n when(\n () =>\n this.pendingNodeList.length > 0 &&\n this.pendingNodeList.some(\n node =>\n node.isAlive &&\n this.options.shouldLoadPredicate(\n node.parent ? node.parent.value : null\n )\n ),\n () => {\n this.options.loadType().then(\n action((type: T) => {\n this.loadedType = type\n this.pendingNodeList.forEach(node => {\n if (!node.parent) {\n return\n }\n if (!this.loadedType) {\n return\n }\n\n node.parent.applyPatches([\n {\n op: \"replace\",\n path: `/${node.subpath}`,\n value: node.snapshot\n }\n ])\n })\n })\n )\n }\n )\n }\n\n override describe() {\n return `<lazy ${this.name}>`\n }\n\n instantiate(\n parent: AnyObjectNode | null,\n subpath: string,\n environment: any,\n value: this[\"C\"]\n ): this[\"N\"] {\n if (this.loadedType) {\n return this.loadedType.instantiate(\n parent,\n subpath,\n environment,\n value\n ) as this[\"N\"]\n }\n\n const node = createScalarNode(\n this,\n parent,\n subpath,\n environment,\n deepFreeze(value)\n )\n this.pendingNodeList.push(node)\n\n when(\n () => !node.isAlive,\n () => {\n // guard the index: splice(-1, 1) would drop an unrelated pending node\n const index = this.pendingNodeList.indexOf(node)\n if (index >= 0) {\n this.pendingNodeList.splice(index, 1)\n }\n }\n )\n\n return node\n }\n\n isValidSnapshot(\n value: this[\"C\"],\n context: IValidationContext\n ): IValidationResult {\n if (this.loadedType) {\n return this.loadedType.validate(value, context)\n }\n if (!isSerializable(value)) {\n return typeCheckFailure(\n context,\n value,\n \"Value is not serializable and cannot be lazy\"\n )\n }\n return typeCheckSuccess()\n }\n\n override reconcile(\n current: this[\"N\"],\n value: T,\n parent: AnyObjectNode,\n subpath: string\n ): this[\"N\"] {\n if (this.loadedType) {\n // a node created after load carries the loaded type: let it reconcile so\n // the instance survives applySnapshot instead of dying on every write\n const loaded: IAnyType = this.loadedType\n const currentType: IAnyType = current.type\n if (currentType === loaded) {\n return this.loadedType.reconcile(\n current,\n value,\n parent,\n subpath\n ) as this[\"N\"]\n }\n current.die()\n return this.loadedType.instantiate(\n parent,\n subpath,\n parent.environment,\n value\n ) as this[\"N\"]\n }\n return super.reconcile(current, value, parent, subpath)\n }\n}\n","import {\n type AnyObjectNode,\n type IAnyType,\n type IType,\n type IValidationContext,\n type IValidationResult,\n SimpleType,\n TypeFlags,\n createScalarNode,\n deepFreeze,\n isSerializable,\n isType,\n optional,\n typeCheckFailure,\n typeCheckSuccess\n} from \"../../internal.ts\"\n\n/**\n * @internal\n * @hidden\n */\nexport class Frozen<T> extends SimpleType<T, T, T> {\n readonly flags = TypeFlags.Frozen\n\n constructor(private subType?: IAnyType) {\n super(subType ? undefined : \"frozen\")\n }\n\n protected override computeName(): string {\n return `frozen(${this.subType!.name})`\n }\n\n override describe() {\n return \"<any immutable value>\"\n }\n\n instantiate(\n parent: AnyObjectNode | null,\n subpath: string,\n environment: any,\n value: this[\"C\"]\n ): this[\"N\"] {\n // create the node\n return createScalarNode(\n this,\n parent,\n subpath,\n environment,\n deepFreeze(value)\n )\n }\n\n isValidSnapshot(\n value: this[\"C\"],\n context: IValidationContext\n ): IValidationResult {\n if (!isSerializable(value)) {\n return typeCheckFailure(\n context,\n value,\n \"Value is not serializable and cannot be frozen\"\n )\n }\n if (this.subType) {\n return this.subType.validate(value, context)\n }\n return typeCheckSuccess()\n }\n}\n\nconst untypedFrozenInstance = new Frozen()\n\nexport function frozen<C>(subType: IType<C, any, any>): IType<C, C, C>\nexport function frozen<T>(defaultValue: T): IType<T | undefined | null, T, T>\nexport function frozen<T = any>(): IType<T, T, T> // do not assume undefined by default, let the user specify it if needed\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<TypeScriptType>()` - 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<Point>()\n * })\n * ```\n *\n * @param defaultValueOrType\n * @returns\n */\nexport function frozen(arg?: any): any {\n if (arguments.length === 0) {\n return untypedFrozenInstance\n } else if (isType(arg)) {\n return new Frozen(arg)\n } else {\n return optional(untypedFrozenInstance, arg)\n }\n}\n\n/**\n * Returns if a given value represents a frozen type.\n *\n * Returns a plain `boolean`, not a `type is IT` predicate: with the parameter\n * typed as `IT`, narrowing to `IT` was a no-op in the positive branch while\n * collapsing the negative one to `never`, so `if (!isX(t)) { t.name }` failed\n * to compile. Guards with a distinct narrowing target (`isArrayType`,\n * `isMapType`, `isModelType`) keep their predicate.\n *\n * @param type\n * @returns\n */\nexport function isFrozenType(type: IAnyType): boolean {\n return isType(type) && (type.flags & TypeFlags.Frozen) > 0\n}\n","import {\n type AnyNode,\n type AnyObjectNode,\n Hook,\n type IAnyComplexType,\n type IAnyStateTreeNode,\n type IAnyType,\n type IDisposer,\n type IMaybe,\n type IStateTreeNode,\n type IType,\n type IValidationContext,\n type IValidationResult,\n NodeLifeCycle,\n type ReferenceIdentifier,\n SimpleType,\n TypeFlags,\n applyPatch,\n assertIsType,\n createScalarNode,\n devMode,\n fail,\n getIdentifier,\n getStateTreeNode,\n isModelType,\n isStateTreeNode,\n isType,\n isValidIdentifier,\n maybe,\n normalizeIdentifier,\n typeCheckFailure,\n typeCheckSuccess\n} from \"../../internal.ts\"\n\nexport type OnReferenceInvalidatedEvent<STN extends IAnyStateTreeNode> = {\n parent: IAnyStateTreeNode\n invalidTarget: STN | undefined\n invalidId: ReferenceIdentifier\n replaceRef: (newRef: STN | null | undefined) => void\n removeRef: () => void\n cause: \"detach\" | \"destroy\" | \"invalidSnapshotReference\"\n}\n\nexport type OnReferenceInvalidated<STN extends IAnyStateTreeNode> = (\n event: OnReferenceInvalidatedEvent<STN>\n) => void\n\nfunction getInvalidationCause(hook: Hook): \"detach\" | \"destroy\" | undefined {\n switch (hook) {\n case Hook.beforeDestroy:\n return \"destroy\"\n case Hook.beforeDetach:\n return \"detach\"\n default:\n return undefined\n }\n}\n\n/** @hidden */\nexport type ReferenceT<IT extends IAnyType> = IT[\"TypeWithoutSTN\"] &\n IStateTreeNode<IReferenceType<IT>>\n\nclass StoredReference<IT extends IAnyType> {\n readonly identifier!: ReferenceIdentifier\n node!: AnyNode\n\n private resolvedReference?: {\n node: AnyObjectNode\n lastCacheModification: string\n }\n\n constructor(\n value: ReferenceT<IT> | ReferenceIdentifier,\n private readonly targetType: IT\n ) {\n if (isValidIdentifier(value)) {\n this.identifier = value\n } else if (isStateTreeNode(value)) {\n const targetNode = getStateTreeNode(value)\n if (!targetNode.identifierAttribute) {\n throw fail(\n `Can only store references with a defined identifier attribute.`\n )\n }\n const id = targetNode.unnormalizedIdentifier\n if (id === null || id === undefined) {\n throw fail(\n `Can only store references to tree nodes with a defined identifier.`\n )\n }\n this.identifier = id\n } else {\n throw fail(\n `Can only store references to tree nodes or identifiers, got: '${value}'`\n )\n }\n }\n\n private updateResolvedReference(node: AnyNode) {\n const normalizedId = normalizeIdentifier(this.identifier)\n const root = node.root\n const lastCacheModification =\n root.identifierCache!.getLastCacheModificationPerId(normalizedId)\n if (\n this.resolvedReference?.lastCacheModification !== lastCacheModification\n ) {\n const { targetType } = this\n // reference was initialized with the identifier of the target\n\n const target = root.identifierCache!.resolve(targetType, normalizedId)\n\n if (!target) {\n throw new InvalidReferenceError(\n `[mobx-state-tree] Failed to resolve reference '${this.identifier}' to type '${this.targetType.name}' (from node: ${node.path})`\n )\n }\n\n this.resolvedReference = {\n node: target,\n lastCacheModification\n }\n }\n }\n\n get resolvedValue(): ReferenceT<IT> {\n this.updateResolvedReference(this.node)\n return this.resolvedReference!.node.value\n }\n}\n\n/**\n * @internal\n * @hidden\n */\nexport class InvalidReferenceError extends Error {\n constructor(m: string) {\n super(m)\n\n Object.setPrototypeOf(this, InvalidReferenceError.prototype)\n }\n}\n\n/**\n * @internal\n * @hidden\n */\nexport abstract class BaseReferenceType<\n IT extends IAnyComplexType\n> extends SimpleType<\n ReferenceIdentifier,\n ReferenceIdentifier,\n IT[\"TypeWithoutSTN\"]\n> {\n readonly flags = TypeFlags.Reference\n\n constructor(\n protected readonly targetType: IT,\n private readonly onInvalidated?: OnReferenceInvalidated<ReferenceT<IT>>\n ) {\n super()\n }\n\n protected override computeName(): string {\n return `reference(${this.targetType.name})`\n }\n\n override isAssignableFrom(type: IAnyType): boolean {\n return this.targetType.isAssignableFrom(type)\n }\n\n isValidSnapshot(\n value: this[\"C\"],\n context: IValidationContext\n ): IValidationResult {\n return isValidIdentifier(value)\n ? typeCheckSuccess()\n : typeCheckFailure(\n context,\n value,\n \"Value is not a valid identifier, which is a string or a number\"\n )\n }\n\n private fireInvalidated(\n cause: \"detach\" | \"destroy\" | \"invalidSnapshotReference\",\n storedRefNode: this[\"N\"],\n referenceId: ReferenceIdentifier,\n refTargetNode: AnyObjectNode | null\n ) {\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 const storedRefParentNode = storedRefNode.parent\n if (!storedRefParentNode?.isAlive) {\n return\n }\n const storedRefParentValue = storedRefParentNode.storedValue\n if (!storedRefParentValue) {\n return\n }\n this.onInvalidated!({\n cause,\n parent: storedRefParentValue,\n invalidTarget: refTargetNode ? refTargetNode.storedValue : undefined,\n invalidId: referenceId,\n replaceRef(newRef) {\n applyPatch(storedRefNode.root.storedValue, {\n op: \"replace\",\n value: newRef,\n path: storedRefNode.path\n })\n },\n removeRef() {\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 private addTargetNodeWatcher(\n storedRefNode: this[\"N\"],\n referenceId: ReferenceIdentifier\n ): IDisposer | undefined {\n // this will make sure the target node becomes created\n const refTargetValue = this.getValue(storedRefNode)\n if (!refTargetValue) {\n return undefined\n }\n const refTargetNode = getStateTreeNode(refTargetValue)\n\n const hookHandler = (_: AnyNode, refTargetNodeHook: Hook) => {\n const cause = getInvalidationCause(refTargetNodeHook)\n if (!cause) {\n return\n }\n this.fireInvalidated(cause, storedRefNode, referenceId, refTargetNode)\n }\n\n const refTargetDetachHookDisposer = refTargetNode.registerHook(\n Hook.beforeDetach,\n hookHandler\n )\n const refTargetDestroyHookDisposer = refTargetNode.registerHook(\n Hook.beforeDestroy,\n hookHandler\n )\n\n return () => {\n refTargetDetachHookDisposer()\n refTargetDestroyHookDisposer()\n }\n }\n\n protected watchTargetNodeForInvalidations(\n storedRefNode: this[\"N\"],\n identifier: ReferenceIdentifier,\n customGetSet: ReferenceOptionsGetSet<IT> | undefined\n ) {\n if (!this.onInvalidated) {\n return\n }\n\n let onRefTargetDestroyedHookDisposer: IDisposer | undefined\n\n // get rid of the watcher hook when the stored ref node is destroyed\n // detached is ignored since scalar nodes (where the reference resides) cannot be detached\n storedRefNode.registerHook(Hook.beforeDestroy, () => {\n if (onRefTargetDestroyedHookDisposer) {\n onRefTargetDestroyedHookDisposer()\n }\n })\n\n const startWatching = (sync: boolean) => {\n // re-create hook in case the stored ref gets reattached\n if (onRefTargetDestroyedHookDisposer) {\n onRefTargetDestroyedHookDisposer()\n }\n\n // make sure the target node is actually there and initialized\n const storedRefParentNode = storedRefNode.parent\n const storedRefParentValue = storedRefParentNode?.storedValue\n if (\n storedRefParentNode &&\n storedRefParentNode.isAlive &&\n storedRefParentValue\n ) {\n let refTargetNodeExists: boolean\n if (customGetSet) {\n refTargetNodeExists = !!customGetSet.get(\n identifier,\n storedRefParentValue\n )\n } else {\n refTargetNodeExists = storedRefNode.root.identifierCache!.has(\n this.targetType,\n normalizeIdentifier(identifier)\n )\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(\n \"invalidSnapshotReference\",\n storedRefNode,\n identifier,\n null\n )\n }\n } else {\n onRefTargetDestroyedHookDisposer = this.addTargetNodeWatcher(\n storedRefNode,\n identifier\n )\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, () => {\n // make sure to attach it so it can start listening\n if (storedRefNode.parent) {\n storedRefNode.parent.createObservableInstanceIfNeeded()\n }\n })\n }\n // start watching once the node is attached somewhere / parent changes\n storedRefNode.registerHook(Hook.afterAttach, () => {\n startWatching(false)\n })\n }\n }\n}\n\n/**\n * @internal\n * @hidden\n */\nexport class IdentifierReferenceType<\n IT extends IAnyComplexType\n> extends BaseReferenceType<IT> {\n override getValue(storedRefNode: this[\"N\"]) {\n if (!storedRefNode.isAlive) {\n return undefined\n }\n const storedRef: StoredReference<IT> = storedRefNode.storedValue\n return storedRef.resolvedValue as any\n }\n\n override getSnapshot(storedRefNode: this[\"N\"]) {\n const ref: StoredReference<IT> = storedRefNode.storedValue\n return ref.identifier\n }\n\n instantiate(\n parent: AnyObjectNode | null,\n subpath: string,\n environment: any,\n initialValue: this[\"C\"] | this[\"T\"]\n ): this[\"N\"] {\n const identifier = isStateTreeNode(initialValue)\n ? getIdentifier(initialValue)!\n : initialValue\n const storedRef = new StoredReference(initialValue, this.targetType as any)\n const storedRefNode: this[\"N\"] = createScalarNode(\n this,\n parent,\n subpath,\n environment,\n storedRef as any\n )\n storedRef.node = storedRefNode\n this.watchTargetNodeForInvalidations(\n storedRefNode,\n identifier as string,\n undefined\n )\n return storedRefNode\n }\n\n override reconcile(\n current: this[\"N\"],\n newValue: this[\"C\"] | this[\"T\"],\n parent: AnyObjectNode,\n subpath: string\n ): this[\"N\"] {\n if (!current.isDetaching && current.type === this) {\n const compareByValue = isStateTreeNode(newValue)\n const ref: StoredReference<IT> = current.storedValue\n if (\n (!compareByValue && ref.identifier === newValue) ||\n (compareByValue && ref.resolvedValue === newValue)\n ) {\n current.setParent(parent, subpath)\n return current\n }\n }\n const newNode = this.instantiate(parent, subpath, undefined, newValue)\n current.die() // noop if detaching\n return newNode\n }\n}\n\n/**\n * @internal\n * @hidden\n */\nexport class CustomReferenceType<\n IT extends IAnyComplexType\n> extends BaseReferenceType<IT> {\n constructor(\n targetType: IT,\n private readonly options: ReferenceOptionsGetSet<IT>,\n onInvalidated?: OnReferenceInvalidated<ReferenceT<IT>>\n ) {\n super(targetType, onInvalidated)\n }\n\n override getValue(storedRefNode: this[\"N\"]) {\n if (!storedRefNode.isAlive) {\n return undefined as any\n }\n const referencedNode = this.options.get(\n storedRefNode.storedValue,\n storedRefNode.parent ? storedRefNode.parent.storedValue : null\n )\n return referencedNode\n }\n\n override getSnapshot(storedRefNode: this[\"N\"]) {\n return storedRefNode.storedValue\n }\n\n instantiate(\n parent: AnyObjectNode | null,\n subpath: string,\n environment: any,\n newValue: this[\"C\"] | this[\"T\"]\n ): this[\"N\"] {\n const identifier = isStateTreeNode(newValue)\n ? this.options.set(newValue, parent ? parent.storedValue : null)\n : newValue\n const storedRefNode: this[\"N\"] = createScalarNode(\n this,\n parent,\n subpath,\n environment,\n identifier as any\n )\n this.watchTargetNodeForInvalidations(\n storedRefNode,\n identifier as string,\n this.options\n )\n return storedRefNode\n }\n\n override reconcile(\n current: this[\"N\"],\n newValue: this[\"C\"] | this[\"T\"],\n parent: AnyObjectNode,\n subpath: string\n ): this[\"N\"] {\n const newIdentifier = isStateTreeNode(newValue)\n ? this.options.set(newValue, current ? current.storedValue : null)\n : newValue\n if (\n !current.isDetaching &&\n current.type === this &&\n current.storedValue === newIdentifier\n ) {\n current.setParent(parent, subpath)\n return current\n }\n const newNode = this.instantiate(parent, subpath, undefined, newIdentifier)\n current.die() // noop if detaching\n return newNode\n }\n}\n\nexport interface ReferenceOptionsGetSet<IT extends IAnyComplexType> {\n get(\n identifier: ReferenceIdentifier,\n parent: IAnyStateTreeNode | null\n ): ReferenceT<IT>\n set(\n value: ReferenceT<IT>,\n parent: IAnyStateTreeNode | null\n ): ReferenceIdentifier\n}\n\nexport interface ReferenceOptionsOnInvalidated<IT extends IAnyComplexType> {\n // called when the current reference is about to become invalid\n onInvalidated: OnReferenceInvalidated<ReferenceT<IT>>\n}\n\nexport type ReferenceOptions<IT extends IAnyComplexType> =\n | ReferenceOptionsGetSet<IT>\n | ReferenceOptionsOnInvalidated<IT>\n | (ReferenceOptionsGetSet<IT> & ReferenceOptionsOnInvalidated<IT>)\n\n/** @hidden */\nexport interface IReferenceType<IT extends IAnyComplexType> extends IType<\n ReferenceIdentifier,\n ReferenceIdentifier,\n IT[\"TypeWithoutSTN\"]\n> {}\n\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 */\nexport function reference<IT extends IAnyComplexType>(\n subType: IT,\n options?: ReferenceOptions<IT>\n): IReferenceType<IT> {\n assertIsType(subType, 1)\n if (devMode()) {\n if (options && typeof options === \"string\") {\n // istanbul ignore next\n throw fail(\n \"References with base path are no longer supported. Please remove the base path.\"\n )\n }\n }\n\n const getSetOptions = options\n ? (options as ReferenceOptionsGetSet<IT>)\n : undefined\n const onInvalidated = options\n ? (options as ReferenceOptionsOnInvalidated<IT>).onInvalidated\n : undefined\n\n if (getSetOptions && (getSetOptions.get || getSetOptions.set)) {\n if (devMode()) {\n if (!getSetOptions.get || !getSetOptions.set) {\n throw fail(\n \"reference options must either contain both a 'get' and a 'set' method or none of them\"\n )\n }\n }\n\n return new CustomReferenceType(\n subType,\n {\n get: getSetOptions.get,\n set: getSetOptions.set\n },\n onInvalidated\n )\n } else {\n return new IdentifierReferenceType(subType, onInvalidated)\n }\n}\n\n/**\n * Returns if a given value represents a reference type.\n *\n * Returns a plain `boolean`, not a `type is IT` predicate: with the parameter\n * typed as `IT`, narrowing to `IT` was a no-op in the positive branch while\n * collapsing the negative one to `never`, so `if (!isX(t)) { t.name }` failed\n * to compile. Guards with a distinct narrowing target (`isArrayType`,\n * `isMapType`, `isModelType`) keep their predicate.\n *\n * @param type\n * @returns\n */\nexport function isReferenceType(type: IAnyType): boolean {\n return isType(type) && (type.flags & TypeFlags.Reference) > 0\n}\n\nexport function safeReference<IT extends IAnyComplexType>(\n subType: IT,\n options: (ReferenceOptionsGetSet<IT> | object) & {\n acceptsUndefined: false\n onInvalidated?: OnReferenceInvalidated<ReferenceT<IT>>\n }\n): IReferenceType<IT>\nexport function safeReference<IT extends IAnyComplexType>(\n subType: IT,\n options?: (ReferenceOptionsGetSet<IT> | object) & {\n acceptsUndefined?: boolean\n onInvalidated?: OnReferenceInvalidated<ReferenceT<IT>>\n }\n): IMaybe<IReferenceType<IT>>\n/**\n * `types.safeReference` - A safe reference is like a standard reference, except that it accepts the undefined value by default\n * and automatically sets itself to undefined (when the parent is a model) / removes itself from arrays and maps\n * when the reference it is pointing to gets detached/destroyed.\n *\n * The optional options parameter object accepts a parameter named `acceptsUndefined`, which is set to true by default, so it is suitable\n * for model properties.\n * When used inside collections (arrays/maps), it is recommended to set this option to false so it can't take undefined as value,\n * which is usually the desired in those cases.\n * Additionally, the optional options parameter object accepts a parameter named `onInvalidated`, which will be called when the reference target node that the reference is pointing to is about to be detached/destroyed\n *\n * Strictly speaking it is a `types.maybe(types.reference(X))` (when `acceptsUndefined` is set to true, the default) and\n * `types.reference(X)` (when `acceptsUndefined` is set to false), both of them with a customized `onInvalidated` option.\n *\n * @param subType\n * @param options\n * @returns\n */\nexport function safeReference<IT extends IAnyComplexType>(\n subType: IT,\n options?: (ReferenceOptionsGetSet<IT> | object) & {\n acceptsUndefined?: boolean\n onInvalidated?: OnReferenceInvalidated<ReferenceT<IT>>\n }\n): IReferenceType<IT> | IMaybe<IReferenceType<IT>> {\n const refType = reference(subType, {\n ...options,\n onInvalidated(ev) {\n if (options && options.onInvalidated) {\n options.onInvalidated(ev)\n }\n ev.removeRef()\n }\n })\n\n if (options && options.acceptsUndefined === false) {\n return refType\n } else {\n return maybe(refType)\n }\n}\n","import {\n type AnyObjectNode,\n type IAnyType,\n type ISimpleType,\n type IValidationContext,\n type IValidationResult,\n ModelType,\n SimpleType,\n TypeFlags,\n assertArg,\n createScalarNode,\n fail,\n isType,\n typeCheckFailure,\n typeCheckSuccess\n} from \"../../internal.ts\"\n\nabstract class BaseIdentifierType<T> extends SimpleType<T, T, T> {\n readonly flags = TypeFlags.Identifier\n\n constructor(\n name: string,\n private readonly validType: \"string\" | \"number\"\n ) {\n super(name)\n }\n\n instantiate(\n parent: AnyObjectNode | null,\n subpath: string,\n environment: any,\n initialValue: this[\"C\"]\n ): this[\"N\"] {\n if (!parent || !(parent.type instanceof ModelType)) {\n throw fail(\n `Identifier types can only be instantiated as direct child of a model type`\n )\n }\n\n return createScalarNode(this, parent, subpath, environment, initialValue)\n }\n\n override reconcile(\n current: this[\"N\"],\n newValue: this[\"C\"],\n parent: AnyObjectNode,\n subpath: string\n ) {\n // we don't consider detaching here since identifier are scalar nodes, and scalar nodes cannot be detached\n if (current.storedValue !== newValue) {\n throw fail(\n `Tried to change identifier from '${current.storedValue}' to '${newValue}'. Changing identifiers is not allowed.`\n )\n }\n current.setParent(parent, subpath)\n return current\n }\n\n isValidSnapshot(\n value: this[\"C\"],\n context: IValidationContext\n ): IValidationResult {\n if (typeof value !== this.validType) {\n return typeCheckFailure(\n context,\n value,\n `Value is not a valid ${this.describe()}, expected a ${this.validType}`\n )\n }\n return typeCheckSuccess()\n }\n}\n\n/**\n * @internal\n * @hidden\n */\nexport class IdentifierType extends BaseIdentifierType<string> {\n constructor() {\n super(`identifier`, \"string\")\n }\n}\n\n/**\n * @internal\n * @hidden\n */\nexport class IdentifierNumberType extends BaseIdentifierType<number> {\n constructor() {\n super(\"identifierNumber\", \"number\")\n }\n}\n\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 */\nexport const identifier: ISimpleType<string> = new IdentifierType()\n\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 */\nexport const identifierNumber: ISimpleType<number> = new IdentifierNumberType()\n\n/**\n * Returns if a given value represents an identifier type.\n *\n * Returns a plain `boolean`, not a `type is IT` predicate: with the parameter\n * typed as `IT`, narrowing to `IT` was a no-op in the positive branch while\n * collapsing the negative one to `never`, so `if (!isX(t)) { t.name }` failed\n * to compile. Guards with a distinct narrowing target (`isArrayType`,\n * `isMapType`, `isModelType`) keep their predicate.\n *\n * @param type\n * @returns\n */\nexport function isIdentifierType(type: IAnyType): boolean {\n return isType(type) && (type.flags & TypeFlags.Identifier) > 0\n}\n\n/**\n * Valid types for identifiers.\n */\nexport type ReferenceIdentifier = string | number\n\n/**\n * @internal\n * @hidden\n */\nexport function normalizeIdentifier(id: ReferenceIdentifier): string {\n return `${id}`\n}\n\n/**\n * @internal\n * @hidden\n */\nexport function isValidIdentifier(id: any): id is ReferenceIdentifier {\n return typeof id === \"string\" || typeof id === \"number\"\n}\n\n/**\n * @internal\n * @hidden\n */\nexport function assertIsValidIdentifier(\n id: ReferenceIdentifier,\n argNumber: number | number[]\n) {\n assertArg(id, isValidIdentifier, \"string or number (identifier)\", argNumber)\n}\n","import {\n type AnyObjectNode,\n type IType,\n type IValidationContext,\n type IValidationResult,\n SimpleType,\n TypeFlags,\n createScalarNode,\n typeCheckFailure,\n typeCheckSuccess\n} from \"../../internal.ts\"\n\nexport interface CustomTypeOptions<S, T> {\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): boolean\n /** a non empty string is assumed to be a validation error */\n getValidationMessage(snapshot: S): string\n // TODO: isSnapshotEqual\n // TODO: isValueEqual\n}\n\n/**\n * `types.custom` - Creates a custom type. Custom types can be used for arbitrary immutable values, that have a serializable representation. For example, to create your own Date representation, Decimal type etc.\n *\n * The signature of the options is:\n * ```ts\n * export interface CustomTypeOptions<S, T> {\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<string, Decimal>({\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 */\nexport function custom<S, T>(\n options: CustomTypeOptions<S, T>\n): IType<S | T, S, T> {\n return new CustomType<S, T>(options)\n}\n\n/**\n * @internal\n * @hidden\n */\nexport class CustomType<S, T> extends SimpleType<S | T, S, T> {\n readonly flags = TypeFlags.Custom\n\n constructor(protected readonly options: CustomTypeOptions<S, T>) {\n super(options.name)\n }\n\n isValidSnapshot(\n value: this[\"C\"],\n context: IValidationContext\n ): IValidationResult {\n if (this.options.isTargetType(value)) {\n return typeCheckSuccess()\n }\n\n const typeError: string = this.options.getValidationMessage(value as S)\n if (typeError) {\n return typeCheckFailure(\n context,\n value,\n `Invalid value for type '${this.name}': ${typeError}`\n )\n }\n return typeCheckSuccess()\n }\n\n override getSnapshot(node: this[\"N\"]): S {\n return this.options.toSnapshot(node.storedValue)\n }\n\n instantiate(\n parent: AnyObjectNode | null,\n subpath: string,\n environment: any,\n initialValue: S | T\n ): this[\"N\"] {\n const valueToStore: T = this.options.isTargetType(initialValue)\n ? (initialValue as T)\n : this.options.fromSnapshot(initialValue as S, parent?.root.environment)\n return createScalarNode(this, parent, subpath, environment, valueToStore)\n }\n\n override reconcile(\n current: this[\"N\"],\n value: S | T,\n parent: AnyObjectNode,\n subpath: string\n ): this[\"N\"] {\n const isSnapshot = !this.options.isTargetType(value)\n // in theory customs use scalar nodes which cannot be detached, but still...\n if (!current.isDetaching) {\n const unchanged =\n current.type === this &&\n (isSnapshot\n ? value === current.snapshot\n : value === current.storedValue)\n if (unchanged) {\n current.setParent(parent, subpath)\n return current\n }\n }\n const valueToStore: T = isSnapshot\n ? this.options.fromSnapshot(value as S, parent.root.environment)\n : (value as T)\n const newNode = this.instantiate(parent, subpath, undefined, valueToStore)\n current.die() // noop if detaching\n return newNode\n }\n}\n","import {\n type AnyObjectNode,\n BaseType,\n type ExtractNodeType,\n type IAnyType,\n type IType,\n type IValidationContext,\n type IValidationResult,\n assertIsType,\n fail,\n isStateTreeNode,\n isType,\n typeCheckSuccess\n} from \"../../internal.ts\"\n\nclass Resilient<IT extends IAnyType, FT extends IAnyType> extends BaseType<\n IT[\"CreationType\"] | FT[\"CreationType\"],\n IT[\"SnapshotType\"] | FT[\"SnapshotType\"],\n IT[\"TypeWithoutSTN\"] | FT[\"TypeWithoutSTN\"],\n ExtractNodeType<IT> | ExtractNodeType<FT>\n> {\n get flags() {\n return this._subtype.flags\n }\n\n constructor(\n private readonly _subtype: IT,\n private readonly _fallbackType: FT,\n private readonly _createFallbackSnapshot: (\n error: unknown,\n snapshot: unknown\n ) => FT[\"CreationType\"]\n ) {\n super()\n }\n\n protected override computeName(): string {\n return `resilient(${this._subtype.name})`\n }\n\n override describe() {\n return `resilient(${this._subtype.describe()})`\n }\n\n private _instantiateFallback(\n parent: AnyObjectNode | null,\n subpath: string,\n environment: any,\n originalSnapshot: any,\n originalError: unknown\n ): this[\"N\"] {\n let fallbackSnapshot: FT[\"CreationType\"]\n try {\n fallbackSnapshot = this._createFallbackSnapshot(\n originalError,\n originalSnapshot\n )\n } catch (e) {\n throw fail(\n `resilient: createFallbackSnapshot threw while handling error for '${this._subtype.name}': ${originalError}. createFallbackSnapshot error: ${e}`\n )\n }\n try {\n return this._fallbackType.instantiate(\n parent,\n subpath,\n environment,\n fallbackSnapshot\n ) as this[\"N\"]\n } catch (e) {\n throw fail(\n `resilient: fallback type '${this._fallbackType.name}' failed to instantiate while handling error for '${this._subtype.name}': ${originalError}. Fallback error: ${e}`\n )\n }\n }\n\n instantiate(\n parent: AnyObjectNode | null,\n subpath: string,\n environment: any,\n initialValue: this[\"C\"] | this[\"T\"]\n ): this[\"N\"] {\n if (isStateTreeNode(initialValue)) {\n return this._subtype.instantiate(\n parent,\n subpath,\n environment,\n initialValue\n ) as this[\"N\"]\n }\n try {\n return this._subtype.instantiate(\n parent,\n subpath,\n environment,\n initialValue\n ) as this[\"N\"]\n } catch (e) {\n return this._instantiateFallback(\n parent,\n subpath,\n environment,\n initialValue,\n e\n )\n }\n }\n\n reconcile(\n current: this[\"N\"],\n newValue: this[\"C\"] | this[\"T\"],\n parent: AnyObjectNode,\n subpath: string\n ): this[\"N\"] {\n if (isStateTreeNode(newValue)) {\n return this._subtype.reconcile(\n current,\n newValue,\n parent,\n subpath\n ) as this[\"N\"]\n }\n if (this._fallbackType.isAssignableFrom(current.type)) {\n // `current` holds the fallback. Try the real type again, but keep the\n // fallback node around while doing so — it is what the catch reconciles.\n let recovered: this[\"N\"]\n try {\n recovered = this._subtype.instantiate(\n parent,\n subpath,\n undefined,\n newValue\n ) as this[\"N\"]\n } catch (e) {\n return this._fallbackType.reconcile(\n current,\n this._createFallbackSnapshot(e, newValue),\n parent,\n subpath\n ) as this[\"N\"]\n }\n // the fallback node has been replaced, so it has to die: otherwise it\n // stays alive in the tree and its identifier stays in the root's cache,\n // where it collides with the recovered node's\n current.die()\n return recovered\n }\n try {\n return this._subtype.reconcile(\n current,\n newValue,\n parent,\n subpath\n ) as this[\"N\"]\n } catch (e) {\n current.die()\n return this._instantiateFallback(parent, subpath, undefined, newValue, e)\n }\n }\n\n isValidSnapshot(\n _value: this[\"C\"],\n _context: IValidationContext\n ): IValidationResult {\n return typeCheckSuccess()\n }\n\n override is(thing: unknown): thing is any {\n if (isType(thing)) {\n return (\n this._subtype.isAssignableFrom(thing) ||\n this._fallbackType.isAssignableFrom(thing)\n )\n }\n try {\n if (this._subtype.is(thing)) {\n return true\n }\n } catch (_e) {\n // subtype.is() may throw (e.g. union dispatcher)\n }\n try {\n return this._fallbackType.is(thing)\n } catch (_e) {\n return false\n }\n }\n\n override isAssignableFrom(type: IAnyType) {\n return (\n this._subtype.isAssignableFrom(type) ||\n this._fallbackType.isAssignableFrom(type)\n )\n }\n\n getSubTypes() {\n return [this._subtype, this._fallbackType]\n }\n\n override getSnapshot(node: this[\"N\"]): this[\"S\"] {\n return node.snapshot\n }\n}\n\nexport interface IResilientType<\n IT extends IAnyType,\n FT extends IAnyType\n> extends IType<\n IT[\"CreationType\"] | FT[\"CreationType\"],\n IT[\"SnapshotType\"] | FT[\"SnapshotType\"],\n IT[\"TypeWithoutSTN\"] | FT[\"TypeWithoutSTN\"]\n> {}\n\n/**\n * `types.resilient` - Wraps a type so that instantiation errors are caught\n * and a fallback type is used instead. This is useful for loading data that\n * may contain unknown or invalid subtrees (e.g., plugin types that are not\n * installed) without crashing the entire state tree.\n *\n * The `createFallbackSnapshot` callback receives the caught error and the\n * original snapshot, and must return a valid snapshot for the fallback type.\n *\n * @param type The type to wrap.\n * @param fallbackType The fallback type to use when instantiation fails.\n * @param createFallbackSnapshot Callback that produces a fallback snapshot from the error and original snapshot.\n * @returns A resilient type.\n */\nexport function resilient<IT extends IAnyType, FT extends IAnyType>(\n type: IT,\n fallbackType: FT,\n createFallbackSnapshot: (\n error: unknown,\n snapshot: unknown\n ) => FT[\"CreationType\"]\n): IResilientType<IT, FT> {\n assertIsType(type, 1)\n assertIsType(fallbackType, 2)\n return new Resilient(type, fallbackType, createFallbackSnapshot)\n}\n","// we import the types to re-export them inside types.\nimport {\n DatePrimitive,\n array,\n boolean,\n compose,\n custom,\n enumeration,\n finite,\n float,\n frozen,\n identifier,\n identifierNumber,\n integer,\n late,\n lazy,\n literal,\n map,\n maybe,\n maybeNull,\n model,\n nullType,\n number,\n optional,\n stripDefault,\n reference,\n refinement,\n safeReference,\n resilient,\n snapshotProcessor,\n string,\n undefinedType,\n union\n} from \"../internal.ts\"\n\nexport const types = {\n enumeration,\n model,\n compose,\n custom,\n reference,\n safeReference,\n union,\n optional,\n stripDefault,\n literal,\n maybe,\n maybeNull,\n refinement,\n string,\n boolean,\n number,\n integer,\n float,\n finite,\n Date: DatePrimitive,\n map,\n array,\n frozen,\n identifier,\n identifierNumber,\n late,\n lazy,\n undefined: undefinedType,\n null: nullType,\n snapshotProcessor,\n resilient\n}\n"],"names":["mobxAction","mobxDefineProperty","defineProperty"],"mappings":";;AAQA,IAAI,kBAAkB,GAAmB,MAAM;AAE/C;;;;;;AAMG;AACG,SAAU,qBAAqB,CAAC,IAAoB,EAAA;IACxD,kBAAkB,GAAG,IAAI;AAC3B;AAEA;;;;AAIG;SACa,qBAAqB,GAAA;AACnC,IAAA,OAAO,kBAAkB;AAC3B;AAQA;;;;;;;;;AASG;AACG,SAAU,qBAAqB,CAAC,IAAoB,EAAA;IACxD,qBAAqB,CAAC,IAAI,CAAC;AAC7B;;AChDA;;AAEG;AACH,IAAY,IAMX;AAND,CAAA,UAAY,IAAI,EAAA;AACd,IAAA,IAAA,CAAA,aAAA,CAAA,GAAA,aAA2B;AAC3B,IAAA,IAAA,CAAA,aAAA,CAAA,GAAA,aAA2B;AAC3B,IAAA,IAAA,CAAA,2BAAA,CAAA,GAAA,2BAAuD;AACvD,IAAA,IAAA,CAAA,cAAA,CAAA,GAAA,cAA6B;AAC7B,IAAA,IAAA,CAAA,eAAA,CAAA,GAAA,eAA+B;AACjC,CAAC,EANW,IAAI,KAAJ,IAAI,GAAA,EAAA,CAAA,CAAA;;AC0ChB;;;;;AAKG;AACG,SAAU,OAAO,CAAC,MAAyB,EAAA;AAC/C,IAAA,qBAAqB,CAAC,MAAM,EAAE,CAAC,CAAC;AAEhC,IAAA,OAAO,gBAAgB,CAAC,MAAM,CAAC,CAAC,IAAI;AACtC;AAEA;;;;;;;;;;;;;;;AAeG;AACG,SAAU,YAAY,CAC1B,MAAyB,EACzB,YAAqB,EAAA;AAErB,IAAA,qBAAqB,CAAC,MAAM,EAAE,CAAC,CAAC;IAEhC,OAAO,gBAAgB,CAAC,MAAM,CAAC,CAAC,YAAY,CAAC,YAAY,CAAC;AAC5D;AAEA;;;;;;;;AAQG;AACG,SAAU,OAAO,CACrB,MAAyB,EACzB,QAA+D,EAAA;;AAG/D,IAAA,qBAAqB,C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AAM,KAAK,GAAG;IACnB,WAAW;IACX,KAAK;IACL,OAAO;IACP,MAAM;IACN,SAAS;IACT,aAAa;IACb,KAAK;IACL,QAAQ;IACR,YAAY;IACZ,OAAO;IACP,KAAK;IACL,SAAS;IACT,UAAU;IACV,MAAM;IACN,OAAO;IACP,MAAM;IACN,OAAO;IACP,KAAK;IACL,MAAM;AACN,IAAA,IAAI,EAAE,aAAa;IACnB,GAAG;IACH,KAAK;IACL,MAAM;IACN,UAAU;IACV,gBAAgB;IAChB,IAAI;IACJ,IAAI;AACJ,IAAA,SAAS,EAAE,aAAa;AACxB,IAAA,IAAI,EAAE,QAAQ;IACd,iBAAiB;IACjB;;;;;"}
|
|
1
|
+
{"version":3,"file":"mobx-state-tree.mjs","sources":["../src/core/node/livelinessChecking.ts","../src/core/node/Hook.ts","../src/core/mst-operations.ts","../src/core/node/BaseNode.ts","../src/core/node/scalar-node.ts","../src/core/node/object-node.ts","../src/core/type/type.ts","../src/middlewares/create-action-tracking-middleware.ts","../src/middlewares/createActionTrackingMiddleware2.ts","../src/middlewares/on-action.ts","../src/core/action.ts","../src/core/actionContext.ts","../src/core/type/type-checker.ts","../src/core/node/identifier-cache.ts","../src/core/node/create-node.ts","../src/core/node/node-utils.ts","../src/utils.ts","../src/core/flow.ts","../src/core/json-patch.ts","../src/types/utility-types/snapshotProcessor.ts","../src/types/complex-types/collection-hooks.ts","../src/types/complex-types/map.ts","../src/types/complex-types/array.ts","../src/types/complex-types/model.ts","../src/types/primitives.ts","../src/types/utility-types/literal.ts","../src/types/utility-types/refinement.ts","../src/types/utility-types/enumeration.ts","../src/types/utility-types/union.ts","../src/types/utility-types/optional.ts","../src/types/utility-types/maybe.ts","../src/types/utility-types/late.ts","../src/types/utility-types/lazy.ts","../src/types/utility-types/frozen.ts","../src/types/utility-types/reference.ts","../src/types/utility-types/identifier.ts","../src/types/utility-types/custom.ts","../src/types/utility-types/resilient.ts","../src/types/index.ts"],"sourcesContent":["/**\n * Defines what MST should do when running into reads / writes to objects that have died.\n * - `\"warn\"`: Print a warning (default).\n * - `\"error\"`: Throw an exception.\n * - \"`ignore`\": Do nothing.\n */\nexport type LivelinessMode = \"warn\" | \"error\" | \"ignore\"\n\nlet livelinessChecking: LivelinessMode = \"warn\"\n\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 */\nexport function setLivelinessChecking(mode: LivelinessMode) {\n livelinessChecking = mode\n}\n\n/**\n * Returns the current liveliness checking mode.\n *\n * @returns `\"warn\"`, `\"error\"` or `\"ignore\"`\n */\nexport function getLivelinessChecking(): LivelinessMode {\n return livelinessChecking\n}\n\n/**\n * @deprecated use LivelinessMode instead\n * @hidden\n */\nexport type LivelynessMode = LivelinessMode\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 */\nexport function setLivelynessChecking(mode: LivelinessMode) {\n setLivelinessChecking(mode)\n}\n","/**\n * @hidden\n */\nexport enum Hook {\n afterCreate = \"afterCreate\",\n afterAttach = \"afterAttach\",\n afterCreationFinalization = \"afterCreationFinalization\",\n beforeDetach = \"beforeDetach\",\n beforeDestroy = \"beforeDestroy\"\n}\n\nexport interface IHooks {\n [Hook.afterCreate]?: () => void\n [Hook.afterAttach]?: () => void\n [Hook.beforeDetach]?: () => void\n [Hook.beforeDestroy]?: () => void\n}\n\nexport type IHooksGetter<T> = (self: T) => IHooks\n","import { isComputedProp, isObservableProp } from \"mobx\"\n\nimport {\n EMPTY_OBJECT,\n InvalidReferenceError,\n asArray,\n asModelType,\n assertArg,\n assertIsFunction,\n assertIsNumber,\n assertIsStateTreeNode,\n assertIsString,\n assertIsType,\n assertIsValidIdentifier,\n fail,\n freeze,\n getRelativePathBetweenNodes,\n getRunningActionContext,\n getStateTreeNode,\n isModelType,\n isStateTreeNode,\n normalizeIdentifier,\n resolveNodeByPath,\n splitJsonPath\n} from \"../internal.ts\"\n\nimport type {\n AnyObjectNode,\n IActionContext,\n IAnyComplexType,\n IAnyModelType,\n IAnyStateTreeNode,\n IAnyType,\n IDisposer,\n IJsonPatch,\n IStateTreeNode,\n IType,\n ReferenceIdentifier,\n TypeOfValue\n} from \"../internal.ts\"\n\n/** @hidden */\nexport type TypeOrStateTreeNodeToStateTreeNode<\n T extends IAnyType | IAnyStateTreeNode\n> = T extends IType<any, any, infer TT> ? TT & IStateTreeNode<T> : T\n\n/**\n * Returns the _actual_ type of the given tree node. (Or throws)\n *\n * @param object\n * @returns\n */\nexport function getType(object: IAnyStateTreeNode): IAnyComplexType {\n assertIsStateTreeNode(object, 1)\n\n return getStateTreeNode(object).type\n}\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 */\nexport function getChildType(\n object: IAnyStateTreeNode,\n propertyName?: string\n): IAnyType {\n assertIsStateTreeNode(object, 1)\n\n return getStateTreeNode(object).getChildType(propertyName)\n}\n\n/**\n * Registers a function that will be invoked for each mutation that is applied to the provided model instance, or to any of its children.\n * See [patches](https://github.com/mobxjs/mobx-state-tree#patches) for more details. onPatch events are emitted immediately and will not await the end of a transaction.\n * Patches can be used to deeply observe a model tree.\n *\n * @param target the model instance from which to receive patches\n * @param callback the callback that is invoked for each patch. The reversePatch is a patch that would actually undo the emitted patch\n * @returns function to remove the listener\n */\nexport function onPatch(\n target: IAnyStateTreeNode,\n callback: (patch: IJsonPatch, reversePatch: IJsonPatch) => void\n): IDisposer {\n // check all arguments\n assertIsStateTreeNode(target, 1)\n assertIsFunction(callback, 2)\n\n return getStateTreeNode(target).onPatch(callback)\n}\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 */\nexport function onSnapshot<S>(\n target: IStateTreeNode<IType<any, S, any>>,\n callback: (snapshot: S) => void\n): IDisposer {\n // check all arguments\n assertIsStateTreeNode(target, 1)\n assertIsFunction(callback, 2)\n\n return getStateTreeNode(target).onSnapshot(callback)\n}\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 */\nexport function applyPatch(\n target: IAnyStateTreeNode,\n patch: IJsonPatch | ReadonlyArray<IJsonPatch>\n): void {\n // check all arguments\n assertIsStateTreeNode(target, 1)\n assertArg(patch, p => typeof p === \"object\", \"object or array\", 2)\n\n getStateTreeNode(target).applyPatches(asArray(patch))\n}\n\nexport interface IPatchRecorder {\n patches: ReadonlyArray<IJsonPatch>\n inversePatches: ReadonlyArray<IJsonPatch>\n reversedInversePatches: ReadonlyArray<IJsonPatch>\n readonly recording: boolean\n stop(): void\n resume(): void\n replay(target?: IAnyStateTreeNode): void\n undo(target?: IAnyStateTreeNode): void\n}\n\n/**\n * Small abstraction around `onPatch` and `applyPatch`, attaches a patch listener to a tree and records all the patches.\n * Returns a recorder object with the following signature:\n *\n * Example:\n * ```ts\n * export interface IPatchRecorder {\n * // the recorded patches\n * patches: IJsonPatch[]\n * // the inverse of the recorded patches\n * inversePatches: IJsonPatch[]\n * // true if currently recording\n * recording: boolean\n * // stop recording patches\n * stop(): void\n * // resume recording patches\n * resume(): void\n * // apply all the recorded patches on the given target (the original subject if omitted)\n * replay(target?: IAnyStateTreeNode): void\n * // reverse apply the recorded patches on the given target (the original subject if omitted)\n * // stops the recorder if not already stopped\n * undo(): void\n * }\n * ```\n *\n * The optional filter function allows to skip recording certain patches.\n *\n * @param subject\n * @param filter\n * @returns\n */\nexport function recordPatches(\n subject: IAnyStateTreeNode,\n filter?: (\n patch: IJsonPatch,\n inversePatch: IJsonPatch,\n actionContext: IActionContext | undefined\n ) => boolean\n): IPatchRecorder {\n // check all arguments\n assertIsStateTreeNode(subject, 1)\n\n interface IPatches {\n patches: IJsonPatch[]\n reversedInversePatches: IJsonPatch[]\n inversePatches: IJsonPatch[]\n }\n\n const data: Pick<IPatches, \"patches\" | \"inversePatches\"> = {\n patches: [],\n inversePatches: []\n }\n\n // we will generate the immutable copy of patches on demand for public consumption\n const publicData: { [K in keyof IPatches]?: IPatches[K] | undefined } = {}\n\n let disposer: IDisposer | undefined\n\n const recorder: IPatchRecorder = {\n get recording() {\n return !!disposer\n },\n get patches() {\n if (!publicData.patches) {\n publicData.patches = data.patches.slice()\n }\n return publicData.patches\n },\n get reversedInversePatches() {\n if (!publicData.reversedInversePatches) {\n publicData.reversedInversePatches = data.inversePatches\n .slice()\n .reverse()\n }\n return publicData.reversedInversePatches\n },\n get inversePatches() {\n if (!publicData.inversePatches) {\n publicData.inversePatches = data.inversePatches.slice()\n }\n return publicData.inversePatches\n },\n stop() {\n if (disposer) {\n disposer()\n disposer = undefined\n }\n },\n resume() {\n if (disposer) {\n return\n }\n disposer = onPatch(subject, (patch, inversePatch) => {\n // skip patches that are asked to be filtered if there's a filter in place\n if (filter && !filter(patch, inversePatch, getRunningActionContext())) {\n return\n }\n data.patches.push(patch)\n data.inversePatches.push(inversePatch)\n\n // mark immutable public patches as dirty\n publicData.patches = undefined\n publicData.inversePatches = undefined\n publicData.reversedInversePatches = undefined\n })\n },\n replay(target?: IAnyStateTreeNode) {\n applyPatch(target || subject, data.patches)\n },\n undo(target?: IAnyStateTreeNode) {\n applyPatch(target || subject, data.inversePatches.slice().reverse())\n }\n }\n\n recorder.resume()\n return recorder\n}\n\n/**\n * The inverse of `unprotect`.\n *\n * @param target\n */\nexport function protect(target: IAnyStateTreeNode): void {\n // check all arguments\n assertIsStateTreeNode(target, 1)\n\n const node = getStateTreeNode(target)\n if (!node.isRoot) {\n throw fail(\"`protect` can only be invoked on root nodes\")\n }\n node.isProtectionEnabled = true\n}\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 */\nexport function unprotect(target: IAnyStateTreeNode): void {\n // check all arguments\n assertIsStateTreeNode(target, 1)\n\n const node = getStateTreeNode(target)\n if (!node.isRoot) {\n throw fail(\"`unprotect` can only be invoked on root nodes\")\n }\n node.isProtectionEnabled = false\n}\n\n/**\n * Returns true if the object is in protected mode, @see protect\n */\nexport function isProtected(target: IAnyStateTreeNode): boolean {\n // check all arguments\n assertIsStateTreeNode(target, 1)\n\n return getStateTreeNode(target).isProtected\n}\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 */\nexport function applySnapshot<C>(\n target: IStateTreeNode<IType<C, any, any>>,\n snapshot: C\n) {\n // check all arguments\n assertIsStateTreeNode(target, 1)\n\n return getStateTreeNode(target).applySnapshot(snapshot)\n}\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 */\nexport function getSnapshot<S>(\n target: IStateTreeNode<IType<any, S, any>>,\n applyPostProcess = true\n): S {\n // check all arguments\n assertIsStateTreeNode(target, 1)\n\n const node = getStateTreeNode(target)\n if (applyPostProcess) {\n return node.snapshot\n }\n\n return freeze(node.type.getSnapshot(node, false))\n}\n\nfunction findParentAtDepth(node: AnyObjectNode, depth: number) {\n let remaining = depth\n let parent: AnyObjectNode | null = node.parent\n while (parent) {\n if (--remaining === 0) {\n return parent\n }\n parent = parent.parent\n }\n return null\n}\n\nfunction findParentOfType(node: AnyObjectNode, type: IAnyComplexType) {\n let parent: AnyObjectNode | null = node.parent\n while (parent) {\n if (type.is(parent.storedValue)) {\n return parent\n }\n parent = parent.parent\n }\n return null\n}\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 */\nexport function hasParent(target: IAnyStateTreeNode, depth = 1): boolean {\n // check all arguments\n assertIsStateTreeNode(target, 1)\n assertIsNumber(depth, 2, 0)\n\n return findParentAtDepth(getStateTreeNode(target), depth) !== null\n}\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 */\nexport function getParent<IT extends IAnyStateTreeNode | IAnyComplexType>(\n target: IAnyStateTreeNode,\n depth = 1\n): TypeOrStateTreeNodeToStateTreeNode<IT> {\n // check all arguments\n assertIsStateTreeNode(target, 1)\n assertIsNumber(depth, 2, 0)\n\n const parent = findParentAtDepth(getStateTreeNode(target), depth)\n if (!parent) {\n throw fail(\n `Failed to find the parent of ${getStateTreeNode(target)} at depth ${depth}`\n )\n }\n return parent.storedValue\n}\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 */\nexport function hasParentOfType(\n target: IAnyStateTreeNode,\n type: IAnyComplexType\n): boolean {\n // check all arguments\n assertIsStateTreeNode(target, 1)\n assertIsType(type, 2)\n\n return findParentOfType(getStateTreeNode(target), type) !== null\n}\n\n/**\n * Returns the target's parent of a given type, or throws.\n *\n * @param target\n * @param type\n * @returns\n */\nexport function getParentOfType<IT extends IAnyComplexType>(\n target: IAnyStateTreeNode,\n type: IT\n): IT[\"Type\"] {\n // check all arguments\n assertIsStateTreeNode(target, 1)\n assertIsType(type, 2)\n\n const parent = findParentOfType(getStateTreeNode(target), type)\n if (!parent) {\n throw fail(\n `Failed to find the parent of ${getStateTreeNode(target)} of a given type`\n )\n }\n return parent.storedValue\n}\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 */\nexport function getRoot<IT extends IAnyComplexType | IAnyStateTreeNode>(\n target: IAnyStateTreeNode\n): TypeOrStateTreeNodeToStateTreeNode<IT> {\n // check all arguments\n assertIsStateTreeNode(target, 1)\n\n return getStateTreeNode(target).root.storedValue\n}\n\n/**\n * Returns the path of the given object in the model tree\n *\n * @param target\n * @returns\n */\nexport function getPath(target: IAnyStateTreeNode): string {\n // check all arguments\n assertIsStateTreeNode(target, 1)\n\n return getStateTreeNode(target).path\n}\n\n/**\n * Returns the path of the given object as unescaped string array.\n *\n * @param target\n * @returns\n */\nexport function getPathParts(target: IAnyStateTreeNode): string[] {\n // check all arguments\n assertIsStateTreeNode(target, 1)\n\n return splitJsonPath(getStateTreeNode(target).path)\n}\n\n/**\n * Returns true if the given object is the root of a model tree.\n *\n * @param target\n * @returns\n */\nexport function isRoot(target: IAnyStateTreeNode): boolean {\n // check all arguments\n assertIsStateTreeNode(target, 1)\n\n return getStateTreeNode(target).isRoot\n}\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 */\nexport function resolvePath<T = any>(\n target: IAnyStateTreeNode,\n path: string\n): T | undefined {\n // check all arguments\n assertIsStateTreeNode(target, 1)\n assertIsString(path, 2)\n\n const node = resolveNodeByPath(getStateTreeNode(target), path)\n return node ? node.value : undefined\n}\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 */\nexport function resolveIdentifier<IT extends IAnyModelType>(\n type: IT,\n target: IAnyStateTreeNode,\n identifier: ReferenceIdentifier\n): IT[\"Type\"] | undefined {\n // check all arguments\n assertIsType(type, 1)\n assertIsStateTreeNode(target, 2)\n assertIsValidIdentifier(identifier, 3)\n\n const node = getStateTreeNode(target).root.identifierCache!.resolve(\n type,\n normalizeIdentifier(identifier)\n )\n return node?.value\n}\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 */\nexport function getIdentifier(target: IAnyStateTreeNode): string | null {\n // check all arguments\n assertIsStateTreeNode(target, 1)\n\n return getStateTreeNode(target).identifier\n}\n\n/**\n * Resolves a reference getter to the referenced node, or `undefined` when the\n * reference is empty, dangling, or (with `checkIfAlive`) points at a dead node.\n * Backs both {@link tryReference} and {@link isValidReference}.\n */\nfunction resolveReference<N extends IAnyStateTreeNode>(\n getter: () => N | null | undefined,\n checkIfAlive: boolean\n): N | undefined {\n try {\n const node = getter()\n if (node === undefined || node === null) {\n return undefined\n }\n if (!isStateTreeNode(node)) {\n throw fail(\n \"The reference to be checked is not one of node, null or undefined\"\n )\n }\n return !checkIfAlive || isAlive(node) ? node : undefined\n } catch (e) {\n if (e instanceof InvalidReferenceError) {\n return undefined\n }\n throw e\n }\n}\n\n/**\n * Tests if a reference is valid (pointing to an existing node and optionally if alive) and returns such reference if the check passes,\n * else it returns undefined.\n *\n * @param getter Function to access the reference.\n * @param checkIfAlive true to also make sure the referenced node is alive (default), false to skip this check.\n * @returns\n */\nexport function tryReference<N extends IAnyStateTreeNode>(\n getter: () => N | null | undefined,\n checkIfAlive = true\n): N | undefined {\n return resolveReference(getter, checkIfAlive)\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 */\nexport function isValidReference<N extends IAnyStateTreeNode>(\n getter: () => N | null | undefined,\n checkIfAlive = true\n): boolean {\n return resolveReference(getter, checkIfAlive) !== undefined\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 */\nexport function tryResolve<T = any>(\n target: IAnyStateTreeNode,\n path: string\n): T | undefined {\n // check all arguments\n assertIsStateTreeNode(target, 1)\n assertIsString(path, 2)\n\n const node = resolveNodeByPath(getStateTreeNode(target), path, false)\n if (node === undefined) {\n 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/**\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 */\nexport function getRelativePath(\n base: IAnyStateTreeNode,\n target: IAnyStateTreeNode\n): string {\n // check all arguments\n assertIsStateTreeNode(base, 1)\n assertIsStateTreeNode(target, 2)\n\n return getRelativePathBetweenNodes(\n getStateTreeNode(base),\n getStateTreeNode(target)\n )\n}\n\n/**\n * Returns a deep copy of the given state tree node as new tree.\n * Like `getType(x).create(getSnapshot(x))`, except that a node wrapped in a\n * `types.snapshotProcessor` is recreated through the processor, which\n * `getType(x)` (the wrapped type) would skip.\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 */\nexport function clone<T extends IAnyStateTreeNode>(\n source: T,\n keepEnvironment: boolean | object = true\n): T {\n // check all arguments\n assertIsStateTreeNode(source, 1)\n\n const node = getStateTreeNode(source)\n return (node.snapshotProcessorType ?? node.type).create(\n node.snapshot,\n keepEnvironment === true\n ? node.root.environment\n : keepEnvironment === false\n ? undefined\n : keepEnvironment\n )\n}\n\n/**\n * Removes a model element from the state tree, and let it live on as a new state tree\n */\nexport function detach<T extends IAnyStateTreeNode>(target: T): T {\n // check all arguments\n assertIsStateTreeNode(target, 1)\n\n getStateTreeNode(target).detach()\n return target\n}\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 */\nexport function destroy(target: IAnyStateTreeNode): void {\n // check all arguments\n assertIsStateTreeNode(target, 1)\n\n const node = getStateTreeNode(target)\n if (node.isRoot) {\n node.die()\n } else {\n node.parent!.removeChild(node.subpath)\n }\n}\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 */\nexport function isAlive(target: IAnyStateTreeNode): boolean {\n // check all arguments\n assertIsStateTreeNode(target, 1)\n\n return getStateTreeNode(target).observableIsAlive\n}\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 */\nexport function addDisposer(\n target: IAnyStateTreeNode,\n disposer: IDisposer\n): IDisposer {\n // check all arguments\n assertIsStateTreeNode(target, 1)\n assertIsFunction(disposer, 2)\n\n const node = getStateTreeNode(target)\n node.addDisposer(disposer)\n return disposer\n}\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 */\nexport function getEnv<T = any>(target: IAnyStateTreeNode): T {\n // check all arguments\n assertIsStateTreeNode(target, 1)\n\n const node = getStateTreeNode(target)\n const env = node.root.environment\n if (!env) {\n return EMPTY_OBJECT as T\n }\n return env\n}\n\n/**\n * Performs a depth first walk through a tree.\n */\nexport function walk(\n target: IAnyStateTreeNode,\n processor: (item: IAnyStateTreeNode) => void\n): void {\n // check all arguments\n assertIsStateTreeNode(target, 1)\n assertIsFunction(processor, 2)\n\n const node = getStateTreeNode(target)\n node.getChildren().forEach(child => {\n if (isStateTreeNode(child.storedValue)) {\n walk(child.storedValue, processor)\n }\n })\n processor(node.storedValue)\n}\n\nexport interface IModelReflectionPropertiesData {\n name: string\n properties: { [K: string]: IAnyType }\n}\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 */\nexport function getPropertyMembers(\n typeOrNode: IAnyModelType | IAnyStateTreeNode\n): IModelReflectionPropertiesData {\n const type: IAnyType = isStateTreeNode(typeOrNode)\n ? getType(typeOrNode)\n : typeOrNode\n assertArg(type, isModelType, \"model type or model instance\", 1)\n\n // a wrapped model reports the model's properties; a union of models has no\n // single set and reports none\n return {\n name: type.name,\n properties: { ...asModelType(type)?.properties }\n }\n}\n\nexport interface IModelReflectionData extends IModelReflectionPropertiesData {\n actions: string[]\n views: string[]\n volatile: string[]\n flowActions: string[]\n}\n\n/**\n * Returns a reflection of the model node, including name, properties, views, volatile state,\n * and actions. `flowActions` is also provided as a separate array of names for any action that\n * came from a flow generator as well.\n *\n * In the case where a model has two actions: `doSomething` and `doSomethingWithFlow`, where\n * `doSomethingWithFlow` is a flow generator, the `actions` array will contain both actions,\n * i.e. [\"doSomething\", \"doSomethingWithFlow\"], and the `flowActions` array will contain only\n * the flow action, i.e. [\"doSomethingWithFlow\"].\n *\n * @param target\n * @returns\n */\nexport function getMembers(target: IAnyStateTreeNode): IModelReflectionData {\n const type = getStateTreeNode(target).type as unknown as IAnyModelType\n\n const reflected: IModelReflectionData = {\n ...getPropertyMembers(type),\n actions: [],\n volatile: [],\n views: [],\n flowActions: []\n }\n\n const props = Object.getOwnPropertyNames(target)\n props.forEach(key => {\n if (key in reflected.properties) {\n return\n }\n const descriptor = Object.getOwnPropertyDescriptor(target, key)!\n if (descriptor.get) {\n if (isComputedProp(target, key)) {\n reflected.views.push(key)\n } else {\n reflected.volatile.push(key)\n }\n return\n }\n const value = descriptor.value\n if (value?._isFlowAction === true) {\n reflected.flowActions.push(key)\n }\n if (value?._isMSTAction === true) {\n reflected.actions.push(key)\n } else if (isObservableProp(target, key)) {\n reflected.volatile.push(key)\n } else {\n reflected.views.push(key)\n }\n })\n return reflected\n}\n\nexport function cast<\n O extends string | number | boolean | null | undefined = never\n>(snapshotOrInstance: O): O\nexport function cast<O = never>(\n snapshotOrInstance:\n | TypeOfValue<O>[\"CreationType\"]\n | TypeOfValue<O>[\"SnapshotType\"]\n | TypeOfValue<O>[\"Type\"]\n): O\n/**\n * Casts a node snapshot or instance type to an instance type so it can be assigned to a type instance.\n * Note that this is just a cast for the type system, this is, it won't actually convert a snapshot to an instance,\n * but just fool typescript into thinking so.\n * Either way, casting when outside an assignation operation won't compile.\n *\n * Example:\n * ```ts\n * const ModelA = types.model({\n * n: types.number\n * }).actions(self => ({\n * setN(aNumber: number) {\n * self.n = aNumber\n * }\n * }))\n *\n * const ModelB = types.model({\n * innerModel: ModelA\n * }).actions(self => ({\n * someAction() {\n * // this will allow the compiler to assign a snapshot to the property\n * self.innerModel = cast({ a: 5 })\n * }\n * }))\n * ```\n *\n * @param snapshotOrInstance Snapshot or instance\n * @returns The same object cast as an instance\n */\nexport function cast(snapshotOrInstance: any): any {\n return snapshotOrInstance\n}\n\n/**\n * Casts a node instance type to a snapshot type so it can be assigned to a type snapshot (e.g. to be used inside a create call).\n * Note that this is just a cast for the type system, this is, it won't actually convert an instance to a snapshot,\n * but just fool typescript into thinking so.\n *\n * Example:\n * ```ts\n * const ModelA = types.model({\n * n: types.number\n * }).actions(self => ({\n * setN(aNumber: number) {\n * self.n = aNumber\n * }\n * }))\n *\n * const ModelB = types.model({\n * innerModel: ModelA\n * })\n *\n * const a = ModelA.create({ n: 5 });\n * // this will allow the compiler to use a model as if it were a snapshot\n * const b = ModelB.create({ innerModel: castToSnapshot(a)})\n * ```\n *\n * @param snapshotOrInstance Snapshot or instance\n * @returns The same object cast as an input (creation) snapshot\n */\nexport function castToSnapshot<I>(\n snapshotOrInstance: I\n): Extract<I, IAnyStateTreeNode> extends never\n ? I\n : TypeOfValue<I>[\"CreationType\"] {\n return snapshotOrInstance\n}\n\n/**\n * Casts a node instance type to a reference snapshot type so it can be assigned to a reference snapshot (e.g. to be used inside a create call).\n * Note that this is just a cast for the type system, this is, it won't actually convert an instance to a reference snapshot,\n * but just fool typescript into thinking so.\n *\n * Example:\n * ```ts\n * const ModelA = types.model({\n * id: types.identifier,\n * n: types.number\n * }).actions(self => ({\n * setN(aNumber: number) {\n * self.n = aNumber\n * }\n * }))\n *\n * const ModelB = types.model({\n * refA: types.reference(ModelA)\n * })\n *\n * const a = ModelA.create({ id: 'someId', n: 5 });\n * // this will allow the compiler to use a model as if it were a reference snapshot\n * const b = ModelB.create({ refA: castToReferenceSnapshot(a)})\n * ```\n *\n * @param instance Instance\n * @returns The same object cast as a reference snapshot (string or number)\n */\nexport function castToReferenceSnapshot<I>(\n instance: I\n): Extract<I, IAnyStateTreeNode> extends never ? I : ReferenceIdentifier {\n return instance as any\n}\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 */\nexport function getNodeId(target: IAnyStateTreeNode): number {\n assertIsStateTreeNode(target, 1)\n\n return getStateTreeNode(target).nodeId\n}\n","import { type IAtom, action, createAtom } from \"mobx\"\n\nimport {\n type AnyObjectNode,\n EventHandlers,\n Hook,\n type IAnyType,\n type IDisposer,\n NodeLifeCycle,\n devMode,\n escapeJsonPath,\n fail\n} from \"../../internal.ts\"\n\n// `subject` is the node the hook is about: the subscribed node itself, except\n// for a beforeDetach delivered to a node inside the subtree being detached\ntype HookSubscriber = (subject: AnyNode, hook: Hook) => void\ntype HookSubscribers = Record<Hook, HookSubscriber>\n\n/**\n * @internal\n * @hidden\n */\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport abstract class BaseNode<C, S, T> {\n private _escapedSubpath?: string | undefined\n\n private _subpath!: string\n get subpath() {\n return this._subpath\n }\n\n private _subpathUponDeath?: string\n get subpathUponDeath() {\n return this._subpathUponDeath\n }\n\n private _pathUponDeath?: string\n protected get pathUponDeath() {\n return this._pathUponDeath\n }\n\n storedValue!: any // usually the same type as the value, but not always (such as with references)\n get value(): T {\n return (this.type as any).getValue(this)\n }\n\n private aliveAtom?: IAtom\n private _state = NodeLifeCycle.INITIALIZING\n get state() {\n return this._state\n }\n set state(val: NodeLifeCycle) {\n const wasAlive = this.isAlive\n this._state = val\n const isAlive = this.isAlive\n\n if (this.aliveAtom && wasAlive !== isAlive) {\n this.aliveAtom.reportChanged()\n }\n }\n\n private _hookSubscribers?: EventHandlers<HookSubscribers>\n\n protected abstract fireHook(name: Hook): void\n\n protected fireInternalHook(name: Hook, subject: AnyNode = this) {\n this._hookSubscribers?.emit(name, subject, name)\n }\n\n /**\n * Detaching a node takes its whole subtree out of the tree, but only the\n * detached node's parent changes, so only it fires `beforeDetach` for real.\n * Internal subscribers below it (reference watchers on a target) still need\n * to know their node is leaving.\n */\n notifyDetachOf(subject: AnyObjectNode): void {\n this.fireInternalHook(Hook.beforeDetach, subject)\n }\n\n isWithin(ancestor: AnyNode): boolean {\n for (let node = this.parent; node; node = node.parent) {\n if (node === ancestor) {\n return true\n }\n }\n return false\n }\n\n registerHook(hook: Hook, hookHandler: HookSubscriber): IDisposer {\n return (this._hookSubscribers ??= new EventHandlers()).register(\n hook,\n hookHandler\n )\n }\n\n private _parent!: AnyObjectNode | null\n get parent() {\n return this._parent\n }\n\n constructor(\n readonly type: IAnyType,\n parent: AnyObjectNode | null,\n subpath: string,\n public environment: any\n ) {\n this.baseSetParent(parent, subpath)\n }\n\n getReconciliationType() {\n return this.type\n }\n\n private pathAtom?: IAtom\n protected baseSetParent(parent: AnyObjectNode | null, subpath: string) {\n this._parent = parent\n this._subpath = subpath\n this._escapedSubpath = undefined // regenerate when needed\n if (this.pathAtom) {\n this.pathAtom.reportChanged()\n }\n }\n\n /*\n * Returns (escaped) path representation as string\n */\n get path(): string {\n return this.getEscapedPath(true)\n }\n\n protected getEscapedPath(reportObserved: boolean): string {\n if (reportObserved) {\n if (!this.pathAtom) {\n this.pathAtom = createAtom(`path`)\n }\n this.pathAtom.reportObserved()\n }\n if (!this.parent) {\n return \"\"\n }\n // regenerate escaped subpath if needed\n if (this._escapedSubpath === undefined) {\n this._escapedSubpath = !this._subpath ? \"\" : escapeJsonPath(this._subpath)\n }\n return `${this.parent.getEscapedPath(reportObserved)}/${this._escapedSubpath}`\n }\n\n get isRoot(): boolean {\n return this.parent === null\n }\n\n abstract get root(): AnyObjectNode\n\n abstract setParent(\n newParent: AnyObjectNode | null,\n subpath: string | null\n ): void\n\n abstract get snapshot(): S\n abstract getSnapshot(): S\n\n get isAlive() {\n return this.state !== NodeLifeCycle.DEAD\n }\n\n get isDetaching() {\n return this.state === NodeLifeCycle.DETACHING\n }\n\n get observableIsAlive() {\n if (!this.aliveAtom) {\n this.aliveAtom = createAtom(`alive`)\n }\n this.aliveAtom.reportObserved()\n return this.isAlive\n }\n\n die(): void {\n if (!this.isAlive || this.isDetaching) {\n return\n }\n this.aboutToDie()\n this.finalizeDeath()\n }\n\n abstract finalizeCreation(): void\n\n protected baseFinalizeCreation(whenFinalized?: () => void) {\n if (devMode()) {\n if (!this.isAlive) {\n // istanbul ignore next\n throw fail(\n \"assertion failed: cannot finalize the creation of a node that is already dead\"\n )\n }\n }\n\n // goal: afterCreate hooks runs depth-first. After attach runs parent first, so on afterAttach the parent has completed already\n if (this.state === NodeLifeCycle.CREATED) {\n if (this.parent) {\n if (this.parent.state !== NodeLifeCycle.FINALIZED) {\n // parent not ready yet, postpone\n return\n }\n this.fireHook(Hook.afterAttach)\n }\n\n this.state = NodeLifeCycle.FINALIZED\n\n if (whenFinalized) {\n whenFinalized()\n }\n }\n }\n\n abstract finalizeDeath(): void\n\n protected baseFinalizeDeath() {\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 abstract aboutToDie(): void\n\n protected baseAboutToDie() {\n this.fireHook(Hook.beforeDestroy)\n }\n}\nBaseNode.prototype.die = action(BaseNode.prototype.die)\n\n/**\n * @internal\n * @hidden\n */\nexport type AnyNode = BaseNode<any, any, any>\n","import {\n type AnyObjectNode,\n BaseNode,\n type Hook,\n NodeLifeCycle,\n type SimpleType,\n devMode,\n fail,\n freeze\n} from \"../../internal.ts\"\n\n/**\n * @internal\n * @hidden\n */\nexport class ScalarNode<C, S, T> extends BaseNode<C, S, T> {\n // note about hooks:\n // - afterCreate is not emitted in scalar nodes, since it would be emitted in\n // the constructor, before anybody could subscribe to it\n // - afterCreationFinalization could be emitted, but there's no need for it right now\n // - beforeDetach reaches a scalar node only through notifyDetachOf, when an\n // ancestor is detached; a scalar node cannot be detached itself\n\n declare readonly type: SimpleType<C, S, T>\n\n constructor(\n simpleType: SimpleType<C, S, T>,\n parent: AnyObjectNode | null,\n subpath: string,\n environment: any,\n initialSnapshot: C\n ) {\n super(simpleType, parent, subpath, environment)\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\n this.finalizeCreation()\n }\n\n get root(): AnyObjectNode {\n // future optimization: store root ref in the node and maintain it\n if (!this.parent) {\n throw fail(`This scalar node is not part of a tree`)\n }\n return this.parent.root\n }\n\n setParent(newParent: AnyObjectNode, subpath: string): void {\n const parentChanged = this.parent !== newParent\n const 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(\"assertion failed: subpath expected\")\n }\n if (!newParent) {\n // istanbul ignore next\n throw fail(\"assertion failed: parent expected\")\n }\n if (parentChanged) {\n // istanbul ignore next\n throw fail(\"assertion failed: scalar nodes cannot change their parent\")\n }\n }\n\n this.environment = undefined // use parent's\n this.baseSetParent(this.parent, subpath)\n }\n\n get snapshot(): S {\n return freeze(this.getSnapshot())\n }\n\n getSnapshot(): S {\n return this.type.getSnapshot(this)\n }\n\n override toString(): string {\n const path = (this.isAlive ? this.path : this.pathUponDeath) || \"<root>\"\n return `${this.type.name}@${path}${this.isAlive ? \"\" : \" [dead]\"}`\n }\n\n finalizeCreation(): void {\n this.baseFinalizeCreation()\n }\n\n aboutToDie(): void {\n this.baseAboutToDie()\n }\n\n finalizeDeath(): void {\n this.baseFinalizeDeath()\n }\n\n protected fireHook(name: Hook): void {\n this.fireInternalHook(name)\n }\n}\n","import {\n type IComputedValue,\n _allowStateChangesInsideComputed,\n action,\n computed,\n reaction\n} from \"mobx\"\n\nimport {\n BaseNode,\n type ComplexType,\n EMPTY_OBJECT,\n EventHandlers,\n Hook,\n IdentifierCache,\n NodeLifeCycle,\n addHiddenFinalProp,\n convertChildNodesToArray,\n createActionInvoker,\n devMode,\n escapeJsonPath,\n fail,\n freeze,\n getCurrentActionContext,\n getLivelinessChecking,\n getPath,\n normalizeIdentifier,\n resolveNodeByPathParts,\n splitJsonPath,\n splitPatch,\n toJSON,\n warnError,\n type AnyNode,\n type IAnyType,\n type IDisposer,\n type IJsonPatch,\n type IMiddleware,\n type IMiddlewareEvent,\n type IMiddlewareHandler,\n type IReversibleJsonPatch,\n type IStateTreeNode,\n type IType,\n type ReferenceIdentifier\n} from \"../../internal.ts\"\n\nlet nextNodeId = 1\n\nconst enum ObservableInstanceLifecycle {\n // the actual observable instance has not been created yet\n UNINITIALIZED,\n // the actual observable instance is being created\n CREATING,\n // the actual observable instance has been created\n CREATED\n}\n\nconst enum InternalEvents {\n Dispose = \"dispose\",\n Patch = \"patch\",\n Snapshot = \"snapshot\"\n}\n\n/**\n * @internal\n * @hidden\n */\nexport interface IChildNodesMap {\n [key: string]: AnyNode\n}\n\nconst snapshotReactionOptions = {\n onError(e: any) {\n throw e\n }\n}\n\n// keepAlive lets the snapshot computed memoize its value even with no observer,\n// so getSnapshot() stays referentially stable without an eager snapshot\n// reaction serializing the whole tree at create time. Shared: mobx only reads it.\nconst snapshotComputedOptions = { keepAlive: true }\n\ntype InternalEventHandlers<S> = {\n [InternalEvents.Dispose]: IDisposer\n [InternalEvents.Patch]: (patch: IJsonPatch, reversePatch: IJsonPatch) => void\n [InternalEvents.Snapshot]: (snapshot: S) => void\n}\n\n/**\n * @internal\n * @hidden\n */\nexport class ObjectNode<C, S, T> extends BaseNode<C, S, T> {\n declare readonly type: ComplexType<C, S, T>\n declare storedValue: T & IStateTreeNode<IType<C, S, T>>\n\n readonly nodeId = ++nextNodeId\n readonly identifierAttribute?: string | undefined\n readonly identifier: string | null // Identifier is always normalized to string, even if the identifier property isn't\n readonly unnormalizedIdentifier: ReferenceIdentifier | null\n\n identifierCache?: IdentifierCache\n isProtectionEnabled = true\n middlewares?: IMiddleware[]\n hasSnapshotPostProcessor = false\n // `type` is the inner type when a snapshotProcessor wraps this node, so\n // recreating it from its post-processed snapshot has to go through the\n // processor. Only processor-wrapped nodes carry the slot.\n declare snapshotProcessorType?: IAnyType\n\n private _applyPatches?: (patches: ReadonlyArray<IJsonPatch>) => void\n\n applyPatches(patches: ReadonlyArray<IJsonPatch>): void {\n this.createObservableInstanceIfNeeded()\n this._applyPatches!(patches)\n }\n\n private _applySnapshot?: (snapshot: C) => void\n\n applySnapshot(snapshot: C): void {\n this.createObservableInstanceIfNeeded()\n this._applySnapshot!(snapshot)\n }\n\n private _autoUnbox = true // unboxing is disabled when reading child nodes\n _isRunningAction = false // only relevant for root\n private _snapshotReactionDisposer?: IDisposer | undefined\n\n private _observableInstanceState = ObservableInstanceLifecycle.UNINITIALIZED\n private _childNodes: IChildNodesMap\n private _initialSnapshot: C\n private _cachedInitialSnapshot?: S\n private _cachedInitialSnapshotCreated = false\n private _snapshotComputed: IComputedValue<S>\n // whether _snapshotComputed has ever run — see createObservableInstance\n private _snapshotComputedEvaluated = false\n\n constructor(\n complexType: ComplexType<C, S, T>,\n parent: AnyObjectNode | null,\n subpath: string,\n environment: any,\n initialValue: C\n ) {\n super(complexType, parent, subpath, environment)\n // keepAlive: memoize the snapshot after the first read even with no\n // observer, so getSnapshot() is referentially stable (and reconcile-by-\n // snapshot works) without eagerly serializing the whole tree at create\n // time — the previous cost, driven by the eager root reaction below.\n this._snapshotComputed = computed<S>(() => {\n this._snapshotComputedEvaluated = true\n return freeze(this.getSnapshot())\n }, snapshotComputedOptions)\n\n this.unbox = this.unbox.bind(this)\n\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(\n this,\n this._initialSnapshot\n )\n\n // identifier can not be changed during lifecycle of a node\n // so we safely can read it from initial snapshot\n this.identifier = null\n this.unnormalizedIdentifier = null\n if (this.identifierAttribute && this._initialSnapshot) {\n let id = (this._initialSnapshot as any)[this.identifierAttribute]\n if (id === undefined) {\n // try with the actual node if not (for optional identifiers)\n const childNode = this._childNodes[this.identifierAttribute]\n if (childNode) {\n id = childNode.value\n }\n }\n\n if (typeof id !== \"string\" && typeof id !== \"number\") {\n throw fail(\n `Instance identifier '${this.identifierAttribute}' for type '${this.type.name}' must be a string or a number`\n )\n }\n\n // normalize internal identifier to string\n this.identifier = normalizeIdentifier(id)\n this.unnormalizedIdentifier = id\n }\n\n // addNodeToCache no-ops without an identifier attribute, and reaching the\n // root to ask it is a walk up the whole parent chain\n if (this.identifierAttribute) {\n const cache = parent ? parent.root.identifierCache : this.identifierCache\n cache!.addNodeToCache(this)\n }\n }\n\n createObservableInstanceIfNeeded(fireHooks = true): void {\n if (\n this._observableInstanceState ===\n ObservableInstanceLifecycle.UNINITIALIZED\n ) {\n this.createObservableInstance(fireHooks)\n }\n }\n\n createObservableInstance(fireHooks = true): void {\n if (devMode()) {\n if (this.state !== NodeLifeCycle.INITIALIZING) {\n // istanbul ignore next\n throw fail(\n \"assertion failed: the creation of the observable instance must be done on the initializing phase\"\n )\n }\n }\n this._observableInstanceState = ObservableInstanceLifecycle.CREATING\n\n // make sure the parent chain is created as well\n\n // array with parent chain from parent to child\n const parentChain = []\n\n let parent = this.parent\n // for performance reasons we never go back further than the most direct\n // uninitialized parent\n // this is done to avoid traversing the whole tree to the root when using\n // the same reference again\n while (\n parent?._observableInstanceState ===\n ObservableInstanceLifecycle.UNINITIALIZED\n ) {\n parentChain.unshift(parent)\n parent = parent.parent\n }\n\n // initialize the uninitialized parent chain from parent to child\n for (const p of parentChain) {\n // delay firing hooks until after all parents have been created\n p.createObservableInstanceIfNeeded(false)\n }\n\n const type = this.type\n\n try {\n // @ts-expect-error storedValue type mismatch during initialization\n this.storedValue = type.createNewInstance(this._childNodes)\n this.preboot()\n\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 = ObservableInstanceLifecycle.CREATED\n\n // The snapshot computed branches on the non-observable\n // \"_observableInstanceState\" flag we just flipped, so a value already\n // memoized from the initial snapshot is now stale (mobx can't see the\n // change) — refresh it. When it was never read there is nothing to refresh,\n // and forcing it here would serialize the whole subtree (the dominant cost\n // of creating a root) for a value nobody has asked for yet, so we skip it.\n this.refreshMemoizedSnapshot()\n\n // The root's snapshot reaction only drives onSnapshot; set it up lazily\n // (onSnapshot already does) rather than eagerly here, so a root nobody\n // subscribes to never pays for a full-tree snapshot at creation. keepAlive\n // on _snapshotComputed preserves snapshot referential stability without it.\n\n this._childNodes = EMPTY_OBJECT\n\n this.state = NodeLifeCycle.CREATED\n\n if (fireHooks) {\n this.fireHook(Hook.afterCreate)\n // Note that the parent might not be finalized at this point\n // so afterAttach won't be called until later in that case\n this.finalizeCreation()\n\n // fire the hooks of the parents that we created\n for (const p of parentChain.reverse()) {\n p.fireHook(Hook.afterCreate)\n // This will call afterAttach on the child if necessary\n p.finalizeCreation()\n }\n }\n }\n\n get root(): AnyObjectNode {\n const parent = this.parent\n return parent ? parent.root : this\n }\n\n clearParent(): void {\n if (!this.parent) {\n return\n }\n\n this.fireHook(Hook.beforeDetach)\n this.notifyChildrenOfDetach(this)\n const previousState = this.state\n this.state = NodeLifeCycle.DETACHING\n\n const root = this.root\n const newEnv = root.environment\n const 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 override notifyDetachOf(subject: AnyObjectNode): void {\n super.notifyDetachOf(subject)\n this.notifyChildrenOfDetach(subject)\n }\n\n private notifyChildrenOfDetach(subject: AnyObjectNode): void {\n // a handler notified earlier in the walk may have destroyed this node.\n // A node never read still has to be walked: an instance created elsewhere\n // can have been moved under it, subscribers and all.\n if (!this.isAlive) {\n return\n }\n for (const child of this.getChildren()) {\n child.notifyDetachOf(subject)\n }\n }\n\n setParent(newParent: AnyObjectNode, subpath: string): void {\n const parentChanged = newParent !== this.parent\n const 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(\"assertion failed: subpath expected\")\n }\n if (!newParent) {\n // istanbul ignore next\n throw fail(\"assertion failed: new parent expected\")\n }\n\n if (this.parent && parentChanged) {\n throw fail(\n `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(\n `A state tree is not allowed to contain itself. Cannot assign ${this} to path '${newParent.path}/${subpath}'`\n )\n }\n if (\n !this.parent &&\n !!this.environment &&\n this.environment !== newParent.root.environment\n ) {\n throw fail(\n `A state tree cannot be made part of another state tree as long as their environments are different.`\n )\n }\n }\n\n if (parentChanged) {\n // attach to new parent\n this.environment = undefined // will use root's\n newParent.root.identifierCache!.mergeCache(this)\n this.baseSetParent(newParent, subpath)\n this.fireHook(Hook.afterAttach)\n } else if (subpathChanged) {\n // moving to a new subpath on the same parent\n this.baseSetParent(this.parent, subpath)\n }\n }\n\n protected fireHook(name: Hook): void {\n this.fireInternalHook(name)\n\n const fn =\n this.storedValue &&\n typeof this.storedValue === \"object\" &&\n (this.storedValue as any)[name]\n if (typeof fn === \"function\") {\n _allowStateChangesInsideComputed(() => {\n fn.apply(this.storedValue)\n })\n }\n }\n\n private _snapshotUponDeath?: S\n\n // advantage of using computed for a snapshot is that nicely respects transactions etc.\n get snapshot(): S {\n if (this.hasSnapshotPostProcessor) {\n this.createObservableInstanceIfNeeded()\n }\n return this._snapshotComputed.get()\n }\n\n /**\n * @internal\n * @hidden\n * Recompute+retrack the keepAlive snapshot computed if it has already run.\n * Needed whenever something changes what the snapshot would produce without\n * an observable mobx would track: flipping the (non-observable) observable-\n * instance state, or SnapshotProcessor rewriting getSnapshot after\n * construction (see snapshotProcessor._fixNode). If it never ran, there is\n * nothing cached to go stale, so this is a no-op.\n */\n refreshMemoizedSnapshot(): void {\n if (this._snapshotComputedEvaluated) {\n ;(this._snapshotComputed as any).trackAndCompute()\n }\n }\n\n // NOTE: we use this method to get snapshot without creating @computed overhead\n getSnapshot(): S {\n if (!this.isAlive) {\n return this._snapshotUponDeath!\n }\n return this._observableInstanceState === ObservableInstanceLifecycle.CREATED\n ? this._getActualSnapshot()\n : this._getCachedInitialSnapshot()\n }\n\n private _getActualSnapshot(): S {\n return this.type.getSnapshot(this)\n }\n\n private _getCachedInitialSnapshot(): S {\n if (!this._cachedInitialSnapshotCreated) {\n this._cachedInitialSnapshot = this.type.processInitialSnapshot(\n this._childNodes\n )\n this._cachedInitialSnapshotCreated = true\n }\n\n return this._cachedInitialSnapshot!\n }\n\n private isRunningAction(): boolean {\n if (this._isRunningAction) {\n return true\n }\n if (this.isRoot) {\n return false\n }\n return this.parent!.isRunningAction()\n }\n\n assertAlive(context: AssertAliveContext): void {\n const livelinessChecking = getLivelinessChecking()\n if (!this.isAlive && livelinessChecking !== \"ignore\") {\n const error = this._getAssertAliveError(context)\n switch (livelinessChecking) {\n case \"error\":\n throw fail(error)\n case \"warn\":\n warnError(error)\n }\n }\n }\n\n private _getAssertAliveError(context: AssertAliveContext): string {\n const escapedPath = this.getEscapedPath(false) || this.pathUponDeath || \"\"\n const subpath = (context.subpath && escapeJsonPath(context.subpath)) || \"\"\n\n let actionContext = context.actionContext || getCurrentActionContext()\n\n // try to use a real action context if possible since it includes the action name\n if (\n actionContext &&\n actionContext.type !== \"action\" &&\n actionContext.parentActionEvent\n ) {\n actionContext = actionContext.parentActionEvent\n }\n\n let actionFullPath = \"\"\n if (actionContext?.name != null) {\n // try to use the context, and if it not available use the node one\n const actionPath =\n (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 getChildNode(subpath: string): AnyNode {\n this.assertAlive({\n subpath\n })\n this._autoUnbox = false\n try {\n return this._observableInstanceState ===\n ObservableInstanceLifecycle.CREATED\n ? this.type.getChildNode(this, subpath)\n : this._childNodes[subpath]!\n } finally {\n this._autoUnbox = true\n }\n }\n\n getChildren(): ReadonlyArray<AnyNode> {\n this.assertAlive(EMPTY_OBJECT)\n this._autoUnbox = false\n try {\n return this._observableInstanceState ===\n ObservableInstanceLifecycle.CREATED\n ? this.type.getChildren(this)\n : convertChildNodesToArray(this._childNodes)\n } finally {\n this._autoUnbox = true\n }\n }\n\n getChildType(propertyName?: string): IAnyType {\n return this.type.getChildType(propertyName)\n }\n\n get isProtected(): boolean {\n return this.root.isProtectionEnabled\n }\n\n assertWritable(context: AssertAliveContext): void {\n this.assertAlive(context)\n if (!this.isRunningAction() && this.isProtected) {\n throw fail(\n `Cannot modify '${this}', the object is protected and can only be modified by using an action.`\n )\n }\n }\n\n removeChild(subpath: string): void {\n this.type.removeChild(this, subpath)\n }\n\n // bound on the constructor\n unbox(childNode: AnyNode | undefined): AnyNode | undefined {\n if (!childNode) {\n return childNode\n }\n\n this.assertAlive({\n subpath: childNode.subpath || childNode.subpathUponDeath\n })\n return this._autoUnbox ? childNode.value : childNode\n }\n\n override toString(): string {\n const path = (this.isAlive ? this.path : this.pathUponDeath) || \"<root>\"\n const identifier = this.identifier ? `(id: ${this.identifier})` : \"\"\n return `${this.type.name}@${path}${identifier}${this.isAlive ? \"\" : \" [dead]\"}`\n }\n\n finalizeCreation(): void {\n this.baseFinalizeCreation(() => {\n for (const child of this.getChildren()) {\n child.finalizeCreation()\n }\n\n this.fireInternalHook(Hook.afterCreationFinalization)\n })\n }\n\n detach(): void {\n if (!this.isAlive) {\n throw fail(`Error while detaching, node is not alive.`)\n }\n\n this.clearParent()\n }\n\n private preboot(): void {\n this._applyPatches = createActionInvoker(\n this.storedValue,\n \"@APPLY_PATCHES\",\n (patches: ReadonlyArray<IJsonPatch>) => {\n patches.forEach(patch => {\n if (!patch.path) {\n this.type.applySnapshot(this, patch.value)\n return\n }\n const parts = splitJsonPath(patch.path)\n const node = resolveNodeByPathParts(\n this,\n parts.slice(0, -1)\n ) as AnyObjectNode\n node.applyPatchLocally(parts[parts.length - 1]!, patch)\n })\n }\n )\n this._applySnapshot = createActionInvoker(\n this.storedValue,\n \"@APPLY_SNAPSHOT\",\n (snapshot: C) => {\n // the current snapshot needs no reconcile\n if (snapshot === (this.snapshot as any)) {\n return\n }\n this.type.applySnapshot(this, snapshot)\n }\n )\n\n addHiddenFinalProp(this.storedValue, \"$treenode\", this)\n addHiddenFinalProp(this.storedValue, \"toJSON\", toJSON)\n }\n\n aboutToDie(): void {\n if (\n this._observableInstanceState ===\n ObservableInstanceLifecycle.UNINITIALIZED\n ) {\n return\n }\n\n this.getChildren().forEach(node => {\n node.aboutToDie()\n })\n\n // beforeDestroy should run before the disposers since else we could end up in a situation where\n // a disposer added with addDisposer at this stage (beforeDestroy) is actually never released\n this.baseAboutToDie()\n\n this._internalEvents?.emit(InternalEvents.Dispose)\n this._internalEvents?.clear(InternalEvents.Dispose)\n }\n\n finalizeDeath(): void {\n // invariant: not called directly but from \"die\"\n this.getChildren().forEach(node => {\n node.finalizeDeath()\n })\n this.root.identifierCache!.notifyDied(this)\n\n // \"kill\" the computed prop and just store the last snapshot\n const snapshot = this.snapshot\n this._snapshotUponDeath = snapshot\n\n this._internalEvents?.clearAll()\n\n this.baseFinalizeDeath()\n }\n\n onSnapshot(onChange: (snapshot: S) => void): IDisposer {\n this._addSnapshotReaction()\n const unregister = this.internalEvents().register(\n InternalEvents.Snapshot,\n onChange\n )\n return () => {\n unregister()\n // The reaction re-serializes the whole subtree on every change, so leaving\n // it running once the last listener is gone would keep charging the node\n // for a snapshot nobody receives. Referential stability of getSnapshot()\n // does not depend on it — that comes from keepAlive on _snapshotComputed.\n if (!this._internalEvents?.hasSubscribers(InternalEvents.Snapshot)) {\n this._removeSnapshotReaction()\n }\n }\n }\n\n protected emitSnapshot(snapshot: S): void {\n this._internalEvents?.emit(InternalEvents.Snapshot, snapshot)\n }\n\n onPatch(\n handler: (patch: IJsonPatch, reversePatch: IJsonPatch) => void\n ): IDisposer {\n return this.internalEvents().register(InternalEvents.Patch, handler)\n }\n\n emitPatch(basePatch: IReversibleJsonPatch, source: AnyNode): void {\n if (this._internalEvents?.hasSubscribers(InternalEvents.Patch)) {\n const localizedPatch: IReversibleJsonPatch = {\n ...basePatch,\n path: `${source.path.slice(this.path.length)}/${basePatch.path}` // calculate the relative path of the patch\n }\n const [patch, reversePatch] = splitPatch(localizedPatch)\n this._internalEvents?.emit(InternalEvents.Patch, patch, reversePatch)\n }\n if (this.parent) {\n this.parent.emitPatch(basePatch, source)\n }\n }\n\n hasDisposer(disposer: () => void): boolean {\n return !!this._internalEvents?.has(InternalEvents.Dispose, disposer)\n }\n\n addDisposer(disposer: () => void): void {\n if (!this.hasDisposer(disposer)) {\n this.internalEvents().register(InternalEvents.Dispose, disposer, true)\n return\n }\n throw fail(\n \"cannot add a disposer when it is already registered for execution\"\n )\n }\n\n removeDisposer(disposer: () => void): void {\n if (!this._internalEvents?.has(InternalEvents.Dispose, disposer)) {\n throw fail(\n \"cannot remove a disposer which was never registered for execution\"\n )\n }\n this._internalEvents?.unregister(InternalEvents.Dispose, disposer)\n }\n\n private removeMiddleware(middleware: IMiddleware): void {\n if (this.middlewares) {\n const index = this.middlewares.indexOf(middleware)\n if (index >= 0) {\n this.middlewares.splice(index, 1)\n }\n }\n }\n\n addMiddleWare(handler: IMiddlewareHandler, includeHooks = true): IDisposer {\n const middleware = { handler, includeHooks }\n if (!this.middlewares) {\n this.middlewares = [middleware]\n } else {\n this.middlewares.push(middleware)\n }\n\n return () => {\n this.removeMiddleware(middleware)\n }\n }\n\n applyPatchLocally(subpath: string, patch: IJsonPatch): void {\n this.assertWritable({\n subpath\n })\n this.createObservableInstanceIfNeeded()\n this.type.applyPatchLocally(this, subpath, patch)\n }\n\n private _addSnapshotReaction(): void {\n if (!this._snapshotReactionDisposer) {\n const snapshotDisposer = reaction(\n () => this.snapshot,\n snapshot => this.emitSnapshot(snapshot),\n snapshotReactionOptions\n )\n this.addDisposer(snapshotDisposer)\n this._snapshotReactionDisposer = snapshotDisposer\n }\n }\n\n private _removeSnapshotReaction(): void {\n const disposer = this._snapshotReactionDisposer\n if (!disposer) {\n return\n }\n this._snapshotReactionDisposer = undefined\n // not removeDisposer(), which throws when the registration is already gone —\n // the last listener can be disposed from within a disposer, i.e. after\n // aboutToDie has cleared them\n this._internalEvents?.unregister(InternalEvents.Dispose, disposer)\n disposer()\n }\n\n // created on first registration: most nodes never get a listener\n private _internalEvents?: EventHandlers<InternalEventHandlers<S>>\n\n private internalEvents(): EventHandlers<InternalEventHandlers<S>> {\n return (this._internalEvents ??= new EventHandlers())\n }\n}\nObjectNode.prototype.createObservableInstance = action(\n ObjectNode.prototype.createObservableInstance\n)\nObjectNode.prototype.detach = action(ObjectNode.prototype.detach)\n\n/**\n * @internal\n * @hidden\n */\nexport type AnyObjectNode = ObjectNode<any, any, any>\n\n/**\n * @internal\n * @hidden\n */\nexport interface AssertAliveContext {\n subpath?: string | undefined\n actionContext?: IMiddlewareEvent | undefined\n}\n","import { action } from \"mobx\"\n\nimport {\n type BaseNode,\n assertArg,\n fail,\n getStateTreeNode,\n getStateTreeNodeSafe,\n getType,\n isMutable,\n isStateTreeNode,\n normalizeIdentifier,\n typeCheckFailure,\n typeCheckSuccess,\n typecheckInternal,\n type AnyNode,\n type AnyObjectNode,\n type IChildNodesMap,\n type IJsonPatch,\n type IStateTreeNode,\n type IValidationContext,\n type IValidationResult,\n type ModelPrimitive,\n type ObjectNode,\n type ScalarNode\n} from \"../../internal.ts\"\n\n/**\n * @internal\n * @hidden\n */\nexport enum TypeFlags {\n String = 1,\n Number = 1 << 1,\n Boolean = 1 << 2,\n Date = 1 << 3,\n Literal = 1 << 4,\n Array = 1 << 5,\n Map = 1 << 6,\n Object = 1 << 7,\n Frozen = 1 << 8,\n Optional = 1 << 9,\n Reference = 1 << 10,\n Identifier = 1 << 11,\n Late = 1 << 12,\n Refinement = 1 << 13,\n Union = 1 << 14,\n Null = 1 << 15,\n Undefined = 1 << 16,\n Integer = 1 << 17,\n Custom = 1 << 18,\n SnapshotProcessor = 1 << 19,\n Lazy = 1 << 20,\n Finite = 1 << 21,\n Float = 1 << 22\n}\n\n/**\n * The value `getSubTypes()` returns when a type cannot report its subtype,\n * which is distinct from reporting that it has none (`null`).\n */\nexport const cannotDetermineSubtype = \"cannotDetermine\"\n\n/**\n * A state tree node value.\n * @hidden\n */\nexport type STNValue<T, IT extends IAnyType> = T extends object\n ? T & IStateTreeNode<IT>\n : T\n\n/** @hidden */\nconst $type: unique symbol = Symbol(\"$type\")\n\n/**\n * A type, either complex or simple.\n */\nexport interface IType<C, S, T> {\n // fake, will never be present, just for typing\n /** @hidden */\n readonly [$type]: undefined\n\n /**\n * Friendly type name. Read-only: types are shared (unions built from the\n * same members are the same object), so renaming one renames it everywhere.\n * Name a type where it is built instead — `types.model(name, ...)`,\n * `.named()`, or the `name` option of `union`/`snapshotProcessor`.\n */\n readonly name: string\n\n /**\n * Name of the identifier attribute or null if none.\n */\n readonly identifierAttribute?: string | undefined\n\n /**\n * Creates an instance for the type given an snapshot input.\n *\n * The snapshot argument is required only when leaving it out would be a\n * runtime error: the creation type has a required member (`{} extends C` is\n * false) and does not admit `undefined`, which is what a type supplying its\n * own default snapshot — an array, a map, anything `optional` — does. So\n * `types.model({ a: types.string }).create()` is a compile error rather than\n * a runtime throw, while `types.model().create()`,\n * `types.array(types.string).create()` and\n * `types.optional(types.string, \"x\").create()` stay valid.\n *\n * @returns An instance of that type.\n */\n create(\n ...args: {} extends C\n ? [snapshot?: C, env?: any]\n : undefined extends C\n ? [snapshot?: C, env?: any]\n : [snapshot: C, env?: any]\n ): this[\"Type\"]\n\n /**\n * Checks if a given snapshot / instance is of the given type.\n *\n * @param thing Snapshot or instance to be checked.\n * @returns true if the value is of the current type, false otherwise.\n */\n is(thing: unknown): thing is C | this[\"Type\"]\n\n /**\n * Run's the type's typechecker on the given value with the given validation context.\n *\n * @param thing Value to be checked, either a snapshot or an instance.\n * @param context Validation context, an array of { subpaths, subtypes } that should be validated\n * @returns The validation result, an array with the list of validation errors.\n */\n validate(thing: C, context: IValidationContext): IValidationResult\n\n /**\n * Gets the textual representation of the type as a string.\n */\n describe(): string\n\n /**\n * @deprecated use `Instance<typeof MyType>` instead.\n * @hidden\n */\n readonly Type: STNValue<T, this>\n\n /**\n * @deprecated do not use.\n * @hidden\n */\n readonly TypeWithoutSTN: T\n\n /**\n * @deprecated use `SnapshotOut<typeof MyType>` instead.\n * @hidden\n */\n readonly SnapshotType: S\n\n /**\n * @deprecated use `SnapshotIn<typeof MyType>` instead.\n * @hidden\n */\n readonly CreationType: C\n\n // Internal api's\n\n /**\n * @internal\n * @hidden\n */\n flags: TypeFlags\n /**\n * @internal\n * @hidden\n */\n isType: true\n /**\n * @internal\n * @hidden\n */\n instantiate(\n parent: AnyObjectNode | null,\n subpath: string,\n environment: any,\n initialValue: C | T\n ): BaseNode<C, S, T>\n /**\n * @internal\n * @hidden\n */\n reconcile(\n current: BaseNode<C, S, T>,\n newValue: C | T,\n parent: AnyObjectNode,\n subpath: string\n ): BaseNode<C, S, T>\n /**\n * @internal\n * @hidden\n */\n getSnapshot(node: BaseNode<C, S, T>, applyPostProcess?: boolean): S\n /**\n * @internal\n * @hidden\n */\n isAssignableFrom(type: IAnyType): boolean\n /**\n * @internal\n * @hidden\n */\n getSubTypes(): IAnyType[] | IAnyType | null | typeof cannotDetermineSubtype\n}\n\n/**\n * Any kind of type.\n */\nexport interface IAnyType extends IType<any, any, any> {}\n\n/**\n * A simple type, this is, a type where the instance and the snapshot representation are the same.\n */\nexport interface ISimpleType<T> extends IType<T, T, T> {}\n\n/** @hidden */\nexport type Primitives = ModelPrimitive | null | undefined\n\n/**\n * A complex type.\n * @deprecated just for compatibility with old versions, could be deprecated on the next major version\n * @hidden\n */\nexport interface IComplexType<C, S, T> extends IType<C, S, T & object> {}\n\n/**\n * Any kind of complex type.\n */\nexport interface IAnyComplexType extends IType<any, any, object> {}\n\n/** @hidden */\nexport type ExtractCSTWithSTN<\n IT extends {\n [$type]: undefined\n CreationType: any\n SnapshotType: any\n Type: any\n }\n> = IT[\"CreationType\"] | IT[\"SnapshotType\"] | IT[\"Type\"]\n\n/**\n * The instance representation of a given type.\n */\nexport type Instance<T> = T extends { [$type]: undefined; Type: any }\n ? T[\"Type\"]\n : T\n\n/**\n * The input (creation) snapshot representation of a given type.\n */\nexport type SnapshotIn<T> = T extends { [$type]: undefined; CreationType: any }\n ? T[\"CreationType\"]\n : T extends IStateTreeNode<infer IT>\n ? IT[\"CreationType\"]\n : T\n\n/**\n * The output snapshot representation of a given type.\n */\nexport type SnapshotOut<T> = T extends { [$type]: undefined; SnapshotType: any }\n ? T[\"SnapshotType\"]\n : T extends IStateTreeNode<infer IT>\n ? IT[\"SnapshotType\"]\n : T\n\n/**\n * A type which is equivalent to the union of SnapshotIn and Instance types of a given typeof TYPE or typeof VARIABLE.\n * For primitives it defaults to the primitive itself.\n *\n * For example:\n * - `SnapshotOrInstance<typeof ModelA> = SnapshotIn<typeof ModelA> | Instance<typeof ModelA>`\n * - `SnapshotOrInstance<typeof self.a (where self.a is a ModelA)> = SnapshotIn<typeof ModelA> | Instance<typeof ModelA>`\n *\n * Usually you might want to use this when your model has a setter action that sets a property.\n *\n * Example:\n * ```ts\n * const ModelA = types.model({\n * n: types.number\n * })\n *\n * const ModelB = types.model({\n * innerModel: ModelA\n * }).actions(self => ({\n * // this will accept as property both the snapshot and the instance, whichever is preferred\n * setInnerModel(m: SnapshotOrInstance<typeof self.innerModel>) {\n * self.innerModel = cast(m)\n * }\n * }))\n * ```\n */\nexport type SnapshotOrInstance<T> = SnapshotIn<T> | Instance<T>\n\n/**\n * A base type produces a MST node (Node in the state tree)\n *\n * @internal\n * @hidden\n */\nexport abstract class BaseType<\n C,\n S,\n T,\n N extends BaseNode<any, any, any> = BaseNode<C, S, T>\n> implements IType<C, S, T> {\n // `declare`, not a definite-assignment `!`: none of these five exist at\n // runtime — `$type` is the nominal brand and C/S/T/N only make the inner\n // types available to subclasses as `this[\"C\"]` etc. Under\n // useDefineForClassFields a `!` field is still *emitted*, so every type\n // object in the process was materializing five own slots it never reads.\n declare readonly [$type]: undefined\n\n // these are just to make inner types avaialable to inherited classes\n declare readonly C: C\n declare readonly S: S\n declare readonly T: T\n declare readonly N: N\n\n // on the prototype, not on every instance: it is the same `true` for every\n // type ever built, and an own slot per type is exactly the kind of per-type\n // charge ADR 0003 is about. Assigned below the class body.\n declare readonly isType: true\n\n // `undefined` on the prototype rather than an own slot per type: the\n // composite types leave the name unset (see `name` below), so for a union or\n // an optional this field only ever held `undefined`. The own slot appears\n // when a name is actually assigned, which is the same trick as `isType`.\n declare private _name?: string\n\n /**\n * Builds the name of a type that does not get one handed to it. Composite\n * types (`union`, `array`, `map`, `reference`, ...) override this to fold\n * their members' names; see {@link name}. It runs after construction, so\n * unlike a `super(...)` argument it can read the subclass's own fields.\n */\n protected computeName(): string {\n // istanbul ignore next\n throw fail(`${this.constructor.name} has neither a name nor a computeName`)\n }\n\n /**\n * Friendly type name.\n *\n * A composite type folds its members' names, which for a union is a map +\n * join over every member — and the result is read only by error messages and\n * `describe()`. So those types leave it unset and it is built on first read\n * and cached: a union that never fails a typecheck never builds one, and\n * jbrowse builds a union per config slot, tens of thousands per session load.\n *\n * Deliberately not a lambda passed to the constructor: that allocated a\n * closure per type (the very cost being avoided) and made two separately\n * built but equivalent types compare unequal, since the closures differ.\n */\n get name(): string {\n return (this._name ??= this.computeName())\n }\n\n set name(value: string) {\n this._name = value\n }\n\n constructor(name?: string) {\n if (name !== undefined) {\n this._name = name\n }\n }\n\n create(snapshot?: C, environment?: any) {\n typecheckInternal(this, snapshot)\n return this.instantiate(null, \"\", environment, snapshot!).value\n }\n\n getSnapshot(_node: N, _applyPostProcess?: boolean): S {\n // istanbul ignore next\n throw fail(\"unimplemented method\")\n }\n\n abstract reconcile(\n current: N,\n newValue: C | T,\n parent: AnyObjectNode,\n subpath: string\n ): N\n\n abstract instantiate(\n parent: AnyObjectNode | null,\n subpath: string,\n environment: any,\n initialValue: C | T\n ): N\n\n declare abstract flags: TypeFlags\n\n describe(): string {\n return this.name\n }\n\n abstract isValidSnapshot(\n value: C,\n context: IValidationContext\n ): IValidationResult\n\n isAssignableFrom(type: IAnyType): boolean {\n return type === this\n }\n\n validate(value: C | T, context: IValidationContext): IValidationResult {\n const node = getStateTreeNodeSafe(value)\n if (node) {\n const valueType = getType(value)\n return this.isAssignableFrom(valueType)\n ? typeCheckSuccess()\n : typeCheckFailure(context, value)\n // it is tempting to compare snapshots, but in that case we should always clone on assignments...\n }\n\n return this.isValidSnapshot(value as C, context)\n }\n\n is(thing: unknown): thing is any {\n return this.validate(thing as C, [{ path: \"\", type: this }]).length === 0\n }\n\n get Type(): any {\n // istanbul ignore next\n throw fail(\n \"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 }\n get TypeWithoutSTN(): any {\n // istanbul ignore next\n throw fail(\n \"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 }\n get SnapshotType(): any {\n // istanbul ignore next\n throw fail(\n \"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 }\n get CreationType(): any {\n // istanbul ignore next\n throw fail(\n \"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 }\n\n abstract getSubTypes():\n | IAnyType[]\n | IAnyType\n | null\n | typeof cannotDetermineSubtype\n}\nBaseType.prototype.create = action(BaseType.prototype.create)\n// Defaults that every type shares, kept off the individual type objects. See\n// `isType` and `_name` in the class body.\nObject.assign(BaseType.prototype as object, { isType: true, _name: undefined })\n\n/**\n * @internal\n * @hidden\n */\nexport type ExtractNodeType<IT extends IAnyType> =\n IT extends BaseType<any, any, any, infer N> ? N : never\n\n/**\n * A complex type produces a MST node (Node in the state tree)\n *\n * @internal\n * @hidden\n */\nexport abstract class ComplexType<C, S, T> extends BaseType<\n C,\n S,\n T,\n ObjectNode<C, S, T>\n> {\n identifierAttribute?: string | undefined\n\n override create(snapshot: C = this.getDefaultSnapshot(), environment?: any) {\n return super.create(snapshot, environment)\n }\n\n getValue(node: this[\"N\"]): T {\n node.createObservableInstanceIfNeeded()\n return node.storedValue\n }\n\n abstract getDefaultSnapshot(): C\n\n abstract createNewInstance(childNodes: IChildNodesMap): T\n abstract finalizeNewInstance(node: this[\"N\"], instance: any): void\n\n abstract applySnapshot(node: this[\"N\"], snapshot: C): void\n abstract applyPatchLocally(\n node: this[\"N\"],\n subpath: string,\n patch: IJsonPatch\n ): void\n abstract processInitialSnapshot(childNodes: IChildNodesMap): S\n\n abstract getChildren(node: this[\"N\"]): ReadonlyArray<AnyNode>\n abstract getChildNode(node: this[\"N\"], key: string): AnyNode\n abstract getChildType(propertyName?: string): IAnyType\n abstract initializeChildNodes(node: this[\"N\"], snapshot: any): IChildNodesMap\n abstract removeChild(node: this[\"N\"], subpath: string): void\n\n isMatchingSnapshotId(current: this[\"N\"], snapshot: C): boolean {\n return (\n !current.identifierAttribute ||\n current.identifier ===\n normalizeIdentifier((snapshot as any)[current.identifierAttribute])\n )\n }\n\n private tryToReconcileNode(current: this[\"N\"], newValue: C | T) {\n if (current.isDetaching) {\n return false\n }\n if ((current.snapshot as any) === newValue) {\n // newValue is the current snapshot of the node, noop\n return true\n }\n if (isStateTreeNode(newValue) && getStateTreeNode(newValue) === current) {\n // the current node is the same as the new one\n return true\n }\n if (\n current.type === this &&\n isMutable(newValue) &&\n !isStateTreeNode(newValue) &&\n this.isMatchingSnapshotId(current, newValue as any)\n ) {\n // the newValue has no node, so can be treated like a snapshot\n // we can reconcile\n current.applySnapshot(newValue as C)\n return true\n }\n return false\n }\n\n reconcile(\n current: this[\"N\"],\n newValue: C | T,\n parent: AnyObjectNode,\n subpath: string\n ): this[\"N\"] {\n const nodeReconciled = this.tryToReconcileNode(current, newValue)\n if (nodeReconciled) {\n current.setParent(parent, subpath)\n return current\n }\n\n // current node cannot be recycled in any way\n current.die() // noop if detaching\n // attempt to reuse the new one\n if (isStateTreeNode(newValue) && this.isAssignableFrom(getType(newValue))) {\n // newValue is a Node as well, move it here..\n const newNode = getStateTreeNode(newValue)\n newNode.setParent(parent, subpath)\n return newNode\n }\n // nothing to do, we have to create a new node\n return this.instantiate(parent, subpath, undefined, newValue)\n }\n\n getSubTypes() {\n return null\n }\n}\n\n/**\n * @internal\n * @hidden\n */\nexport abstract class SimpleType<C, S, T> extends BaseType<\n C,\n S,\n T,\n ScalarNode<C, S, T>\n> {\n abstract override instantiate(\n parent: AnyObjectNode | null,\n subpath: string,\n environment: any,\n initialValue: C\n ): this[\"N\"]\n\n createNewInstance(snapshot: C): T {\n return snapshot as any\n }\n\n getValue(node: this[\"N\"]): T {\n return node.storedValue\n }\n\n override getSnapshot(node: this[\"N\"]): S {\n return node.storedValue\n }\n\n reconcile(\n current: this[\"N\"],\n newValue: C,\n parent: AnyObjectNode,\n subpath: string\n ): this[\"N\"] {\n // reconcile only if type and value are still the same, and only if the node is not detaching\n if (\n !current.isDetaching &&\n current.type === this &&\n current.storedValue === newValue\n ) {\n return current\n }\n const res = this.instantiate(parent, subpath, undefined, newValue)\n current.die() // noop if detaching\n return res\n }\n\n getSubTypes() {\n return null\n }\n}\n\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 */\nexport function isType(value: unknown): value is IAnyType {\n return (\n typeof value === \"object\" && (value as IAnyType | null)?.isType === true\n )\n}\n\n/**\n * The one type a wrapper hands everything to: what an `optional`,\n * `stripDefault`, `refinement`, `snapshotProcessor` or (resolved) `late`\n * wraps. `undefined` for any other type, including a union or a `resilient`,\n * which pick a type per value.\n *\n * Resolves a `late` type's definition if it has not been read yet.\n */\nexport function getWrappedType(type: IAnyType): IAnyType | undefined {\n const subtype = type.getSubTypes()\n return isType(subtype) ? subtype : undefined\n}\n\n/**\n * Strips every wrapper {@link getWrappedType} sees through, down to the type\n * that actually builds the value: for a complex type `T`,\n * `getType(T.create(snapshot)) === unwrapType(T)`.\n *\n * `types.model({ xs: types.array(X) }).properties.xs`, for instance, is an\n * `optional` whose unwrapped type is the array type.\n */\nexport function unwrapType(type: IAnyType): IAnyType {\n const wrapped = getWrappedType(type)\n return wrapped ? unwrapType(wrapped) : type\n}\n\n/**\n * @internal\n * @hidden\n */\nexport function assertIsType(type: IAnyType, argNumber: number | number[]) {\n assertArg(type, isType, \"mobx-state-tree type\", argNumber)\n}\n","import { type IMiddlewareEvent, type IMiddlewareHandler } from \"../internal.ts\"\n\nexport interface IActionTrackingMiddlewareHooks<T> {\n filter?: (call: IMiddlewareEvent) => boolean\n onStart: (call: IMiddlewareEvent) => T\n onResume: (call: IMiddlewareEvent, context: T) => void\n onSuspend: (call: IMiddlewareEvent, context: T) => void\n onSuccess: (call: IMiddlewareEvent, context: T, result: any) => void\n onFail: (call: IMiddlewareEvent, context: T, error: any) => void\n}\n\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 */\nexport function createActionTrackingMiddleware<T = any>(\n hooks: IActionTrackingMiddlewareHooks<T>\n): IMiddlewareHandler {\n // per middleware, not per module: the entries hold the `context` this\n // middleware's own onStart returned, so two middlewares on one tree would\n // otherwise overwrite each other's context and then delete the shared entry —\n // whichever saw `flow_return` second dereferenced `undefined`.\n // createActionTrackingMiddleware2 scopes its map the same way.\n const runningActions = new Map<\n number,\n { async: boolean; call: IMiddlewareEvent; context: T }\n >()\n\n return function actionTrackingMiddleware(\n call: IMiddlewareEvent,\n next: (actionCall: IMiddlewareEvent) => any,\n _abort: (value: any) => any\n ) {\n switch (call.type) {\n case \"action\": {\n if (!hooks.filter || hooks.filter(call) === true) {\n const context = hooks.onStart(call)\n hooks.onResume(call, context)\n runningActions.set(call.id, {\n call,\n context,\n async: false\n })\n try {\n const res = next(call)\n hooks.onSuspend(call, context)\n if (runningActions.get(call.id)!.async === false) {\n runningActions.delete(call.id)\n hooks.onSuccess(call, context, res)\n }\n return res\n } 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 case \"flow_spawn\": {\n const root = runningActions.get(call.rootId)!\n root.async = true\n return next(call)\n }\n case \"flow_resume\":\n case \"flow_resume_error\": {\n const root = runningActions.get(call.rootId)!\n hooks.onResume(call, root.context)\n try {\n return next(call)\n } finally {\n hooks.onSuspend(call, root.context)\n }\n }\n case \"flow_throw\": {\n const root = runningActions.get(call.rootId)!\n runningActions.delete(call.rootId)\n hooks.onFail(call, root.context, call.args[0])\n return next(call)\n }\n case \"flow_return\": {\n const 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","import {\n type IActionContext,\n type IMiddlewareEvent,\n type IMiddlewareHandler\n} from \"../internal.ts\"\n\nexport interface IActionTrackingMiddleware2Call<\n TEnv\n> extends Readonly<IActionContext> {\n env: TEnv | undefined\n readonly parentCall?: IActionTrackingMiddleware2Call<TEnv> | undefined\n}\n\nexport interface IActionTrackingMiddleware2Hooks<TEnv> {\n filter?: (call: IActionTrackingMiddleware2Call<TEnv>) => boolean\n onStart: (call: IActionTrackingMiddleware2Call<TEnv>) => void\n onFinish: (call: IActionTrackingMiddleware2Call<TEnv>, error?: any) => void\n}\n\nclass RunningAction {\n private flowsPending = 0\n private running = true\n\n constructor(\n public readonly hooks: IActionTrackingMiddleware2Hooks<any> | undefined,\n readonly call: IActionTrackingMiddleware2Call<any>\n ) {\n if (hooks) {\n hooks.onStart(call)\n }\n }\n\n finish(error?: any) {\n if (this.running) {\n this.running = false\n if (this.hooks) {\n this.hooks.onFinish(this.call, error)\n }\n }\n }\n\n incFlowsPending() {\n this.flowsPending++\n }\n\n decFlowsPending() {\n this.flowsPending--\n }\n\n get hasFlowsPending() {\n return this.flowsPending > 0\n }\n}\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 */\nexport function createActionTrackingMiddleware2<TEnv = any>(\n middlewareHooks: IActionTrackingMiddleware2Hooks<TEnv>\n): IMiddlewareHandler {\n const runningActions = new Map<number, RunningAction>()\n\n return function actionTrackingMiddleware(\n call: IMiddlewareEvent,\n next: (actionCall: IMiddlewareEvent) => any\n ) {\n // find parentRunningAction\n const parentRunningAction = call.parentActionEvent\n ? runningActions.get(call.parentActionEvent.id)\n : undefined\n\n if (call.type === \"action\") {\n const newCall: IActionTrackingMiddleware2Call<TEnv> = {\n ...call,\n // make a shallow copy of the parent action env\n env: parentRunningAction?.call.env,\n parentCall: parentRunningAction?.call\n }\n\n const passesFilter =\n !middlewareHooks.filter || middlewareHooks.filter(newCall)\n const hooks = passesFilter ? middlewareHooks : undefined\n\n const runningAction = new RunningAction(hooks, newCall)\n runningActions.set(call.id, runningAction)\n\n let res\n try {\n res = next(call)\n } catch (e) {\n runningActions.delete(call.id)\n runningAction.finish(e)\n throw e\n }\n // sync action finished\n if (!runningAction.hasFlowsPending) {\n runningActions.delete(call.id)\n runningAction.finish()\n }\n return res\n } else {\n if (!parentRunningAction) {\n return next(call)\n }\n\n switch (call.type) {\n case \"flow_spawn\": {\n parentRunningAction.incFlowsPending()\n return next(call)\n }\n case \"flow_resume\":\n case \"flow_resume_error\": {\n return next(call)\n }\n case \"flow_throw\": {\n const error = call.args[0]\n try {\n return next(call)\n } finally {\n parentRunningAction.decFlowsPending()\n if (!parentRunningAction.hasFlowsPending) {\n runningActions.delete(call.parentActionEvent!.id)\n parentRunningAction.finish(error)\n }\n }\n }\n case \"flow_return\": {\n try {\n return next(call)\n } finally {\n parentRunningAction.decFlowsPending()\n if (!parentRunningAction.hasFlowsPending) {\n runningActions.delete(call.parentActionEvent!.id)\n parentRunningAction.finish()\n }\n }\n }\n }\n }\n }\n}\n","import { runInAction } from \"mobx\"\n\nimport {\n type IActionContext,\n type IAnyStateTreeNode,\n type IDisposer,\n addMiddleware,\n applyPatch,\n applySnapshot,\n asArray,\n assertArg,\n assertIsStateTreeNode,\n devMode,\n fail,\n getRelativePathBetweenNodes,\n getRunningActionContext,\n getStateTreeNode,\n getType,\n isArray,\n isPlainObject,\n isPrimitive,\n isProtected,\n isRoot,\n isStateTreeNode,\n tryResolve,\n warnError\n} from \"../internal.ts\"\n\nexport interface ISerializedActionCall {\n name: string\n path?: string\n args?: any[]\n}\n\nexport interface IActionRecorder {\n actions: ReadonlyArray<ISerializedActionCall>\n readonly recording: boolean\n stop(): void\n resume(): void\n replay(target: IAnyStateTreeNode): void\n}\n\nfunction serializeArgument(arg: any): any {\n if (arg instanceof Date) {\n return { $MST_DATE: arg.getTime() }\n }\n if (isPrimitive(arg)) {\n return arg\n }\n // We should not serialize MST nodes, even if we can, because we don't know if the receiving party can handle a raw snapshot instead of an\n // MST type instance. So if one wants to serialize a MST node that was pass in, either explitly pass: 1: an id, 2: a (relative) path, 3: a snapshot\n if (isStateTreeNode(arg)) {\n return serializeTheUnserializable(`[MSTNode: ${getType(arg).name}]`)\n }\n if (typeof arg === \"function\") {\n return serializeTheUnserializable(`[function]`)\n }\n if (typeof arg === \"object\" && !isPlainObject(arg) && !isArray(arg)) {\n return serializeTheUnserializable(\n `[object ${arg?.constructor?.name || \"Complex Object\"}]`\n )\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 return arg\n } catch (e) {\n return serializeTheUnserializable(`${e}`)\n }\n}\n\nfunction deserializeArgument(value: any): any {\n if (value && typeof value === \"object\" && \"$MST_DATE\" in value) {\n return new Date(value[\"$MST_DATE\"])\n }\n return value\n}\n\nfunction serializeTheUnserializable(baseType: string) {\n return {\n $MST_UNSERIALIZABLE: true,\n type: baseType\n }\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 */\nexport function applyAction(\n target: IAnyStateTreeNode,\n actions: ISerializedActionCall | ISerializedActionCall[]\n): void {\n // check all arguments\n assertIsStateTreeNode(target, 1)\n assertArg(actions, a => typeof a === \"object\", \"object or array\", 2)\n\n runInAction(() => {\n asArray(actions).forEach(action => baseApplyAction(target, action))\n })\n}\n\nfunction baseApplyAction(\n target: IAnyStateTreeNode,\n action: ISerializedActionCall\n): any {\n const resolvedTarget = tryResolve(target, action.path || \"\")\n if (!resolvedTarget) {\n throw fail(`Invalid action path: ${action.path || \"\"}`)\n }\n const node = getStateTreeNode(resolvedTarget)\n\n // Reserved functions\n if (action.name === \"@APPLY_PATCHES\") {\n return applyPatch.call(null, resolvedTarget, action.args![0])\n }\n if (action.name === \"@APPLY_SNAPSHOT\") {\n return applySnapshot.call(null, resolvedTarget, action.args![0])\n }\n\n if (!(typeof resolvedTarget[action.name] === \"function\")) {\n throw fail(`Action '${action.name}' does not exist in '${node.path}'`)\n }\n return resolvedTarget[action.name](\n ...(action.args ? action.args.map(deserializeArgument) : [])\n )\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 */\nexport function recordActions(\n subject: IAnyStateTreeNode,\n filter?: (\n action: ISerializedActionCall,\n actionContext: IActionContext | undefined\n ) => boolean\n): IActionRecorder {\n // check all arguments\n assertIsStateTreeNode(subject, 1)\n\n const actions: ISerializedActionCall[] = []\n const listener = (call: ISerializedActionCall) => {\n const recordThis = filter ? filter(call, getRunningActionContext()) : true\n if (recordThis) {\n actions.push(call)\n }\n }\n\n let disposer: IDisposer | undefined\n const recorder: IActionRecorder = {\n actions,\n get recording() {\n return !!disposer\n },\n stop() {\n if (disposer) {\n disposer()\n disposer = undefined\n }\n },\n resume() {\n if (disposer) {\n return\n }\n disposer = onAction(subject, listener)\n },\n replay(target) {\n applyAction(target, actions)\n }\n }\n\n recorder.resume()\n return recorder\n}\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 */\nexport function onAction(\n target: IAnyStateTreeNode,\n listener: (call: ISerializedActionCall) => void,\n attachAfter = false\n): IDisposer {\n // check all arguments\n assertIsStateTreeNode(target, 1)\n if (devMode()) {\n if (!isRoot(target)) {\n warnError(\n \"Warning: Attaching onAction listeners to non root nodes is dangerous: No events will be emitted for actions initiated higher up in the tree.\"\n )\n }\n if (!isProtected(target)) {\n warnError(\n \"Warning: Attaching onAction listeners to non protected nodes is dangerous: No events will be emitted for direct modifications without action.\"\n )\n }\n }\n\n return addMiddleware(target, function handler(rawCall, next) {\n if (rawCall.type === \"action\" && rawCall.id === rawCall.rootId) {\n const sourceNode = getStateTreeNode(rawCall.context)\n const info = {\n name: rawCall.name,\n path: getRelativePathBetweenNodes(getStateTreeNode(target), sourceNode),\n args: rawCall.args.map(serializeArgument)\n }\n if (attachAfter) {\n const 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","import { action as mobxAction } from \"mobx\"\n\nimport {\n Hook,\n devMode,\n fail,\n getRoot,\n getStateTreeNode,\n warnError\n} from \"../internal.ts\"\n\nimport type {\n AnyObjectNode,\n IActionContext,\n IAnyStateTreeNode,\n IDisposer\n} from \"../internal.ts\"\n\nexport type IMiddlewareEventType =\n | \"action\"\n | \"flow_spawn\"\n | \"flow_resume\"\n | \"flow_resume_error\"\n | \"flow_return\"\n | \"flow_throw\"\n// | \"task_spawn TODO, see #273\"\n\nexport interface IMiddlewareEvent extends IActionContext {\n /** Event type */\n readonly type: IMiddlewareEventType\n\n /** Parent event unique id */\n readonly parentId: number\n /** Parent event object */\n readonly parentEvent: IMiddlewareEvent | undefined\n\n /** Root event unique id */\n readonly rootId: number\n /** Id of all events, from root until current (excluding current) */\n readonly allParentIds: number[]\n}\n\nexport type FunctionWithFlag = ((...args: any[]) => any) & {\n _isMSTAction?: boolean | undefined\n _isFlowAction?: boolean | undefined\n $mst_middleware?: IMiddleware[] | undefined\n}\n\n/**\n * @internal\n * @hidden\n */\nexport type IMiddleware = {\n handler: IMiddlewareHandler\n includeHooks: boolean\n}\n\nexport type IMiddlewareHandler = (\n actionCall: IMiddlewareEvent,\n next: (actionCall: IMiddlewareEvent, callback?: (value: any) => any) => void,\n abort: (value: any) => void\n) => any\n\nlet nextActionId = 1\nlet currentActionContext: IMiddlewareEvent | undefined\n\n/**\n * @internal\n * @hidden\n */\nexport function getCurrentActionContext() {\n return currentActionContext\n}\n\n/**\n * @internal\n * @hidden\n */\nexport function getNextActionId() {\n return nextActionId++\n}\n\n// TODO: optimize away entire action context if there is no middleware in tree?\n/**\n * @internal\n * @hidden\n */\nexport function runWithActionContext(\n context: IMiddlewareEvent,\n fn: (...args: any[]) => any\n) {\n const node = getStateTreeNode(context.context)\n\n if (context.type === \"action\") {\n node.assertAlive({\n actionContext: context\n })\n }\n\n const baseIsRunningAction = node._isRunningAction\n node._isRunningAction = true\n const previousContext = currentActionContext\n currentActionContext = context\n try {\n return runMiddleWares(node, context, fn)\n } finally {\n currentActionContext = previousContext\n node._isRunningAction = baseIsRunningAction\n }\n}\n\n/**\n * @internal\n * @hidden\n */\nexport function getParentActionContext(\n parentContext: IMiddlewareEvent | undefined\n) {\n if (!parentContext) {\n return undefined\n }\n if (parentContext.type === \"action\") {\n return parentContext\n }\n return parentContext.parentActionEvent\n}\n\n/**\n * @internal\n * @hidden\n */\nexport function createActionInvoker<T extends FunctionWithFlag>(\n target: IAnyStateTreeNode,\n name: string,\n fn: T\n) {\n const res = function (...args: any[]) {\n const id = getNextActionId()\n const parentContext = currentActionContext\n const parentActionContext = getParentActionContext(parentContext)\n\n return runWithActionContext(\n {\n type: \"action\",\n name,\n id,\n args,\n context: target,\n tree: getRoot(target),\n rootId: parentContext ? parentContext.rootId : id,\n parentId: parentContext ? parentContext.id : 0,\n allParentIds: parentContext\n ? [...parentContext.allParentIds, parentContext.id]\n : [],\n parentEvent: parentContext,\n parentActionEvent: parentActionContext\n },\n fn\n )\n }\n ;(res as FunctionWithFlag)._isMSTAction = true\n ;(res as FunctionWithFlag)._isFlowAction = fn._isFlowAction\n return res\n}\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 */\nexport function addMiddleware(\n target: IAnyStateTreeNode,\n handler: IMiddlewareHandler,\n includeHooks = true\n): IDisposer {\n const node = getStateTreeNode(target)\n if (devMode()) {\n if (!node.isProtectionEnabled) {\n warnError(\n \"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/**\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 */\nexport function decorate<T extends (...args: any[]) => any>(\n handler: IMiddlewareHandler,\n fn: T,\n includeHooks = true\n): T {\n const middleware: IMiddleware = { handler, includeHooks }\n const f = fn as FunctionWithFlag\n if (!f.$mst_middleware) {\n f.$mst_middleware = []\n }\n f.$mst_middleware.push(middleware)\n return fn\n}\n\nclass CollectedMiddlewares {\n private arrayIndex = 0\n private inArrayIndex = 0\n private middlewares: IMiddleware[][] = []\n\n constructor(node: AnyObjectNode, fn: (...args: any[]) => any) {\n // we just push middleware arrays into an array of arrays to avoid making copies\n const mw = (fn as FunctionWithFlag).$mst_middleware\n if (mw) {\n this.middlewares.push(mw)\n }\n let n: AnyObjectNode | null = node\n // Find all middlewares. Optimization: cache this?\n while (n) {\n if (n.middlewares) {\n this.middlewares.push(n.middlewares)\n }\n n = n.parent\n }\n }\n\n get isEmpty() {\n return this.middlewares.length <= 0\n }\n\n getNextMiddleware(): IMiddleware | undefined {\n const array = this.middlewares[this.arrayIndex]\n if (!array) {\n return undefined\n }\n const item = array[this.inArrayIndex++]\n if (!item) {\n this.arrayIndex++\n this.inArrayIndex = 0\n return this.getNextMiddleware()\n }\n return item\n }\n}\n\nfunction runMiddleWares(\n node: AnyObjectNode,\n baseCall: IMiddlewareEvent,\n originalFn: (...args: any[]) => any\n): any {\n const middlewares = new CollectedMiddlewares(node, originalFn)\n // Short circuit\n if (middlewares.isEmpty) {\n return mobxAction(originalFn)(...baseCall.args)\n }\n\n let result: any = null\n\n function runNextMiddleware(call: IMiddlewareEvent): any {\n const middleware = middlewares.getNextMiddleware()\n const handler = middleware?.handler\n\n if (!handler) {\n return mobxAction(originalFn)(...call.args)\n }\n\n // skip hooks if asked to\n if (!middleware.includeHooks && call.name in Hook) {\n return runNextMiddleware(call)\n }\n\n let nextInvoked = false\n function next(\n call2: IMiddlewareEvent,\n callback?: (value: any) => any\n ): void {\n nextInvoked = true\n // the result can contain\n // - the non manipulated return value from an action\n // - the non manipulated abort value\n // - one of the above but manipulated through the callback function\n result = runNextMiddleware(call2)\n if (callback) {\n result = callback(result)\n }\n }\n\n let abortInvoked = false\n function abort(value: any) {\n abortInvoked = true\n // overwrite the result\n // can be manipulated through middlewares earlier in the queue using the callback fn\n result = value\n }\n\n handler(call, next, abort)\n if (devMode()) {\n if (!nextInvoked && !abortInvoked) {\n const node2 = getStateTreeNode(call.tree)\n throw fail(\n `Neither the next() nor the abort() callback within the middleware ${handler.name} for the action: \"${call.name}\" on the node: ${node2.type.name} was invoked.`\n )\n } else if (nextInvoked && abortInvoked) {\n const node2 = getStateTreeNode(call.tree)\n throw fail(\n `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 return runNextMiddleware(baseCall)\n}\n","import { type IAnyStateTreeNode, type IMiddlewareEvent } from \"../internal.ts\"\nimport { getCurrentActionContext } from \"./action.ts\"\n\nexport interface IActionContext {\n /** Event name (action name for actions) */\n readonly name: string\n\n /** Event unique id */\n readonly id: number\n\n /** Parent action event object */\n readonly parentActionEvent: IMiddlewareEvent | undefined\n\n /** Event context (node where the action was invoked) */\n readonly context: IAnyStateTreeNode\n /** Event tree (root node of the node where the action was invoked) */\n readonly tree: IAnyStateTreeNode\n\n /** Event arguments in an array (action arguments for actions) */\n readonly args: any[]\n}\n\n/**\n * Returns the currently executing MST action context, or undefined if none.\n */\nexport function getRunningActionContext(): IActionContext | undefined {\n let current = getCurrentActionContext()\n while (current && current.type !== \"action\") {\n current = current.parentActionEvent\n }\n return current\n}\n\nfunction _isActionContextThisOrChildOf(\n actionContext: IActionContext,\n sameOrParent: number | IActionContext | IMiddlewareEvent,\n includeSame: boolean\n) {\n const parentId =\n typeof sameOrParent === \"number\" ? sameOrParent : sameOrParent.id\n\n let current: IActionContext | IMiddlewareEvent | undefined = includeSame\n ? actionContext\n : actionContext.parentActionEvent\n while (current) {\n if (current.id === parentId) {\n return true\n }\n current = current.parentActionEvent\n }\n return false\n}\n\n/**\n * Returns if the given action context is a parent of this action context.\n */\nexport function isActionContextChildOf(\n actionContext: IActionContext,\n parent: number | IActionContext | IMiddlewareEvent\n) {\n return _isActionContextThisOrChildOf(actionContext, parent, false)\n}\n\n/**\n * Returns if the given action context is this or a parent of this action context.\n */\nexport function isActionContextThisOrChildOf(\n actionContext: IActionContext,\n parentOrThis: number | IActionContext | IMiddlewareEvent\n) {\n return _isActionContextThisOrChildOf(actionContext, parentOrThis, true)\n}\n","import {\n EMPTY_ARRAY,\n type ExtractCSTWithSTN,\n type IAnyType,\n fail,\n getStateTreeNode,\n isPrimitive,\n isPrimitiveType,\n isStateTreeNode,\n isTypeCheckingEnabled\n} from \"../../internal.ts\"\n\n/** Validation context entry, this is, where the validation should run against which type */\nexport interface IValidationContextEntry {\n /** Subpath where the validation should be run, or an empty string to validate it all */\n path: string\n /** Type to validate the subpath against */\n type: IAnyType\n}\n\n/** Array of validation context entries */\nexport type IValidationContext = IValidationContextEntry[]\n\n/** Type validation error */\nexport interface IValidationError {\n /** Validation context */\n context: IValidationContext\n /** Value that was being validated, either a snapshot or an instance */\n value: any\n /** Error message */\n message?: string | undefined\n}\n\n/** Type validation result, which is an array of type validation errors */\nexport type IValidationResult = ReadonlyArray<IValidationError>\n\nconst MAX_STRINGIFY_DEPTH = 3\nconst MAX_STRINGIFY_ARRAY_ITEMS = 10\nconst MAX_STRINGIFY_OBJECT_KEYS = 20\nconst MAX_STRINGIFY_STRING_LENGTH = 100\n\n// Recursively cap depth, array length, object key count, and string length so a\n// huge offending snapshot degrades into readable, bounded context instead of a\n// wall of text that then gets sliced mid-structure. The depth cap also bounds\n// recursion on circular structures.\nfunction truncateForStringify(value: any, depth: number): any {\n if (typeof value === \"string\") {\n return value.length > MAX_STRINGIFY_STRING_LENGTH\n ? `${value.substring(0, MAX_STRINGIFY_STRING_LENGTH)}… (${value.length - MAX_STRINGIFY_STRING_LENGTH} more characters)`\n : value\n }\n if (value === null || typeof value !== \"object\") {\n return value\n }\n if (depth >= MAX_STRINGIFY_DEPTH) {\n return Array.isArray(value) ? \"[…]\" : \"{…}\"\n }\n if (Array.isArray(value)) {\n const items = value\n .slice(0, MAX_STRINGIFY_ARRAY_ITEMS)\n .map(item => truncateForStringify(item, depth + 1))\n if (value.length > MAX_STRINGIFY_ARRAY_ITEMS) {\n items.push(`… ${value.length - MAX_STRINGIFY_ARRAY_ITEMS} more items`)\n }\n return items\n }\n const keys = Object.keys(value)\n const result: Record<string, any> = {}\n for (const key of keys.slice(0, MAX_STRINGIFY_OBJECT_KEYS)) {\n result[key] = truncateForStringify(value[key], depth + 1)\n }\n if (keys.length > MAX_STRINGIFY_OBJECT_KEYS) {\n result[\"…\"] = `${keys.length - MAX_STRINGIFY_OBJECT_KEYS} more keys`\n }\n return result\n}\n\nfunction safeStringify(value: any) {\n try {\n return JSON.stringify(truncateForStringify(value, 0))\n } catch (e) {\n // istanbul ignore next\n return `<Unserializable: ${e}>`\n }\n}\n\nfunction prettyPrintValue(value: any) {\n return typeof value === \"function\"\n ? `<function${value.name ? ` ${value.name}` : \"\"}>`\n : isStateTreeNode(value)\n ? `<${value}>`\n : `\\`${safeStringify(value)}\\``\n}\n\nfunction shortenPrintValue(valueInString: string) {\n return valueInString.length < 280\n ? valueInString\n : `${valueInString.substring(0, 272)}......${valueInString.substring(valueInString.length - 8)}`\n}\n\nfunction toErrorString(error: IValidationError): string {\n const { value } = error\n // every context entry carries a type: they are built by getContextForPath and\n // by typecheck's initial `[{ path: \"\", type }]`\n const type = error.context[error.context.length - 1]!.type\n const fullPath = error.context\n .map(({ path }) => path)\n .filter(path => path.length > 0)\n .join(\"/\")\n\n const pathPrefix = fullPath.length > 0 ? `at path \"/${fullPath}\" ` : ``\n\n const currentTypename = isStateTreeNode(value)\n ? `value of type ${getStateTreeNode(value).type.name}:`\n : isPrimitive(value)\n ? \"value\"\n : \"snapshot\"\n\n let expectation: string\n if (isPrimitiveType(type) || isPrimitive(value)) {\n expectation = \".\"\n } else {\n const isSnapshotCompatible =\n isStateTreeNode(value) && type.is(getStateTreeNode(value).snapshot)\n expectation = `, expected an instance of \\`${type.name}\\` or a snapshot like \\`${shortenPrintValue(\n type.describe()\n )}\\` instead.${\n isSnapshotCompatible\n ? \" (Note that a snapshot of the provided value is compatible with the targeted type)\"\n : \"\"\n }`\n }\n\n return `${pathPrefix}${currentTypename} ${shortenPrintValue(\n prettyPrintValue(value)\n )} is not assignable to type: \\`${type.name}\\`${\n error.message ? ` (${error.message})` : \"\"\n }${expectation}`\n}\n\n/**\n * @internal\n * @hidden\n * Pushes a new entry onto the context array (mutates in place for performance).\n * Returns the same context array for chaining.\n */\nexport function getContextForPath(\n context: IValidationContext,\n path: string,\n type: IAnyType\n): IValidationContext {\n context.push({ path, type })\n return context\n}\n\n/**\n * @internal\n * @hidden\n * Pops the last entry from the context array (mutates in place).\n * Must be called after validation to restore context state.\n */\nexport function popContext(context: IValidationContext): void {\n context.pop()\n}\n\n/**\n * @internal\n * @hidden\n */\nexport function typeCheckSuccess(): IValidationResult {\n return EMPTY_ARRAY\n}\n\n/**\n * @internal\n * @hidden\n */\nexport function typeCheckFailure(\n context: IValidationContext,\n value: any,\n message?: string\n): IValidationResult {\n // Clone context since it may be mutated after this error is created\n return [{ context: context.slice(), value, message }]\n}\n\n// TODO; doublecheck: typecheck should only needed to be invoked from: type.create and array / map / value.property will change\n/**\n * @internal\n * @hidden\n */\nexport function typecheckInternal<IT extends IAnyType>(\n type: IAnyType,\n value: ExtractCSTWithSTN<IT>\n): void {\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/**\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 */\nexport function typecheck<IT extends IAnyType>(\n type: IT,\n value: ExtractCSTWithSTN<IT>\n): void {\n const errors = type.validate(value, [{ path: \"\", type }])\n\n if (errors.length > 0) {\n throw fail(validationErrorsToString(type, value, errors))\n }\n}\n\nconst MAX_ERRORS_REPORTED = 10\n\n/**\n * @internal\n * @hidden\n * Format a list of validation errors as bullet-style lines, capped at\n * MAX_ERRORS_REPORTED entries with an overflow suffix. Shared by typecheck()\n * and union's `noMatchMessage` so prod-build union failures can include\n * candidate validation errors using the same formatting.\n */\nexport function formatValidationErrorLines(\n errors: ReadonlyArray<IValidationError>\n): string[] {\n const shown = errors.slice(0, MAX_ERRORS_REPORTED).map(toErrorString)\n const overflow = errors.length - shown.length\n if (overflow > 0) {\n shown.push(`(… and ${overflow} more error${overflow === 1 ? \"\" : \"s\"})`)\n }\n return shown\n}\n\nfunction validationErrorsToString<IT extends IAnyType>(\n type: IT,\n value: ExtractCSTWithSTN<IT>,\n errors: ReadonlyArray<IValidationError>\n): string | undefined {\n if (errors.length === 0) {\n return undefined\n }\n return `Error while converting ${shortenPrintValue(prettyPrintValue(value))} to \\`${\n type.name\n }\\`:\\n\\n ${formatValidationErrorLines(errors).join(\"\\n \")}`\n}\n","import { type IObservableArray, entries, observable, values } from \"mobx\"\n\nimport {\n type AnyObjectNode,\n type IAnyComplexType,\n type ObjectNode,\n fail,\n mobxShallow\n} from \"../../internal.ts\"\n\nlet identifierCacheId = 0\n\n/**\n * @internal\n * @hidden\n */\nexport class IdentifierCache {\n private cacheId = identifierCacheId++\n\n // n.b. in cache all identifiers are normalized to strings\n private cache = observable.map<string, IObservableArray<AnyObjectNode>>()\n\n // last time the cache (array) for a given time changed\n // n.b. it is not really the time, but just an integer that gets increased after each modification to the array\n private lastCacheModificationPerId = observable.map<string, number>()\n\n private updateLastCacheModificationPerId(identifier: string) {\n const lcm = this.lastCacheModificationPerId.get(identifier)\n // we start at 1 since 0 means no update since cache creation\n this.lastCacheModificationPerId.set(\n identifier,\n lcm === undefined ? 1 : lcm + 1\n )\n }\n\n getLastCacheModificationPerId(identifier: string): string {\n const modificationId = this.lastCacheModificationPerId.get(identifier) || 0\n return `${this.cacheId}-${modificationId}`\n }\n\n addNodeToCache(node: AnyObjectNode, lastCacheUpdate = true): void {\n if (node.identifierAttribute) {\n const identifier = node.identifier!\n // one observable-map read, not a has() plus a get(): this runs for every\n // identified node created\n let set = this.cache.get(identifier)\n if (!set) {\n set = observable.array<AnyObjectNode>([], mobxShallow)\n this.cache.set(identifier, set)\n }\n if (set.includes(node)) {\n throw fail(`Already registered`)\n }\n set.push(node)\n if (lastCacheUpdate) {\n this.updateLastCacheModificationPerId(identifier)\n }\n }\n }\n\n mergeCache(node: AnyObjectNode) {\n values(node.identifierCache!.cache).forEach(nodes =>\n nodes.forEach(child => {\n this.addNodeToCache(child)\n })\n )\n }\n\n notifyDied(node: AnyObjectNode) {\n if (node.identifierAttribute) {\n const id = node.identifier!\n const set = this.cache.get(id)\n if (set) {\n set.remove(node)\n // remove empty sets from cache\n if (!set.length) {\n this.cache.delete(id)\n }\n this.updateLastCacheModificationPerId(id)\n }\n }\n }\n\n splitCache(splitNode: AnyObjectNode): IdentifierCache {\n const newCache = new IdentifierCache()\n // The slash is added here so we only match children of the splitNode. In version 5.1.8 and\n // earlier there was no trailing slash, so non children that started with the same path string\n // were being matched incorrectly.\n const basePath = `${splitNode.path}/`\n entries(this.cache).forEach(([id, nodes]) => {\n let modified = false\n for (let i = nodes.length - 1; i >= 0; i--) {\n const node = nodes[i]!\n if (node === splitNode || node.path.startsWith(basePath)) {\n newCache.addNodeToCache(node, false) // no need to update lastUpdated since it is a whole new cache\n nodes.splice(i, 1)\n // remove empty sets from cache\n if (!nodes.length) {\n this.cache.delete(id)\n }\n modified = true\n }\n }\n if (modified) {\n this.updateLastCacheModificationPerId(id)\n }\n })\n return newCache\n }\n\n has(type: IAnyComplexType, identifier: string): boolean {\n const set = this.cache.get(identifier)\n if (!set) {\n return false\n }\n return set.some(candidate => type.isAssignableFrom(candidate.type))\n }\n\n resolve<IT extends IAnyComplexType>(\n type: IT,\n identifier: string\n ): ObjectNode<\n IT[\"CreationType\"],\n IT[\"SnapshotType\"],\n IT[\"TypeWithoutSTN\"]\n > | null {\n const set = this.cache.get(identifier)\n if (!set) {\n return null\n }\n const matches = set.filter(candidate =>\n type.isAssignableFrom(candidate.type)\n )\n switch (matches.length) {\n case 0:\n return null\n case 1:\n return matches[0]!\n default:\n throw fail(\n `Cannot resolve a reference to type '${\n type.name\n }' with id: '${identifier}' unambigously, there are multiple candidates: ${matches\n .map(n => n.path)\n .join(\", \")}`\n )\n }\n }\n}\n","import {\n type AnyNode,\n type AnyObjectNode,\n BaseNode,\n type ComplexType,\n ObjectNode,\n ScalarNode,\n type SimpleType,\n fail,\n getStateTreeNodeSafe\n} from \"../../internal.ts\"\n\n/**\n * @internal\n * @hidden\n */\nexport function createObjectNode<C, S, T>(\n type: ComplexType<C, S, T>,\n parent: AnyObjectNode | null,\n subpath: string,\n environment: any,\n initialValue: C | T\n): ObjectNode<C, S, T> {\n const existingNode = getStateTreeNodeSafe(initialValue)\n if (existingNode) {\n if (existingNode.parent) {\n // istanbul ignore next\n throw fail(\n `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 '${\n parent ? parent.path : \"\"\n }/${subpath}', but it lives already at '${existingNode.path}'`\n )\n }\n\n if (parent) {\n existingNode.setParent(parent, subpath)\n }\n // else it already has no parent since it is a pre-requisite\n\n return existingNode\n }\n\n // not a node, a snapshot\n return new ObjectNode(type, parent, subpath, environment, initialValue as C)\n}\n\n/**\n * @internal\n * @hidden\n */\nexport function createScalarNode<C, S, T>(\n type: SimpleType<C, S, T>,\n parent: AnyObjectNode | null,\n subpath: string,\n environment: any,\n initialValue: C\n): ScalarNode<C, S, T> {\n return new ScalarNode(type, parent, subpath, environment, initialValue)\n}\n\n/**\n * @internal\n * @hidden\n */\nexport function isNode(value: unknown): value is AnyNode {\n return value instanceof BaseNode\n}\n","import {\n EMPTY_ARRAY,\n ObjectNode,\n ScalarNode,\n assertArg,\n fail,\n joinJsonPath,\n splitJsonPath\n} from \"../../internal.ts\"\n\nimport type {\n AnyNode,\n AnyObjectNode,\n IAnyComplexType,\n IAnyType,\n IChildNodesMap,\n IType,\n Instance,\n STNValue\n} from \"../../internal.ts\"\n\n/**\n * @internal\n * @hidden\n */\nexport enum NodeLifeCycle {\n INITIALIZING, // setting up\n CREATED, // afterCreate has run\n FINALIZED, // afterAttach has run\n DETACHING, // being detached from the tree\n DEAD // no coming back from this one\n}\n\n/**\n * Common interface that represents a node instance.\n * @hidden\n */\nexport interface IStateTreeNode<IT extends IAnyType = IAnyType> {\n /**\n * @internal\n */\n readonly $treenode?: any\n\n // Phantom property — never present at runtime, exists only so TypeScript can infer IT\n // via `T extends IStateTreeNode<infer IT>`. The [IT] | [any] tuple forces inference on\n // the concrete type while still allowing widening to IAnyType. A string key is used\n // instead of a unique symbol so tsgo can name the type in declaration files (TS4058).\n readonly $__mstStateTreeNodeType__?: [IT] | [any]\n}\n\n/** @hidden */\nexport type TypeOfValue<T extends IAnyStateTreeNode> =\n T extends IStateTreeNode<infer IT> ? IT : never\n\n/**\n * Represents any state tree node instance.\n * @hidden\n */\nexport interface IAnyStateTreeNode extends STNValue<any, IAnyType> {}\n\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 */\nexport function isStateTreeNode<IT extends IAnyComplexType = IAnyComplexType>(\n value: unknown\n): value is STNValue<Instance<IT>, IT> {\n return !!(value as IStateTreeNode | null | undefined)?.$treenode\n}\n\n/**\n * @internal\n * @hidden\n */\nexport function assertIsStateTreeNode(\n value: IAnyStateTreeNode,\n argNumber: number | number[]\n): void {\n assertArg(value, isStateTreeNode, \"mobx-state-tree node\", argNumber)\n}\n\n/**\n * @internal\n * @hidden\n */\nexport function getStateTreeNode(value: IAnyStateTreeNode): AnyObjectNode {\n if (!isStateTreeNode(value)) {\n // istanbul ignore next\n throw fail(`Value ${value} is no MST Node`)\n }\n return value.$treenode!\n}\n\n/**\n * @internal\n * @hidden\n */\nexport function getStateTreeNodeSafe(\n value: IAnyStateTreeNode\n): AnyObjectNode | null {\n return value?.[\"$treenode\"] || null\n}\n\n/**\n * @internal\n * @hidden\n */\nexport function toJSON<S>(this: IStateTreeNode<IType<any, S, any>>): S {\n return getStateTreeNode(this).snapshot\n}\n\nconst doubleDot = (_: any) => \"..\"\n\n/**\n * @internal\n * @hidden\n */\nexport function getRelativePathBetweenNodes(\n base: AnyObjectNode,\n target: AnyObjectNode\n): string {\n // PRE condition target is (a child of) base!\n if (base.root !== target.root) {\n throw fail(\n `Cannot calculate relative path: objects '${base}' and '${target}' are not part of the same object tree`\n )\n }\n\n const baseParts = splitJsonPath(base.path)\n const targetParts = splitJsonPath(target.path)\n let common = 0\n for (; common < baseParts.length; common++) {\n if (baseParts[common] !== targetParts[common]) {\n break\n }\n }\n // TODO: assert that no targetParts paths are \"..\", \".\" or \"\"!\n return (\n baseParts.slice(common).map(doubleDot).join(\"/\") +\n joinJsonPath(targetParts.slice(common))\n )\n}\n\n/**\n * @internal\n * @hidden\n */\nexport function resolveNodeByPath(\n base: AnyObjectNode,\n path: string,\n failIfResolveFails = true\n): AnyNode | undefined {\n return resolveNodeByPathParts(base, splitJsonPath(path), failIfResolveFails)\n}\n\n/**\n * @internal\n * @hidden\n */\nexport function resolveNodeByPathParts(\n base: AnyObjectNode,\n pathParts: string[],\n failIfResolveFails = true\n): AnyNode | undefined {\n let current: AnyNode | null = base\n try {\n for (let i = 0; i < pathParts.length; i++) {\n const part = pathParts[i]!\n if (part === \"..\") {\n current = current.parent\n if (current) {\n continue\n } // 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 const value: any = current.value\n if (isStateTreeNode(value)) {\n current = getStateTreeNode(value)\n // fall through\n }\n }\n if (current instanceof ObjectNode) {\n const subType = current.getChildType(part)\n if (subType) {\n current = current.getChildNode(part)\n if (current) {\n continue\n }\n }\n }\n }\n throw fail(\n `Could not resolve '${part}' in path '${\n joinJsonPath(pathParts.slice(0, i)) || \"/\"\n }' while resolving '${joinJsonPath(pathParts)}'`\n )\n }\n } catch (e) {\n if (!failIfResolveFails) {\n return undefined\n }\n throw e\n }\n return current\n}\n\n/**\n * @internal\n * @hidden\n */\nexport function convertChildNodesToArray(\n childNodes: IChildNodesMap | null\n): ReadonlyArray<AnyNode> {\n if (!childNodes) {\n return EMPTY_ARRAY\n }\n\n const result = Object.values(childNodes)\n return result.length ? result : EMPTY_ARRAY\n}\n","import {\n defineProperty as mobxDefineProperty,\n isObservableArray,\n isObservableObject\n} from \"mobx\"\n\nimport type { Primitives } from \"./core/type/type.ts\"\n\nconst plainObjectString = Object.toString()\n\n/**\n * @internal\n * @hidden\n */\nexport const EMPTY_ARRAY: readonly never[] = Object.freeze([])\n\n/**\n * @internal\n * @hidden\n */\n\nexport const EMPTY_OBJECT: {} = Object.freeze({})\n\n/**\n * @internal\n * @hidden\n */\nexport const mobxShallow = { deep: false } as const\nObject.freeze(mobxShallow)\n\n/**\n * A generic disposer.\n */\nexport type IDisposer = () => void\n\n/**\n * @internal\n * @hidden\n */\nexport function fail(message = \"Illegal state\"): Error {\n return new Error(`[mobx-state-tree] ${message}`)\n}\n\n/**\n * @internal\n * @hidden\n */\nexport function identity(_: any): any {\n return _\n}\n\n/**\n * @internal\n * @hidden\n */\nexport function isArray(val: unknown): val is any[] {\n return Array.isArray(val) || isObservableArray(val)\n}\n\n/**\n * @internal\n * @hidden\n */\nexport function asArray<T>(\n val: undefined | null | T | T[] | ReadonlyArray<T>\n): ReadonlyArray<T> {\n if (!val) {\n return EMPTY_ARRAY\n }\n if (isArray(val)) {\n return val\n }\n return [val] as T[]\n}\n\n/**\n * @internal\n * @hidden\n */\nexport function isPlainObject(value: unknown): value is { [k: string]: any } {\n if (value === null || typeof value !== \"object\") {\n return false\n }\n const proto = Object.getPrototypeOf(value)\n // Fast path for an object literal from this realm — nearly every snapshot MST\n // inspects. The fallback compares the constructor's *source text* so that an\n // `Object` from another realm (iframe, vm context) still counts as plain; it\n // is ~6x slower, so only cross-realm and null-prototype values pay for it.\n if (proto === Object.prototype || proto == null) {\n return true\n }\n return proto.constructor?.toString() === plainObjectString\n}\n\n/**\n * @internal\n * @hidden\n */\nexport function isMutable(value: unknown) {\n return (\n value !== null &&\n typeof value === \"object\" &&\n !(value instanceof Date) &&\n !(value instanceof RegExp)\n )\n}\n\n/**\n * @internal\n * @hidden\n */\nexport function isPrimitive(\n value: unknown,\n includeDate = true\n): value is Primitives {\n return (\n value === null ||\n value === undefined ||\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"boolean\" ||\n (includeDate && value instanceof Date)\n )\n}\n\n/**\n * @internal\n * @hidden\n * Freeze a value and return it (if not in production)\n */\nexport function freeze<T>(value: T): T {\n if (!devMode()) {\n return value\n }\n return isPrimitive(value) || isObservableArray(value)\n ? value\n : Object.freeze(value)\n}\n\n/**\n * @internal\n * @hidden\n * Recursively freeze a value (if not in production)\n */\nexport function deepFreeze<T>(value: T): T {\n if (devMode()) {\n freeze(value)\n if (isPlainObject(value)) {\n for (const v of Object.values(value)) {\n if (!isPrimitive(v) && !Object.isFrozen(v)) {\n deepFreeze(v)\n }\n }\n }\n }\n return value\n}\n\n/**\n * @internal\n * @hidden\n */\nexport function isSerializable(value: any) {\n return typeof value !== \"function\"\n}\n\n/**\n * @internal\n * @hidden\n */\nexport function defineProperty(\n object: any,\n key: PropertyKey,\n descriptor: PropertyDescriptor\n) {\n if (isObservableObject(object)) {\n mobxDefineProperty(object, key, descriptor)\n } else {\n Object.defineProperty(object, key, descriptor)\n }\n}\n\n/**\n * @internal\n * @hidden\n */\nexport function addHiddenFinalProp(object: any, propName: string, value: any) {\n defineProperty(object, propName, {\n enumerable: false,\n writable: false,\n configurable: true,\n value\n })\n}\n\n/**\n * @internal\n * @hidden\n */\nexport function addHiddenWritableProp(\n object: any,\n propName: string,\n value: any\n) {\n defineProperty(object, propName, {\n enumerable: false,\n writable: true,\n configurable: true,\n value\n })\n}\n\n/**\n * @internal\n * @hidden\n */\nclass EventHandler<F extends (...args: any[]) => any> {\n private handlers: F[] = []\n\n get hasSubscribers(): boolean {\n return this.handlers.length > 0\n }\n\n register(fn: F, atTheBeginning = false): IDisposer {\n if (atTheBeginning) {\n this.handlers.unshift(fn)\n } else {\n this.handlers.push(fn)\n }\n return () => {\n this.unregister(fn)\n }\n }\n\n has(fn: F): boolean {\n return this.handlers.includes(fn)\n }\n\n unregister(fn: F) {\n const index = this.handlers.indexOf(fn)\n if (index >= 0) {\n this.handlers.splice(index, 1)\n }\n }\n\n emit(...args: Parameters<F>) {\n const handlers = this.handlers\n // 0 and 1 handlers are by far the common cases (a patch/snapshot listener, a\n // disposer) and need no copy: with a single handler, calling the value we\n // already read is exactly what iterating a copy of it would do.\n if (handlers.length <= 1) {\n handlers[0]?.(...args)\n return\n }\n // otherwise iterate a copy so (un)registrations during emit don't disturb\n // this pass and reentrant emits stay correct\n for (const f of handlers.slice()) {\n f(...args)\n }\n }\n}\n\n/**\n * @internal\n * @hidden\n */\nexport class EventHandlers<E extends { [k: string]: (...args: any[]) => any }> {\n private eventHandlers?:\n | {\n [k in keyof E]?: EventHandler<E[k]>\n }\n | undefined\n\n hasSubscribers(event: keyof E): boolean {\n return this.eventHandlers?.[event]?.hasSubscribers ?? false\n }\n\n register<N extends keyof E>(\n event: N,\n fn: E[N],\n atTheBeginning = false\n ): IDisposer {\n if (!this.eventHandlers) {\n this.eventHandlers = {}\n }\n let handler = this.eventHandlers[event]\n if (!handler) {\n handler = this.eventHandlers[event] = new EventHandler()\n }\n return handler.register(fn, atTheBeginning)\n }\n\n has<N extends keyof E>(event: N, fn: E[N]): boolean {\n return this.eventHandlers?.[event]?.has(fn) ?? false\n }\n\n unregister<N extends keyof E>(event: N, fn: E[N]) {\n const handler = this.eventHandlers?.[event]\n if (handler) {\n handler.unregister(fn)\n }\n }\n\n clear<N extends keyof E>(event: N) {\n if (this.eventHandlers) {\n delete this.eventHandlers[event]\n }\n }\n\n clearAll() {\n this.eventHandlers = undefined\n }\n\n emit<N extends keyof E>(event: N, ...args: Parameters<E[N]>) {\n const handler = this.eventHandlers?.[event]\n if (handler) {\n handler.emit(...args)\n }\n }\n}\n\n/**\n * @internal\n * @hidden\n */\nexport function warnError(msg: string) {\n console.warn(new Error(`[mobx-state-tree] ${msg}`))\n}\nlet _typeChecking: boolean | undefined\n\n/**\n * Forces full run-time type-checking on or off, overriding the dev-mode and\n * `ENABLE_TYPE_CHECK` env-var defaults. Pass `true` to get better error messages\n * in production builds without relying on an environment variable, `false` to\n * force it off, or `undefined` to restore the default behavior.\n */\nexport function setTypeChecking(enabled: boolean | undefined) {\n _typeChecking = enabled\n}\n\n// the ENABLE_TYPE_CHECK env var is fixed at process start, so read it once:\n// process.env access is a comparatively expensive lookup and isTypeCheckingEnabled\n// runs on every create() / typed write. The setTypeChecking() override and\n// dev-mode default stay live below.\nconst _envTypeCheck =\n typeof process !== \"undefined\" && process.env?.ENABLE_TYPE_CHECK === \"true\"\n\n/**\n * @internal\n * @hidden\n */\nexport function isTypeCheckingEnabled() {\n // an explicit setTypeChecking() override (incl. `false`) wins over the\n // dev-mode / env-var default, hence ?? rather than ||\n return _typeChecking ?? (devMode() || _envTypeCheck)\n}\n\nlet _devMode = process.env.NODE_ENV !== \"production\"\n\n/**\n * @internal\n * @hidden\n */\nexport function devMode() {\n return _devMode\n}\n\n/**\n * @internal\n * @hidden\n */\nexport function setDevMode(value: boolean) {\n _devMode = value\n}\n\n/**\n * @internal\n * @hidden\n */\nexport function assertArg<T>(\n value: T,\n fn: (value: T) => boolean,\n typeName: string,\n argNumber: number | number[]\n) {\n if (devMode()) {\n if (!fn(value)) {\n // istanbul ignore next\n throw fail(\n `expected ${typeName} as argument ${asArray(argNumber).join(\" or \")}, got ${value} instead`\n )\n }\n }\n}\n\n/**\n * @internal\n * @hidden\n */\nexport function assertIsFunction(\n value: (...args: any[]) => any,\n argNumber: number | number[]\n) {\n assertArg(value, fn => typeof fn === \"function\", \"function\", argNumber)\n}\n\n/**\n * @internal\n * @hidden\n */\nexport function assertIsNumber(\n value: number,\n argNumber: number | number[],\n min?: number,\n max?: number\n) {\n assertArg(value, n => typeof n === \"number\", \"number\", argNumber)\n if (min !== undefined) {\n assertArg(value, n => n >= min, `number greater than ${min}`, argNumber)\n }\n if (max !== undefined) {\n assertArg(value, n => n <= max, `number lesser than ${max}`, argNumber)\n }\n}\n\n/**\n * @internal\n * @hidden\n */\nexport function assertIsString(\n value: string,\n argNumber: number | number[],\n canBeEmpty = true\n) {\n assertArg(value, s => typeof s === \"string\", \"string\", argNumber)\n if (!canBeEmpty) {\n assertArg(value, s => s !== \"\", \"not empty string\", argNumber)\n }\n}\n","import { fail } from \"../utils.ts\"\nimport {\n getCurrentActionContext,\n getNextActionId,\n getParentActionContext,\n runWithActionContext\n} from \"./action.ts\"\n\nimport type { FunctionWithFlag, IMiddlewareEventType } from \"./action.ts\"\n\n/**\n * @hidden\n */\nexport type FlowReturn<R> = R extends Promise<infer T> ? T : R\n\n/**\n * See [asynchronous actions](concepts/async-actions.md).\n *\n * @returns The flow as a promise.\n */\nexport function flow<R, Args extends any[]>(\n generator: (...args: Args) => Generator<PromiseLike<any>, R, any>\n): (...args: Args) => Promise<FlowReturn<R>> {\n return createFlowSpawner(generator.name, generator) as any\n}\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 */\nexport function castFlowReturn<T>(val: T): T {\n return val\n}\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<number> { ... }\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 */\nexport function toGeneratorFunction<R, Args extends any[]>(\n p: (...args: Args) => Promise<R>\n) {\n return function* (...args: Args) {\n return (yield p(...args)) as R\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<number> { ... }\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 */\nexport function* toGenerator<R>(p: Promise<R>) {\n return (yield p) as R\n}\n\nfunction createFlowSpawner(name: string, generator: FunctionWithFlag) {\n const spawner = function flowSpawner(this: any, ...flowArgs: any[]) {\n // Implementation based on https://github.com/tj/co/blob/master/index.js\n const runId = getNextActionId()\n // no `!`: the guard below is the point, and asserting non-null first made it\n // dead to the checker while leaving it live at runtime\n const parentContext = getCurrentActionContext()\n if (!parentContext) {\n throw fail(\"a mst flow must always have a parent context\")\n }\n const parentActionContext = getParentActionContext(parentContext)\n if (!parentActionContext) {\n throw fail(\"a mst flow must always have a parent action context\")\n }\n\n const contextBase = {\n name,\n id: runId,\n tree: parentContext.tree,\n context: parentContext.context,\n parentId: parentContext.id,\n allParentIds: [...parentContext.allParentIds, parentContext.id],\n rootId: parentContext.rootId,\n parentEvent: parentContext,\n parentActionEvent: parentActionContext\n }\n\n const spawnerWithMw = spawner as FunctionWithFlag\n\n function wrap(fn: FunctionWithFlag, type: IMiddlewareEventType, arg: any) {\n fn.$mst_middleware = spawnerWithMw.$mst_middleware // pick up any middleware attached to the flow\n return runWithActionContext(\n {\n ...contextBase,\n type,\n args: [arg]\n },\n fn\n )\n }\n\n return new Promise(function (resolve, reject) {\n let gen: Generator<PromiseLike<unknown>, unknown, unknown>\n const init = function asyncActionInit(...initArgs: any[]) {\n gen = generator(...initArgs)\n onFulfilled(undefined) // kick off the flow\n } as FunctionWithFlag\n init.$mst_middleware = spawnerWithMw.$mst_middleware\n\n runWithActionContext(\n {\n ...contextBase,\n type: \"flow_spawn\",\n args: flowArgs\n },\n init\n )\n\n function onFulfilled(res: any) {\n let ret\n try {\n // prettier-ignore\n const cancelError: any = wrap((_r: any) => { ret = gen.next(_r) }, \"flow_resume\", res)\n if (cancelError instanceof Error) {\n ret = gen.throw(cancelError)\n }\n } catch (e) {\n // prettier-ignore\n queueMicrotask(() => {\n wrap((_r: any) => { reject(e) }, \"flow_throw\", e)\n })\n return\n }\n next(ret)\n return\n }\n\n function onRejected(err: any) {\n let ret\n try {\n // prettier-ignore\n wrap((_r: any) => { ret = gen.throw(_r) }, \"flow_resume_error\", err) // or yieldError?\n } catch (e) {\n // prettier-ignore\n queueMicrotask(() => {\n wrap((_r: any) => { reject(e) }, \"flow_throw\", e)\n })\n return\n }\n next(ret)\n }\n\n function next(ret: any) {\n if (ret.done) {\n // prettier-ignore\n queueMicrotask(() => {\n wrap((r: any) => { resolve(r) }, \"flow_return\", ret.value)\n })\n return\n }\n // TODO: support more type of values? See https://github.com/tj/co/blob/249bbdc72da24ae44076afd716349d2089b31c4c/index.js#L100\n if (!ret.value || typeof ret.value.then !== \"function\") {\n // istanbul ignore next\n throw fail(`Only promises can be yielded to \\`async\\`, got: ${ret}`)\n }\n return ret.value.then(onFulfilled, onRejected)\n }\n })\n }\n ;(spawner as FunctionWithFlag)._isFlowAction = true\n return spawner\n}\n","import { fail } from \"../internal.ts\"\n\n/**\n * https://tools.ietf.org/html/rfc6902\n * http://jsonpatch.com/\n */\nexport interface IJsonPatch {\n readonly op: \"replace\" | \"add\" | \"remove\"\n readonly path: string\n readonly value?: any\n}\n\nexport interface IReversibleJsonPatch extends IJsonPatch {\n readonly oldValue: any // This goes beyond JSON-patch, but makes sure each patch can be inverse applied\n}\n\n/**\n * @internal\n * @hidden\n */\nexport function splitPatch(\n patch: IReversibleJsonPatch\n): [IJsonPatch, IJsonPatch] {\n if (!(\"oldValue\" in patch)) {\n throw fail(`Patches without \\`oldValue\\` field cannot be inversed`)\n }\n return [stripPatch(patch), invertPatch(patch)]\n}\n\nfunction stripPatch(patch: IReversibleJsonPatch): IJsonPatch {\n // strips `oldvalue` information from the patch, so that it becomes a patch conform the json-patch spec\n // this removes the ability to undo the patch\n switch (patch.op) {\n case \"add\":\n return { op: \"add\", path: patch.path, value: patch.value }\n case \"remove\":\n return { op: \"remove\", path: patch.path }\n case \"replace\":\n return { op: \"replace\", path: patch.path, value: patch.value }\n }\n}\n\nfunction invertPatch(patch: IReversibleJsonPatch): IJsonPatch {\n switch (patch.op) {\n case \"add\":\n return {\n op: \"remove\",\n path: patch.path\n }\n case \"remove\":\n return {\n op: \"add\",\n path: patch.path,\n value: patch.oldValue\n }\n case \"replace\":\n return {\n op: \"replace\",\n path: patch.path,\n value: patch.oldValue\n }\n }\n}\n\n/**\n * Escape slashes and backslashes.\n *\n * http://tools.ietf.org/html/rfc6901\n */\nexport function escapeJsonPath(path: string): string {\n if (!path.includes(\"/\") && !path.includes(\"~\")) {\n return path\n }\n return path.replace(/~/g, \"~0\").replace(/\\//g, \"~1\")\n}\n\n/**\n * Unescape slashes and backslashes.\n */\nexport function unescapeJsonPath(path: string): string {\n // every escape sequence starts with `~`, so bail before the two regex passes\n // for the overwhelmingly common unescaped part (mirrors escapeJsonPath above)\n if (!path.includes(\"~\")) {\n return path\n }\n return path.replace(/~1/g, \"/\").replace(/~0/g, \"~\")\n}\n\n/**\n * Generates a json-path compliant json path from path parts.\n *\n * @param path\n * @returns\n */\nexport function joinJsonPath(path: string[]): string {\n // `/` refers to property with an empty name, while `` refers to root itself!\n if (path.length === 0) {\n return \"\"\n }\n\n const getPathStr = (p: string[]) => p.map(escapeJsonPath).join(\"/\")\n if (path[0] === \".\" || path[0] === \"..\") {\n // relative\n return getPathStr(path)\n } else {\n // absolute\n return `/${getPathStr(path)}`\n }\n}\n\n/**\n * Splits and decodes a json path into several parts.\n *\n * @param path\n * @returns\n */\nexport function splitJsonPath(path: string): string[] {\n // `/` refers to property with an empty name, while `` refers to root itself!\n const parts = path.split(\"/\").map(unescapeJsonPath)\n\n const valid =\n path === \"\" ||\n path === \".\" ||\n path === \"..\" ||\n path.startsWith(\"/\") ||\n path.startsWith(\"./\") ||\n path.startsWith(\"../\")\n if (!valid) {\n throw fail(\n `a json path must be either rooted, empty or relative, but got '${path}'`\n )\n }\n\n // '/a/b/c' -> [\"a\", \"b\", \"c\"]\n // '../../b/c' -> [\"..\", \"..\", \"b\", \"c\"]\n // '' -> []\n // '/' -> ['']\n // './a' -> [\".\", \"a\"]\n // /./a' -> [\".\", \"a\"] equivalent to './a'\n\n if (parts[0] === \"\") {\n parts.shift()\n }\n return parts\n}\n","import {\n type AnyObjectNode,\n BaseType,\n ComplexType,\n type ExtractNodeType,\n type IAnyType,\n type Instance,\n type IType,\n type IValidationContext,\n type IValidationResult,\n ObjectNode,\n TypeFlags,\n assertIsType,\n devMode,\n fail,\n getSnapshot,\n isStateTreeNode,\n isType,\n isUnionType,\n typeCheckFailure\n} from \"../../internal.ts\"\n\n/** @hidden */\ndeclare const $mstNotCustomized: unique symbol\n\n/** @hidden */\nconst $preProcessorFailed: unique symbol = Symbol(\"$preProcessorFailed\")\n\n/** @hidden */\nexport interface _NotCustomized {\n // only for typings\n readonly [$mstNotCustomized]: undefined\n}\n/** @hidden */\nexport type _CustomOrOther<Custom, Other> = Custom extends _NotCustomized\n ? Other\n : Custom\n\nclass SnapshotProcessor<IT extends IAnyType, CustomC, CustomS> extends BaseType<\n _CustomOrOther<CustomC, IT[\"CreationType\"]>,\n _CustomOrOther<CustomS, IT[\"SnapshotType\"]>,\n IT[\"TypeWithoutSTN\"],\n ExtractNodeType<IT>\n> {\n private _flags?: TypeFlags\n\n // memoized once stable; see the guard on Union.flags\n get flags(): TypeFlags {\n const cached = this._flags\n if (cached !== undefined) {\n return cached\n }\n const result = this._subtype.flags | TypeFlags.SnapshotProcessor\n if (!(result & TypeFlags.Late)) {\n this._flags = result\n }\n return result\n }\n\n constructor(\n private readonly _subtype: IT,\n private readonly _processors: ISnapshotProcessors<IT, CustomC, CustomS>,\n name?: string\n ) {\n // `|| undefined`, so an empty name still falls through to the subtype's, as\n // it did when this read `name || _subtype.name`. Passing `\"\"` straight to\n // `super` would keep it: `_name ??= computeName()` only fills a nullish one.\n super(name || undefined)\n }\n\n protected override computeName(): string {\n return this._subtype.name\n }\n\n override describe() {\n return `snapshotProcessor(${this._subtype.describe()})`\n }\n\n private preProcessSnapshot(sn: this[\"C\"]): IT[\"CreationType\"] {\n if (this._processors.preProcessor) {\n return this._processors.preProcessor.call(null, sn)\n }\n return sn\n }\n\n private preProcessSnapshotSafe(\n sn: this[\"C\"]\n ): IT[\"CreationType\"] | typeof $preProcessorFailed {\n try {\n return this.preProcessSnapshot(sn)\n } catch (_e) {\n return $preProcessorFailed\n }\n }\n\n private postProcessSnapshot(\n sn: IT[\"SnapshotType\"],\n node: this[\"N\"]\n ): this[\"S\"] {\n if (this._processors.postProcessor) {\n return this._processors.postProcessor.call(\n null,\n sn,\n node.storedValue\n ) as any\n }\n return sn\n }\n\n private _fixNode(node: this[\"N\"]): void {\n if (node instanceof ObjectNode) {\n node.snapshotProcessorType = this\n node.hasSnapshotPostProcessor = !!this._processors.postProcessor\n }\n const oldGetSnapshot = node.getSnapshot\n node.getSnapshot = () =>\n this.postProcessSnapshot(oldGetSnapshot.call(node), node) as any\n // getSnapshot was just rewritten; refresh any snapshot already memoized for\n // this node (e.g. it was serialized before being moved under this processor)\n if (node instanceof ObjectNode) {\n node.refreshMemoizedSnapshot()\n }\n if (!isUnionType(this._subtype)) {\n node.getReconciliationType = () => {\n return this\n }\n }\n }\n\n instantiate(\n parent: AnyObjectNode | null,\n subpath: string,\n environment: any,\n initialValue: this[\"C\"] | this[\"T\"]\n ): this[\"N\"] {\n const processedInitialValue = isStateTreeNode(initialValue)\n ? initialValue\n : this.preProcessSnapshot(initialValue)\n const node = this._subtype.instantiate(\n parent,\n subpath,\n environment,\n processedInitialValue\n ) as any\n this._fixNode(node)\n return node\n }\n\n reconcile(\n current: this[\"N\"],\n newValue: this[\"C\"] | this[\"T\"],\n parent: AnyObjectNode,\n subpath: string\n ): this[\"N\"] {\n const node = this._subtype.reconcile(\n current,\n isStateTreeNode(newValue) ? newValue : this.preProcessSnapshot(newValue),\n parent,\n subpath\n ) as any\n if (node !== current) {\n this._fixNode(node)\n }\n return node\n }\n\n override getSnapshot(node: this[\"N\"], applyPostProcess = true): this[\"S\"] {\n const sn = this._subtype.getSnapshot(node)\n return applyPostProcess ? this.postProcessSnapshot(sn, node) : sn\n }\n\n isValidSnapshot(\n value: this[\"C\"],\n context: IValidationContext\n ): IValidationResult {\n const processedSn = this.preProcessSnapshotSafe(value)\n if (processedSn === $preProcessorFailed) {\n return typeCheckFailure(context, value, \"Failed to preprocess value\")\n }\n return this._subtype.validate(processedSn, context)\n }\n\n getSubTypes() {\n return this._subtype\n }\n\n override is(thing: unknown): thing is any {\n const value = isType(thing)\n ? this._subtype\n : isStateTreeNode(thing)\n ? getSnapshot(thing, false)\n : this.preProcessSnapshotSafe(thing as this[\"C\"])\n if (value === $preProcessorFailed) {\n return false\n }\n return (\n this._subtype.validate(value, [{ path: \"\", type: this._subtype }])\n .length === 0\n )\n }\n\n override isAssignableFrom(type: IAnyType): boolean {\n return this._subtype.isAssignableFrom(type)\n }\n\n isMatchingSnapshotId(current: this[\"N\"], snapshot: this[\"C\"]): boolean {\n if (!(this._subtype instanceof ComplexType)) {\n return false\n }\n const processedSn = this.preProcessSnapshot(snapshot)\n return this._subtype.isMatchingSnapshotId(current as any, processedSn)\n }\n}\n\n// public API\n\n/**\n * A type that has its snapshots processed.\n */\nexport interface ISnapshotProcessor<\n IT extends IAnyType,\n CustomC,\n CustomS\n> extends IType<\n _CustomOrOther<CustomC, IT[\"CreationType\"]>,\n _CustomOrOther<CustomS, IT[\"SnapshotType\"]>,\n IT[\"TypeWithoutSTN\"]\n> {}\n\n/**\n * Snapshot processors.\n */\nexport interface ISnapshotProcessors<IT extends IAnyType, CustomC, CustomS> {\n /**\n * Function that transforms an input snapshot.\n *\n * The processor may return the loose input (`CustomC`) as well as the strict\n * creation type: migrations commonly massage an untyped legacy record and\n * rely on MST's runtime revalidation/defaults to fill the rest. This mirrors\n * the lenient return type of `IModelType.preProcessSnapshot`.\n */\n preProcessor?(snapshot: CustomC): IT[\"CreationType\"] | CustomC\n /**\n * Function that transforms an output snapshot.\n * @param snapshot\n */\n postProcessor?(snapshot: IT[\"SnapshotType\"], node: Instance<IT>): CustomS\n}\n\n/**\n * `types.snapshotProcessor` - Runs a pre/post snapshot processor before/after serializing a given type.\n *\n * Example:\n * ```ts\n * const Todo1 = types.model({ text: types.string })\n * // in the backend the text type must be null when empty\n * interface BackendTodo {\n * text: string | null\n * }\n *\n * const Todo2 = types.snapshotProcessor(Todo1, {\n * // from snapshot to instance\n * preProcessor(snapshot: BackendTodo) {\n * return {\n * text: sn.text || \"\";\n * }\n * },\n *\n * // from instance to snapshot\n * postProcessor(snapshot, node): BackendTodo {\n * return {\n * text: !sn.text ? null : sn.text\n * }\n * }\n * })\n * ```\n *\n * @param type Type to run the processors over.\n * @param processors Processors to run.\n * @param name Type name, or undefined to inherit the inner type one.\n * @returns\n */\nexport function snapshotProcessor<\n IT extends IAnyType,\n CustomC = _NotCustomized,\n CustomS = _NotCustomized\n>(\n type: IT,\n processors: ISnapshotProcessors<IT, CustomC, CustomS>,\n name?: string\n): ISnapshotProcessor<IT, CustomC, CustomS> {\n assertIsType(type, 1)\n if (devMode()) {\n if (\n processors.postProcessor &&\n typeof processors.postProcessor !== \"function\"\n ) {\n // istanbul ignore next\n throw fail(\"postSnapshotProcessor must be a function\")\n }\n if (\n processors.preProcessor &&\n typeof processors.preProcessor !== \"function\"\n ) {\n // istanbul ignore next\n throw fail(\"preSnapshotProcessor must be a function\")\n }\n }\n\n return new SnapshotProcessor(type, processors, name)\n}\n","import {\n EMPTY_ARRAY,\n type IHooksGetter,\n addHiddenFinalProp,\n addHiddenWritableProp,\n createActionInvoker,\n devMode\n} from \"../../internal.ts\"\n\n/**\n * Shared backing for `types.array(...).hooks(fn)` / `types.map(...).hooks(fn)`:\n * both collection types keep a list of hook getters on the type and install the\n * returned lifecycle hooks as actions on each instance.\n *\n * @internal\n * @hidden\n */\nexport type HookInitializers<T> = ReadonlyArray<IHooksGetter<T>>\n\n/**\n * Append `hooks` to a collection type's initializer list. `EMPTY_ARRAY` is the\n * shared default, so a type that never calls `.hooks()` allocates nothing.\n *\n * @internal\n * @hidden\n */\nexport function appendHookInitializer<T>(\n current: HookInitializers<T>,\n hooks: IHooksGetter<T>\n): HookInitializers<T> {\n return current.length > 0 ? [...current, hooks] : [hooks]\n}\n\n/**\n * Install every hook the type's initializers produce onto `instance` as an MST\n * action, mirroring how a model's `.actions()` members are attached.\n *\n * @internal\n * @hidden\n */\nexport function installHookInitializers<T>(\n hookInitializers: HookInitializers<T>,\n instance: T\n): void {\n const addProp = !devMode() ? addHiddenFinalProp : addHiddenWritableProp\n for (const initializer of hookInitializers) {\n const hooks = initializer(instance)\n for (const name of Object.keys(hooks)) {\n const hook = hooks[name as keyof typeof hooks]!\n addProp(instance, name, createActionInvoker(instance, name, hook))\n }\n }\n}\n\n/**\n * The empty initializer list every collection type starts with.\n *\n * @internal\n * @hidden\n */\nexport const NO_HOOK_INITIALIZERS = EMPTY_ARRAY as HookInitializers<any>\n","import {\n type IInterceptor,\n type IKeyValueMap,\n type IMapDidChange,\n type IMapWillChange,\n type Lambda,\n ObservableMap,\n _interceptReads,\n action,\n intercept,\n observe,\n values\n} from \"mobx\"\n\nimport {\n type AnyNode,\n type AnyObjectNode,\n ComplexType,\n EMPTY_OBJECT,\n type ExtractCSTWithSTN,\n type HookInitializers,\n type IAnyModelType,\n type IAnyStateTreeNode,\n type IAnyType,\n type IChildNodesMap,\n type IHooksGetter,\n type IJsonPatch,\n type IType,\n type IValidationContext,\n type IValidationResult,\n ModelType,\n NO_HOOK_INITIALIZERS,\n ObjectNode,\n TypeFlags,\n appendHookInitializer,\n asArray,\n assertIsType,\n cannotDetermineSubtype,\n createObjectNode,\n devMode,\n escapeJsonPath,\n fail,\n getContextForPath,\n getSnapshot,\n getStateTreeNode,\n installHookInitializers,\n isMutable,\n isPlainObject,\n isStateTreeNode,\n isType,\n unwrapType,\n isValidIdentifier,\n normalizeIdentifier,\n popContext,\n typeCheckFailure,\n typeCheckSuccess,\n typecheckInternal\n} from \"../../internal.ts\"\n\n/** @hidden */\nexport interface IMapType<IT extends IAnyType> extends IType<\n IKeyValueMap<IT[\"CreationType\"]> | undefined,\n IKeyValueMap<IT[\"SnapshotType\"]>,\n IMSTMap<IT>\n> {\n hooks(hooks: IHooksGetter<IMSTMap<IT>>): IMapType<IT>\n /** the value type of the map */\n getChildType(): IAnyType\n}\n\n/**\n * The forms `merge` and `replace` accept, mirroring mobx's\n * `IObservableMapInitialValues` with MST's snapshot-or-instance value type.\n */\ntype IMSTMapInitialValues<IT extends IAnyType> =\n | IMSTMap<IType<any, any, IT[\"TypeWithoutSTN\"]>>\n | IKeyValueMap<ExtractCSTWithSTN<IT>>\n | Map<string | number, ExtractCSTWithSTN<IT>>\n | readonly (readonly [string | number, ExtractCSTWithSTN<IT>])[]\n\n/** @hidden */\nexport interface IMSTMap<IT extends IAnyType> {\n // bases on ObservableMap, but fine tuned to the auto snapshot conversion of MST\n\n clear(): void\n delete(key: string): boolean\n forEach(\n callbackfn: (value: IT[\"Type\"], key: string, map: this) => void,\n thisArg?: any\n ): void\n get(key: string | number): IT[\"Type\"] | undefined\n has(key: string | number): boolean\n set(key: string | number, value: ExtractCSTWithSTN<IT>): this\n readonly size: number\n put(value: ExtractCSTWithSTN<IT>): IT[\"Type\"]\n keys(): IterableIterator<string>\n values(): IterableIterator<IT[\"Type\"]>\n entries(): IterableIterator<[string, IT[\"Type\"]]>\n [Symbol.iterator](): IterableIterator<[string, IT[\"Type\"]]>\n /** Merge another object into this map, returns self. */\n merge(other?: IMSTMapInitialValues<IT>): this\n replace(values: IMSTMapInitialValues<IT>): this\n\n toJSON(): IKeyValueMap<IT[\"SnapshotType\"]>\n\n toString(): string\n [Symbol.toStringTag]: \"Map\"\n\n /**\n * Observes this object. Triggers for the events 'add', 'update' and 'delete'.\n * See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/observe\n * for callback details\n */\n observe(\n listener: (changes: IMapDidChange<string, IT[\"Type\"]>) => void,\n fireImmediately?: boolean\n ): Lambda\n intercept(handler: IInterceptor<IMapWillChange<string, IT[\"Type\"]>>): Lambda\n}\n\nconst needsIdentifierError = `Map.put can only be used to store complex values that have an identifier type attribute`\n\nfunction tryCollectModelTypes(\n type: IAnyType,\n modelTypes: Array<IAnyModelType>\n): boolean {\n const subtypes = type.getSubTypes()\n if (subtypes === cannotDetermineSubtype) {\n return false\n }\n if (subtypes) {\n const subtypesArray = asArray(subtypes)\n for (const subtype of subtypesArray) {\n if (!tryCollectModelTypes(subtype, modelTypes)) {\n return false\n }\n }\n }\n if (type instanceof ModelType) {\n modelTypes.push(type)\n }\n return true\n}\n\n/**\n * @internal\n * @hidden\n */\nexport enum MapIdentifierMode {\n UNKNOWN,\n YES,\n NO\n}\n\nclass MSTMap<IT extends IAnyType> extends ObservableMap<string, any> {\n override get(key: string): IT[\"Type\"] | undefined {\n // maybe this is over-enthousiastic? normalize numeric keys to strings\n return super.get(`${key}`)\n }\n\n override has(key: string) {\n return super.has(`${key}`)\n }\n\n override delete(key: string) {\n return super.delete(`${key}`)\n }\n\n override set(key: string, value: ExtractCSTWithSTN<IT>): this {\n return super.set(`${key}`, value)\n }\n\n put(value: ExtractCSTWithSTN<IT>): IT[\"Type\"] {\n if (!value) {\n throw fail(`Map.put cannot be used to set empty values`)\n }\n if (isStateTreeNode(value)) {\n const node = getStateTreeNode(value)\n if (devMode()) {\n if (!node.identifierAttribute) {\n throw fail(needsIdentifierError)\n }\n }\n if (node.identifier === null) {\n throw fail(needsIdentifierError)\n }\n this.set(node.identifier, value)\n return value\n } else if (!isMutable(value)) {\n throw fail(`Map.put can only be used to store complex values`)\n } else {\n const mapNode = getStateTreeNode(this)\n const mapType = mapNode.type as MapType<any>\n\n if (mapType.identifierMode !== MapIdentifierMode.YES) {\n throw fail(needsIdentifierError)\n }\n\n const idAttr = mapType.mapIdentifierAttribute!\n const id = (value as any)[idAttr]\n if (!isValidIdentifier(id)) {\n // try again but this time after creating a node for the value\n // since it might be an optional identifier\n const newNode = this.put(\n mapType.getChildType().create(value, mapNode.environment)\n )\n return this.put(getSnapshot(newNode))\n }\n const key = normalizeIdentifier(id)\n this.set(key, value)\n return this.get(key)\n }\n }\n}\n\n/**\n * @internal\n * @hidden\n */\nexport class MapType<IT extends IAnyType> extends ComplexType<\n IKeyValueMap<IT[\"CreationType\"]> | undefined,\n IKeyValueMap<IT[\"SnapshotType\"]>,\n IMSTMap<IT>\n> {\n identifierMode: MapIdentifierMode = MapIdentifierMode.UNKNOWN\n mapIdentifierAttribute: string | undefined = undefined\n readonly flags = TypeFlags.Map\n\n constructor(\n private readonly _subType: IAnyType,\n private readonly hookInitializers: HookInitializers<\n IMSTMap<IT>\n > = NO_HOOK_INITIALIZERS\n ) {\n super()\n this._determineIdentifierMode()\n }\n\n protected override computeName(): string {\n return `Map<string, ${this._subType.name}>`\n }\n\n hooks(hooks: IHooksGetter<IMSTMap<IT>>) {\n return new MapType(\n this._subType,\n appendHookInitializer(this.hookInitializers, hooks)\n )\n }\n\n instantiate(\n parent: AnyObjectNode | null,\n subpath: string,\n environment: any,\n initialValue: this[\"C\"] | this[\"T\"]\n ): this[\"N\"] {\n this._determineIdentifierMode()\n return createObjectNode(this, parent, subpath, environment, initialValue)\n }\n\n private _determineIdentifierMode() {\n if (this.identifierMode !== MapIdentifierMode.UNKNOWN) {\n return\n }\n\n const modelTypes: IAnyModelType[] = []\n if (tryCollectModelTypes(this._subType, modelTypes)) {\n const identifierAttribute: string | undefined = modelTypes.reduce(\n (current: IAnyModelType[\"identifierAttribute\"], type) => {\n if (!type.identifierAttribute) {\n return current\n }\n if (current && current !== type.identifierAttribute) {\n throw fail(\n `The objects in a map should all have the same identifier attribute, expected '${current}', but child of type '${type.name}' declared attribute '${type.identifierAttribute}' as identifier`\n )\n }\n return type.identifierAttribute\n },\n undefined as IAnyModelType[\"identifierAttribute\"]\n )\n\n if (identifierAttribute) {\n this.identifierMode = MapIdentifierMode.YES\n this.mapIdentifierAttribute = identifierAttribute\n } else {\n this.identifierMode = MapIdentifierMode.NO\n }\n }\n }\n\n initializeChildNodes(\n objNode: this[\"N\"],\n initialSnapshot: this[\"C\"] = {}\n ): IChildNodesMap {\n const subType = (objNode.type as this)._subType\n const result: IChildNodesMap = {}\n Object.keys(initialSnapshot).forEach(name => {\n result[name] = subType.instantiate(\n objNode,\n name,\n undefined,\n initialSnapshot[name]\n )\n })\n\n return result\n }\n\n createNewInstance(childNodes: IChildNodesMap): this[\"T\"] {\n // undefined is mobx's enhancer argument, left at its deep default\n return new MSTMap(childNodes, undefined, this.name) as any\n }\n\n finalizeNewInstance(\n node: this[\"N\"],\n instance: ObservableMap<string, any>\n ): void {\n _interceptReads(instance, node.unbox)\n\n installHookInitializers(\n (node.type as this).hookInitializers,\n instance as unknown as IMSTMap<IT>\n )\n\n intercept(instance, this.willChange)\n observe(instance, this.didChange)\n }\n\n getChildren(node: this[\"N\"]): ReadonlyArray<AnyNode> {\n // return (node.storedValue as ObservableMap<any>).values()\n return values(node.storedValue)\n }\n\n getChildNode(node: this[\"N\"], key: string): AnyNode {\n const childNode = node.storedValue.get(`${key}`)\n if (!childNode) {\n throw fail(`Not a child ${key}`)\n }\n return childNode\n }\n\n willChange(\n change: IMapWillChange<string, AnyNode>\n ): IMapWillChange<string, AnyNode> | null {\n const node = getStateTreeNode(change.object as IAnyStateTreeNode)\n const key = change.name\n node.assertWritable({ subpath: key })\n const mapType = node.type as this\n const subType = mapType._subType\n\n switch (change.type) {\n case \"update\":\n {\n const { newValue } = change\n const oldValue = change.object.get(key)\n if (newValue === oldValue) {\n return null\n }\n typecheckInternal(subType, newValue)\n change.newValue = subType.reconcile(\n node.getChildNode(key),\n change.newValue,\n node,\n key\n )\n mapType.processIdentifier(key, change.newValue)\n }\n break\n case \"add\":\n {\n typecheckInternal(subType, change.newValue)\n change.newValue = subType.instantiate(\n node,\n key,\n undefined,\n change.newValue\n )\n mapType.processIdentifier(key, change.newValue)\n }\n break\n }\n return change\n }\n\n private processIdentifier(expected: string, node: AnyNode): void {\n if (\n this.identifierMode === MapIdentifierMode.YES &&\n node instanceof ObjectNode\n ) {\n const identifier = node.identifier!\n if (identifier !== expected) {\n throw fail(\n `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 }\n\n override getSnapshot(node: this[\"N\"]): this[\"S\"] {\n const res: any = {}\n node.getChildren().forEach(childNode => {\n res[childNode.subpath] = childNode.snapshot\n })\n return res\n }\n\n processInitialSnapshot(childNodes: IChildNodesMap): this[\"S\"] {\n const processed: any = {}\n Object.keys(childNodes).forEach(key => {\n processed[key] = childNodes[key]!.getSnapshot()\n })\n return processed\n }\n\n didChange(change: IMapDidChange<string, AnyNode>): void {\n const node = getStateTreeNode(change.object as IAnyStateTreeNode)\n switch (change.type) {\n case \"update\":\n return void node.emitPatch(\n {\n op: \"replace\",\n path: escapeJsonPath(change.name),\n value: change.newValue.snapshot,\n oldValue: change.oldValue ? change.oldValue.snapshot : undefined\n },\n node\n )\n case \"add\":\n return void node.emitPatch(\n {\n op: \"add\",\n path: escapeJsonPath(change.name),\n value: change.newValue.snapshot,\n oldValue: undefined\n },\n node\n )\n case \"delete\":\n // a node got deleted, get the old snapshot and make the node die\n const oldSnapshot = change.oldValue.snapshot\n change.oldValue.die()\n // emit the patch\n return void node.emitPatch(\n {\n op: \"remove\",\n path: escapeJsonPath(change.name),\n oldValue: oldSnapshot\n },\n node\n )\n }\n }\n\n applyPatchLocally(node: this[\"N\"], subpath: string, patch: IJsonPatch): void {\n const target = node.storedValue\n switch (patch.op) {\n case \"add\":\n case \"replace\":\n target.set(subpath, patch.value)\n break\n case \"remove\":\n target.delete(subpath)\n break\n }\n }\n\n applySnapshot(node: this[\"N\"], snapshot: this[\"C\"]): void {\n typecheckInternal(this, snapshot)\n const target = node.storedValue\n // keys present before the apply, minus the ones the snapshot (re)sets — what\n // remains has to be deleted. A Set rather than a plain object: it needs no\n // sentinel values, no second pass to find the survivors, and it can hold keys\n // like \"__proto__\", which an object literal silently swallows.\n const staleKeys = new Set(target.keys())\n if (snapshot) {\n // Don't use target.replace, as it will throw away all existing items first\n for (const key in snapshot) {\n target.set(key, snapshot[key])\n staleKeys.delete(key)\n }\n }\n for (const key of staleKeys) {\n target.delete(key)\n }\n }\n\n getChildType(): IAnyType {\n return this._subType\n }\n\n isValidSnapshot(\n value: this[\"C\"],\n context: IValidationContext\n ): IValidationResult {\n if (!isPlainObject(value)) {\n return typeCheckFailure(context, value, \"Value is not a plain object\")\n }\n\n for (const key of Object.keys(value)) {\n getContextForPath(context, key, this._subType)\n const errors = this._subType.validate(value[key], context)\n popContext(context)\n if (errors.length > 0) {\n return errors\n }\n }\n return typeCheckSuccess()\n }\n\n getDefaultSnapshot(): this[\"C\"] {\n return EMPTY_OBJECT\n }\n\n removeChild(node: this[\"N\"], subpath: string) {\n node.storedValue.delete(subpath)\n }\n}\nMapType.prototype.applySnapshot = action(MapType.prototype.applySnapshot)\n\n/**\n * `types.map` - Creates a key based collection type who's children are all of a uniform declared type.\n * If the type stored in a map has an identifier, it is mandatory to store the child under that identifier in the map.\n *\n * This type will always produce [observable maps](https://mobx.js.org/api.html#observablemap)\n *\n * Example:\n * ```ts\n * const Todo = types.model({\n * id: types.identifier,\n * task: types.string\n * })\n *\n * const TodoStore = types.model({\n * todos: types.map(Todo)\n * })\n *\n * const s = TodoStore.create({ todos: {} })\n * unprotect(s)\n * s.todos.set(17, { task: \"Grab coffee\", id: 17 })\n * s.todos.put({ task: \"Grab cookie\", id: 18 }) // put will infer key from the identifier\n * console.log(s.todos.get(17).task) // prints: \"Grab coffee\"\n * ```\n *\n * @param subtype\n * @returns\n */\nexport function map<IT extends IAnyType>(subtype: IT): IMapType<IT> {\n assertIsType(subtype, 1)\n return new MapType<IT>(subtype)\n}\n\n/**\n * Returns if a type is a map type, or wraps or unions one. For the map type\n * itself, use {@link asMapType}.\n */\nexport function isMapType(type: IAnyType): boolean {\n return isType(type) && (type.flags & TypeFlags.Map) > 0\n}\n\n/**\n * The map type `type` builds its values with, seeing through the wrappers\n * {@link unwrapType} does, or `undefined` if that is not a map type.\n */\nexport function asMapType(type: IAnyType): IMapType<IAnyType> | undefined {\n const unwrapped = unwrapType(type)\n return unwrapped instanceof MapType ? unwrapped : undefined\n}\n","import {\n type IArrayDidChange,\n type IArraySplice,\n type IArrayWillChange,\n type IArrayWillSplice,\n type IObservableArray,\n _getAdministration,\n action,\n intercept,\n observable,\n observe\n} from \"mobx\"\n\nimport {\n type AnyNode,\n type AnyObjectNode,\n ComplexType,\n EMPTY_ARRAY,\n EMPTY_OBJECT,\n type ExtractCSTWithSTN,\n type HookInitializers,\n type IAnyStateTreeNode,\n type IAnyType,\n type IChildNodesMap,\n type IHooksGetter,\n type IJsonPatch,\n type IStateTreeNode,\n type IType,\n type IValidationContext,\n type IValidationResult,\n NO_HOOK_INITIALIZERS,\n ObjectNode,\n TypeFlags,\n appendHookInitializer,\n assertIsType,\n convertChildNodesToArray,\n createObjectNode,\n fail,\n getContextForPath,\n getStateTreeNode,\n installHookInitializers,\n isArray,\n isNode,\n isPlainObject,\n isStateTreeNode,\n isType,\n ModelType,\n unwrapType,\n mobxShallow,\n normalizeIdentifier,\n popContext,\n typeCheckFailure,\n typeCheckSuccess,\n typecheckInternal\n} from \"../../internal.ts\"\n\n/** @hidden */\nexport interface IMSTArray<IT extends IAnyType> extends IObservableArray<\n IT[\"Type\"]\n> {\n // needs to be split or else it will complain about not being compatible with the array interface\n push(...items: IT[\"Type\"][]): number\n push(...items: ExtractCSTWithSTN<IT>[]): number\n\n concat(...items: ConcatArray<IT[\"Type\"]>[]): IT[\"Type\"][]\n concat(...items: ConcatArray<ExtractCSTWithSTN<IT>>[]): IT[\"Type\"][]\n\n concat(...items: (IT[\"Type\"] | ConcatArray<IT[\"Type\"]>)[]): IT[\"Type\"][]\n concat(\n ...items: (ExtractCSTWithSTN<IT> | ConcatArray<ExtractCSTWithSTN<IT>>)[]\n ): IT[\"Type\"][]\n\n splice(start: number, deleteCount?: number): IT[\"Type\"][]\n splice(\n start: number,\n deleteCount: number,\n ...items: IT[\"Type\"][]\n ): IT[\"Type\"][]\n splice(\n start: number,\n deleteCount: number,\n ...items: ExtractCSTWithSTN<IT>[]\n ): IT[\"Type\"][]\n\n unshift(...items: IT[\"Type\"][]): number\n unshift(...items: ExtractCSTWithSTN<IT>[]): number\n}\n\n/** @hidden */\nexport interface IArrayType<IT extends IAnyType> extends IType<\n readonly IT[\"CreationType\"][] | undefined,\n IT[\"SnapshotType\"][],\n IMSTArray<IT>\n> {\n hooks(hooks: IHooksGetter<IMSTArray<IT>>): IArrayType<IT>\n /** the element type of the array */\n getChildType(): IAnyType\n}\n\n/**\n * @internal\n * @hidden\n */\nexport class ArrayType<IT extends IAnyType> extends ComplexType<\n readonly IT[\"CreationType\"][] | undefined,\n IT[\"SnapshotType\"][],\n IMSTArray<IT>\n> {\n readonly flags = TypeFlags.Array\n\n constructor(\n private readonly _subType: IT,\n private readonly hookInitializers: HookInitializers<\n IMSTArray<IT>\n > = NO_HOOK_INITIALIZERS\n ) {\n super()\n }\n\n protected override computeName(): string {\n return `${this._subType.name}[]`\n }\n\n hooks(hooks: IHooksGetter<IMSTArray<IT>>) {\n return new ArrayType(\n this._subType,\n appendHookInitializer(this.hookInitializers, hooks)\n )\n }\n\n instantiate(\n parent: AnyObjectNode | null,\n subpath: string,\n environment: any,\n initialValue: this[\"C\"] | this[\"T\"]\n ): this[\"N\"] {\n return createObjectNode(this, parent, subpath, environment, initialValue)\n }\n\n initializeChildNodes(\n objNode: this[\"N\"],\n snapshot: this[\"C\"] = []\n ): IChildNodesMap {\n const subType = (objNode.type as this)._subType\n const result: IChildNodesMap = {}\n snapshot.forEach((item, index) => {\n const subpath = `${index}`\n result[subpath] = subType.instantiate(objNode, subpath, undefined, item)\n })\n return result\n }\n\n createNewInstance(childNodes: IChildNodesMap): this[\"T\"] {\n const options = { ...mobxShallow, name: this.name }\n return observable.array(\n convertChildNodesToArray(childNodes) as AnyNode[],\n options\n ) as this[\"T\"]\n }\n\n finalizeNewInstance(node: this[\"N\"], instance: this[\"T\"]): void {\n _getAdministration(instance).dehancer = node.unbox\n\n installHookInitializers((node.type as this).hookInitializers, instance)\n\n intercept(instance as IObservableArray<AnyNode>, this.willChange)\n observe(instance as IObservableArray<AnyNode>, this.didChange)\n }\n\n getChildren(node: this[\"N\"]): AnyNode[] {\n return node.storedValue.slice()\n }\n\n getChildNode(node: this[\"N\"], key: string): AnyNode {\n const child = node.storedValue[Number(key)]\n if (child) {\n return child\n }\n throw fail(`Not a child: ${key}`)\n }\n\n willChange(\n change: IArrayWillChange<AnyNode> | IArrayWillSplice<AnyNode>\n ): IArrayWillChange<AnyNode> | IArrayWillSplice<AnyNode> | null {\n const node = getStateTreeNode(change.object as IStateTreeNode<this>)\n node.assertWritable({ subpath: `${change.index}` })\n const subType = (node.type as this)._subType\n\n switch (change.type) {\n case \"update\":\n {\n if (change.newValue === change.object[change.index]) {\n return null\n }\n\n const updatedNodes = reconcileArrayChildren(\n node,\n subType,\n // only the replaced child is reconciled, so read that one node\n // directly — `node.getChildren()` copies the whole backing array,\n // which made a single-element assignment cost O(array length)\n [node.getChildNode(`${change.index}`)],\n [change.newValue],\n change.index\n )\n if (!updatedNodes) {\n return null\n }\n change.newValue = updatedNodes[0]!\n }\n break\n case \"splice\":\n {\n const { index, removedCount, added } = change\n const childNodes = node.getChildren()\n\n const addedNodes = reconcileArrayChildren(\n node,\n subType,\n childNodes.slice(index, index + removedCount),\n added,\n index\n )\n if (!addedNodes) {\n return null\n }\n change.added = addedNodes\n\n // update paths of remaining items\n for (let i = index + removedCount; i < childNodes.length; i++) {\n childNodes[i]!.setParent(node, `${i + added.length - removedCount}`)\n }\n }\n break\n }\n return change\n }\n\n override getSnapshot(node: this[\"N\"]): this[\"S\"] {\n return node.getChildren().map(childNode => childNode.snapshot)\n }\n\n processInitialSnapshot(childNodes: IChildNodesMap): this[\"S\"] {\n const processed: this[\"S\"] = []\n Object.keys(childNodes).forEach(key => {\n processed.push(childNodes[key]!.getSnapshot())\n })\n return processed\n }\n\n didChange(change: IArrayDidChange<AnyNode> | IArraySplice<AnyNode>): void {\n const node = getStateTreeNode(change.object as IAnyStateTreeNode)\n switch (change.type) {\n case \"update\":\n return void node.emitPatch(\n {\n op: \"replace\",\n path: `${change.index}`,\n value: change.newValue.snapshot,\n oldValue: change.oldValue ? change.oldValue.snapshot : undefined\n },\n node\n )\n case \"splice\":\n for (let i = change.removedCount - 1; i >= 0; i--) {\n node.emitPatch(\n {\n op: \"remove\",\n path: `${change.index + i}`,\n oldValue: change.removed[i]!.snapshot\n },\n node\n )\n }\n for (let i = 0; i < change.addedCount; i++) {\n node.emitPatch(\n {\n op: \"add\",\n path: `${change.index + i}`,\n value: node.getChildNode(`${change.index + i}`).snapshot,\n oldValue: undefined\n },\n node\n )\n }\n return\n }\n }\n\n applyPatchLocally(node: this[\"N\"], subpath: string, patch: IJsonPatch): void {\n const target = node.storedValue\n const index = subpath === \"-\" ? target.length : Number(subpath)\n switch (patch.op) {\n case \"replace\":\n target[index] = patch.value\n break\n case \"add\":\n target.splice(index, 0, patch.value)\n break\n case \"remove\":\n target.splice(index, 1)\n break\n }\n }\n\n applySnapshot(node: this[\"N\"], snapshot: this[\"C\"]): void {\n typecheckInternal(this, snapshot)\n const target = node.storedValue\n target.replace(snapshot as any)\n }\n\n getChildType(): IAnyType {\n return this._subType\n }\n\n isValidSnapshot(\n value: this[\"C\"],\n context: IValidationContext\n ): IValidationResult {\n if (!isArray(value)) {\n return typeCheckFailure(context, value, \"Value is not an array\")\n }\n\n for (let i = 0; i < value.length; i++) {\n getContextForPath(context, `${i}`, this._subType)\n const errors = this._subType.validate(value[i], context)\n popContext(context)\n if (errors.length > 0) {\n return errors\n }\n }\n return typeCheckSuccess()\n }\n\n getDefaultSnapshot(): this[\"C\"] {\n return EMPTY_ARRAY\n }\n\n removeChild(node: this[\"N\"], subpath: string) {\n node.storedValue.splice(Number(subpath), 1)\n }\n}\nArrayType.prototype.applySnapshot = action(ArrayType.prototype.applySnapshot)\n\n/**\n * `types.array` - Creates an index based collection type who's children are all of a uniform declared type.\n *\n * This type will always produce [observable arrays](https://mobx.js.org/api.html#observablearray)\n *\n * Example:\n * ```ts\n * const Todo = types.model({\n * task: types.string\n * })\n *\n * const TodoStore = types.model({\n * todos: types.array(Todo)\n * })\n *\n * const s = TodoStore.create({ todos: [] })\n * unprotect(s) // needed to allow modifying outside of an action\n * s.todos.push({ task: \"Grab coffee\" })\n * console.log(s.todos[0]) // prints: \"Grab coffee\"\n * ```\n *\n * @param subtype\n * @returns\n */\nexport function array<IT extends IAnyType>(subtype: IT): IArrayType<IT> {\n assertIsType(subtype, 1)\n return new ArrayType<IT>(subtype)\n}\n\n/**\n * @param firstNewPath index the reconciled slice starts at; both call sites\n * hand over a contiguous run, so subpath `i` is simply `firstNewPath + i`\n */\nfunction reconcileArrayChildren<TT>(\n parent: AnyObjectNode,\n childType: IType<any, any, TT>,\n oldNodes: AnyNode[],\n newValues: TT[],\n firstNewPath: number\n): AnyNode[] | null {\n let nothingChanged = true\n const result: AnyNode[] = []\n // every old node before `next` is claimed\n const claimed = new Uint8Array(oldNodes.length)\n let next = 0\n let finder: ReuseFinder | undefined\n\n for (let i = 0; i < newValues.length; i++) {\n while (claimed[next]) {\n next++\n }\n const oldNode = oldNodes[next]\n let newValue = newValues[i]\n const newPath = `${firstNewPath + i}`\n\n // for some reason, instead of newValue we got a node, fallback to the storedValue\n // TODO: https://github.com/mobxjs/mobx-state-tree/issues/340#issuecomment-325581681\n if (isNode(newValue)) {\n newValue = newValue.storedValue\n }\n\n if (!oldNode) {\n if (\n isStateTreeNode(newValue) &&\n getStateTreeNode(newValue).parent === parent\n ) {\n // this node is owned by this parent, but not in the reconcilable set, so it must be double\n throw fail(\n `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 '${\n parent.path\n }/${newPath}', but it lives already at '${getStateTreeNode(newValue).path}'`\n )\n }\n nothingChanged = false\n result.push(valueAsNode(childType, parent, newPath, newValue))\n } else if (areSame(oldNode, newValue)) {\n claimed[next] = 1\n result.push(valueAsNode(childType, parent, newPath, newValue, oldNode))\n } else {\n nothingChanged = false\n // a single-element write scans one node, cheaper than building an index\n const j =\n oldNodes.length > 1\n ? (finder ??= new ReuseFinder(childType, oldNodes, claimed)).find(\n newValue,\n next\n )\n : scanForSame(oldNodes, claimed, next, newValue)\n let oldMatch: AnyNode | undefined\n if (j >= 0) {\n claimed[j] = 1\n oldMatch = oldNodes[j]\n }\n result.push(valueAsNode(childType, parent, newPath, newValue, oldMatch))\n }\n }\n\n for (let j = next; j < oldNodes.length; j++) {\n if (!claimed[j]) {\n nothingChanged = false\n const oldNode = oldNodes[j]!\n if (oldNode instanceof ObjectNode) {\n // since it is going to be returned by pop/splice/shift better create it before killing it\n // so it doesn't end up in an undead state\n oldNode.createObservableInstanceIfNeeded()\n }\n oldNode.die()\n }\n }\n\n return nothingChanged ? null : result\n}\n\nfunction scanForSame(\n oldNodes: AnyNode[],\n claimed: Uint8Array,\n from: number,\n value: unknown\n) {\n for (let j = from; j < oldNodes.length; j++) {\n if (!claimed[j] && areSame(oldNodes[j]!, value)) {\n return j\n }\n }\n return -1\n}\n\n/**\n * Picks the old node the reorder branch reuses: the first unclaimed one\n * `areSame` holds for. `areSame` reduces to an equality — node identity for a\n * live node, the old node's snapshot for anything else — except where the\n * value is a plain object and the old node carries an identifier, where it\n * runs `is()` before matching ids. So only that case scans, and an identified\n * plain model looks its id up instead, as ADR 0001 records.\n */\nclass ReuseFinder {\n private readonly idAttribute: string | undefined\n private byId?: Map<string, number>\n private byNode?: Map<AnyNode, number>\n private bySnapshot?: { first: Map<unknown, number>; nextSame: Int32Array }\n private anyIdentified?: boolean\n\n constructor(\n childType: IAnyType,\n private readonly oldNodes: AnyNode[],\n private readonly claimed: Uint8Array\n ) {\n this.idAttribute =\n childType instanceof ModelType ? childType.identifierAttribute : undefined\n }\n\n find(value: unknown, next: number): number {\n let j: number\n if (this.idAttribute && isPlainObject(value)) {\n j =\n this.idIndex(next).get(normalizeIdentifier(value[this.idAttribute])) ??\n -1\n } else if (isStateTreeNode(value)) {\n j = this.nodeIndex(next).get(getStateTreeNode(value)) ?? -1\n } else if (!isPlainObject(value) || !this.hasIdentifiedNode(next)) {\n j = this.firstWithSnapshot(value, next)\n } else {\n return scanForSame(this.oldNodes, this.claimed, next, value)\n }\n return j >= 0 && !this.claimed[j] && areSame(this.oldNodes[j]!, value)\n ? j\n : -1\n }\n\n // last one wins on a duplicate id, even when it is already claimed\n private idIndex(next: number) {\n if (!this.byId) {\n this.byId = new Map()\n for (let j = next; j < this.oldNodes.length; j++) {\n const node = this.oldNodes[j]!\n if (node instanceof ObjectNode && node.identifier !== null) {\n this.byId.set(node.identifier, j)\n }\n }\n }\n return this.byId\n }\n\n private nodeIndex(next: number) {\n if (!this.byNode) {\n this.byNode = new Map()\n for (let j = next; j < this.oldNodes.length; j++) {\n this.byNode.set(this.oldNodes[j]!, j)\n }\n }\n return this.byNode\n }\n\n private hasIdentifiedNode(next: number) {\n if (this.anyIdentified === undefined) {\n this.anyIdentified = this.oldNodes\n .slice(next)\n .some(\n node =>\n node instanceof ObjectNode &&\n node.identifier !== null &&\n !!node.identifierAttribute\n )\n }\n return this.anyIdentified\n }\n\n private firstWithSnapshot(value: unknown, next: number) {\n if (!this.bySnapshot) {\n const first = new Map<unknown, number>()\n const nextSame = new Int32Array(this.oldNodes.length)\n for (let j = this.oldNodes.length - 1; j >= next; j--) {\n const node = this.oldNodes[j]!\n if (!this.claimed[j] && node.isAlive) {\n const snapshot = node.snapshot\n nextSame[j] = first.get(snapshot) ?? -1\n first.set(snapshot, j)\n }\n }\n this.bySnapshot = { first, nextSame }\n }\n const { first, nextSame } = this.bySnapshot\n const head = first.get(value)\n if (head === undefined) {\n return -1\n }\n let j = head\n while (j >= 0 && (this.claimed[j] || !this.oldNodes[j]!.isAlive)) {\n j = nextSame[j]!\n }\n if (j !== head) {\n first.set(value, j)\n }\n return j\n }\n}\n\n/**\n * Convert a value to a node at given parent and subpath. Attempts to reuse old node if possible and given.\n */\nfunction valueAsNode(\n childType: IAnyType,\n parent: AnyObjectNode,\n subpath: string,\n newValue: any,\n oldNode?: AnyNode\n) {\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 const childNode = getStateTreeNode(newValue)\n childNode.assertAlive(EMPTY_OBJECT)\n\n // the node lives here\n if (childNode.parent !== null && childNode.parent === parent) {\n childNode.setParent(parent, subpath)\n return childNode\n }\n }\n // there is old node and new one is a value/snapshot\n if (oldNode) {\n return childType.reconcile(oldNode, newValue, parent, subpath)\n }\n\n // nothing to do, create from scratch\n return childType.instantiate(parent, subpath, undefined, newValue)\n }\n\n const newNode = getNewNode()\n if (oldNode && oldNode !== newNode) {\n if (oldNode instanceof ObjectNode) {\n // since it is going to be returned by pop/splice/shift better create it before killing it\n // so it doesn't end up in an undead state\n oldNode.createObservableInstanceIfNeeded()\n }\n oldNode.die()\n }\n return newNode\n}\n\n/**\n * Reconciliation types that carry an identifier expose this; `getReconciliationType`\n * is declared as the general `IAnyType`, on which it isn't part of the surface.\n */\ninterface SnapshotIdMatcher {\n isMatchingSnapshotId(current: AnyNode, snapshot: any): boolean\n}\n\n/**\n * Check if a node holds a value.\n */\nfunction areSame(oldNode: AnyNode, newValue: any): boolean {\n // never consider dead old nodes for reconciliation\n if (!oldNode.isAlive) {\n return false\n }\n\n // the new value has the same node\n if (isStateTreeNode(newValue)) {\n const newNode = getStateTreeNode(newValue)\n return newNode.isAlive && newNode === oldNode\n }\n\n // the provided value is the snapshot of the old node\n if (oldNode.snapshot === newValue) {\n return true\n }\n\n // Non object nodes don't get reconciled\n if (!(oldNode instanceof ObjectNode)) {\n return false\n }\n\n if (\n oldNode.identifier === null ||\n !oldNode.identifierAttribute ||\n !isPlainObject(newValue)\n ) {\n return false\n }\n\n const oldNodeType = oldNode.getReconciliationType()\n // new value is a snapshot with the correct identifier\n return (\n oldNodeType.is(newValue) &&\n (oldNodeType as unknown as SnapshotIdMatcher).isMatchingSnapshotId(\n oldNode,\n newValue\n )\n )\n}\n\n/**\n * Returns if a type is an array type, or wraps or unions one. For the array\n * type itself, use {@link asArrayType}.\n */\nexport function isArrayType(type: IAnyType): boolean {\n return isType(type) && (type.flags & TypeFlags.Array) > 0\n}\n\n/**\n * The array type `type` builds its values with, seeing through the wrappers\n * {@link unwrapType} does, or `undefined` if that is not an array type.\n */\nexport function asArrayType(type: IAnyType): IArrayType<IAnyType> | undefined {\n const unwrapped = unwrapType(type)\n return unwrapped instanceof ArrayType ? unwrapped : undefined\n}\n","import {\n type IObjectDidChange,\n type IObjectWillChange,\n _getAdministration,\n _interceptReads,\n action,\n computed,\n defineProperty,\n getAtom,\n type IAtom,\n intercept,\n isComputedProp,\n isObservableProp,\n makeObservable,\n observable,\n observe,\n set\n} from \"mobx\"\n\nimport {\n type AnyNode,\n type AnyObjectNode,\n ArrayType,\n ComplexType,\n EMPTY_ARRAY,\n EMPTY_OBJECT,\n type FunctionWithFlag,\n Hook,\n type IAnyStateTreeNode,\n type IAnyType,\n type IChildNodesMap,\n type IJsonPatch,\n type IType,\n type IValidationContext,\n type IValidationResult,\n type Instance,\n MapType,\n TypeFlags,\n type _CustomOrOther,\n type _NotCustomized,\n addHiddenFinalProp,\n addHiddenWritableProp,\n assertArg,\n assertIsString,\n createActionInvoker,\n createObjectNode,\n devMode,\n escapeJsonPath,\n fail,\n freeze,\n getContextForPath,\n getPrimitiveFactoryFromValue,\n getStateTreeNode,\n isPlainObject,\n isPrimitive,\n isStateTreeNode,\n isType,\n unwrapType,\n mobxShallow,\n optional,\n shouldStripChildFromSnapshot,\n popContext,\n typeCheckFailure,\n typeCheckSuccess,\n typecheckInternal\n} from \"../../internal.ts\"\n\nconst PRE_PROCESS_SNAPSHOT = \"preProcessSnapshot\"\nconst POST_PROCESS_SNAPSHOT = \"postProcessSnapshot\"\n\n/**\n * mobx's per-property `ObservableValue`: an atom we can `reportObserved()` plus\n * `raw()` to read the stored child node directly, bypassing the unboxing\n * interceptor installed in `finalizeNewInstance`. mobx types `getAtom` as the\n * bare `IDepTreeNode`, so the one narrowing cast lives here.\n */\ntype PropObservable = IAtom & {\n raw(): AnyNode | undefined\n /** the read interceptor `_interceptReads` installs; see finalizeNewInstance */\n dehancer?: (childNode: AnyNode | undefined) => AnyNode | undefined\n}\n\nfunction getPropObservable(storedValue: any, key: string): PropObservable {\n return getAtom(storedValue, key) as PropObservable\n}\n\n/**\n * All of an instance's per-property `ObservableValue`s in one map, or\n * `undefined` if this mobx does not expose them.\n *\n * `observable.object` returns a **Proxy**, and `getAtom(storedValue, key)`\n * probes it with four `isObservableArray/Set/Map/Object` guards plus a `$mobx`\n * read — each one a marker-property read that goes through the proxy's `get`\n * trap. Paying that per property made the trap machinery the bulk of a wide\n * model's `getSnapshot`; resolving the administration once and reading its\n * property map directly reduces the per-property cost to a `Map.get`.\n *\n * `values_` is mobx-internal, hence the undefined result: every caller keeps a\n * path built on supported API, so a mobx that drops it degrades to the old\n * speed rather than breaking.\n *\n * The map is complete for our instances. `getAtom` falls back to\n * `materializeLazy{Computed,Observable}_` because mobx defers constructing an\n * `ObservableValue` for *decorator* annotations; `createNewInstance` builds\n * these through `observable.object`, which populates `values_` eagerly for\n * every declared property.\n */\nfunction getPropObservables(\n storedValue: any\n): Map<string, PropObservable> | undefined {\n const adm = _getAdministration(storedValue) as {\n values_?: Map<string, PropObservable>\n }\n return adm.values_\n}\n\n/** @hidden */\nexport interface ModelProperties {\n [key: string]: IAnyType\n}\n\n/** @hidden */\nexport type ModelPrimitive = string | number | boolean | Date\n\n/** @hidden */\nexport interface ModelPropertiesDeclaration {\n [key: string]: ModelPrimitive | IAnyType\n}\n\n/**\n * Unmaps syntax property declarations to a map of { propName: IType }\n *\n * @hidden\n */\nexport type ModelPropertiesDeclarationToProperties<\n T extends ModelPropertiesDeclaration\n> = T extends { [k: string]: IAnyType } // optimization to reduce nesting\n ? T\n : {\n [K in keyof T]: T[K] extends IAnyType // keep IAnyType check on the top to reduce nesting\n ? T[K]\n : T[K] extends string\n ? IType<string | undefined, string, string>\n : T[K] extends number\n ? IType<number | undefined, number, number>\n : T[K] extends boolean\n ? IType<boolean | undefined, boolean, boolean>\n : T[K] extends Date\n ? IType<number | Date | undefined, number, Date>\n : never\n }\n\n/**\n * Checks if a value is optional (undefined, any or unknown).\n * @hidden\n *\n * Examples:\n * - string = false\n * - undefined = true\n * - string | undefined = true\n * - string & undefined = false, but we don't care\n * - any = true\n * - unknown = true\n */\ntype IsOptionalValue<C, TV, FV> = undefined extends C ? TV : FV\n\n// type _A = IsOptionalValue<string, true, false> // false\n// type _B = IsOptionalValue<undefined, true, false> // true\n// type _C = IsOptionalValue<string | undefined, true, false> // true\n// type _D = IsOptionalValue<string & undefined, true, false> // false, but we don't care\n// type _E = IsOptionalValue<any, true, false> // true\n// type _F = IsOptionalValue<unknown, true, false> // true\n\n/**\n * Name of the properties of an object that can't be set to undefined, any or unknown\n * @hidden\n */\ntype DefinablePropsNames<T> = {\n [K in keyof T]: IsOptionalValue<T[K], never, K>\n}[keyof T]\n\n// Weak brand applied to the truly-empty *creation* type so it doesn't structurally collapse to\n// `{}` (which TypeScript treats as \"any non-nullish value\"), which would let\n// `types.model().create({ anything })` through. It must be a weak type (only an optional prop) so\n// it can be intersected with `Partial<PC>` in ModelCreationType without rejecting valid props.\n//\n// Deliberately NOT applied to the snapshot type (see ModelSnapshotType): a weak brand there is a\n// \"no properties in common\" type that breaks substitutability of derived models with extra\n// optional props onto their base (issue #2186). Exported so TypeScript can name it in declaration\n// files (TS4058) when the creation type propagates into exported function signatures.\nexport interface $EmptyObjectBrand {\n readonly $__mstEmpty__?: never\n}\ntype EmptyObject = $EmptyObjectBrand\n\n/** @hidden */\nexport type MaybeEmpty<T> = keyof T extends never ? EmptyObject : T\n\n/** @hidden */\nexport type ExtractCFromProps<P extends ModelProperties> = {\n [k in keyof P]: P[k][\"CreationType\"]\n}\n\n/**\n * Merge two property bags with last-wins semantics, mirroring how `compose`\n * and `.props()` override props at runtime. A plain `PA & PB` intersects the\n * value types of shared keys, which collapses overridden discriminants (e.g.\n * `types.literal(\"Base\") & types.literal(\"Child\")`) to `never`.\n * @hidden\n */\nexport type _OverrideProps<\n PA extends ModelProperties,\n PB extends ModelProperties\n> = Omit<PA, keyof PB> & PB\n\n/** @hidden */\nexport type _IsAny<T> = 0 extends 1 & T ? true : false\n\n/**\n * Snapshot processors own only the keys they were written for and pass the\n * rest through, so a processor earlier in a model's chain also carries props\n * added after it. Added props therefore replace their keys in a customized\n * creation or snapshot type; an uncustomized one stays uncustomized.\n * @hidden\n */\nexport type _WithAddedKeys<Custom, Added> =\n _IsAny<Custom> extends true\n ? Custom\n : [Custom] extends [_NotCustomized]\n ? _NotCustomized\n : Omit<Custom, keyof Added> & Added\n\n/** @hidden */\nexport type ModelCreationType<PC> = MaybeEmpty<{\n [P in DefinablePropsNames<PC>]: PC[P]\n}> &\n Partial<PC>\n\n/** @hidden */\nexport type ModelCreationType2<P extends ModelProperties, CustomC> = MaybeEmpty<\n _CustomOrOther<CustomC, ModelCreationType<ExtractCFromProps<P>>>\n>\n\n/** @hidden */\nexport type ModelSnapshotType<P extends ModelProperties> = {\n [K in keyof P]: P[K][\"SnapshotType\"]\n}\n\n/** @hidden */\nexport type ModelSnapshotType2<\n P extends ModelProperties,\n CustomS\n> = _CustomOrOther<CustomS, ModelSnapshotType<P>>\n\n/**\n * @hidden\n * we keep this separate from ModelInstanceType to shorten model instance types generated declarations\n */\nexport type ModelInstanceTypeProps<P extends ModelProperties> = {\n [K in keyof P]: P[K][\"Type\"]\n}\n\n/**\n * @hidden\n * do not transform this to an interface or model instance type generated declarations will be longer\n */\nexport type ModelInstanceType<\n P extends ModelProperties,\n O\n> = ModelInstanceTypeProps<P> & O\n\n/** @hidden */\nexport interface ModelActions {\n [key: string]: FunctionWithFlag\n}\n\nexport interface IModelType<\n PROPS extends ModelProperties,\n OTHERS,\n CustomC = _NotCustomized,\n CustomS = _NotCustomized\n> extends IType<\n ModelCreationType2<PROPS, CustomC>,\n ModelSnapshotType2<PROPS, CustomS>,\n ModelInstanceType<PROPS, OTHERS>\n> {\n readonly properties: PROPS\n\n named(newName: string): IModelType<PROPS, OTHERS, CustomC, CustomS>\n\n props<PROPS2 extends ModelPropertiesDeclaration>(\n props: PROPS2\n ): IModelType<\n _OverrideProps<PROPS, ModelPropertiesDeclarationToProperties<PROPS2>>,\n OTHERS,\n _WithAddedKeys<\n CustomC,\n ModelCreationType<\n ExtractCFromProps<ModelPropertiesDeclarationToProperties<PROPS2>>\n >\n >,\n _WithAddedKeys<\n CustomS,\n ModelSnapshotType<ModelPropertiesDeclarationToProperties<PROPS2>>\n >\n >\n\n views<V extends object>(\n fn: (self: Instance<this>) => V\n ): IModelType<PROPS, OTHERS & V, CustomC, CustomS>\n\n actions<A extends ModelActions>(\n fn: (self: Instance<this>) => A\n ): IModelType<PROPS, OTHERS & A, CustomC, CustomS>\n\n volatile<TP extends object>(\n fn: (self: Instance<this>) => TP\n ): IModelType<PROPS, OTHERS & TP, CustomC, CustomS>\n\n extend<\n A extends ModelActions = {},\n V extends object = {},\n VS extends object = {}\n >(\n fn: (self: Instance<this>) => { actions?: A; views?: V; state?: VS }\n ): IModelType<PROPS, OTHERS & A & V & VS, CustomC, CustomS>\n\n preProcessSnapshot<NewC = ModelCreationType2<PROPS, CustomC>>(\n // The preprocessor may return the loose input snapshot (`NewC`) as well as\n // the strict creation type: migrations commonly massage an untyped record\n // and rely on the model's property defaults to fill the rest. Note the\n // result keeps `CustomC` (not `NewC`) as the creation type, so annotating\n // the preprocessor's parameter to accept legacy snapshots does not loosen\n // the type that `.create()` callers must satisfy.\n fn: (snapshot: NewC) => ModelCreationType2<PROPS, CustomC> | NewC\n ): IModelType<PROPS, OTHERS, CustomC, CustomS>\n\n postProcessSnapshot<NewS = ModelSnapshotType2<PROPS, CustomS>>(\n fn: (snapshot: ModelSnapshotType2<PROPS, CustomS>) => NewS\n ): IModelType<PROPS, OTHERS, CustomC, NewS>\n}\n\n/**\n * Any model type.\n */\nexport interface IAnyModelType extends IModelType<any, any, any, any> {}\n\nfunction objectTypeToString(this: any) {\n return getStateTreeNode(this).toString()\n}\n\ntype SnapshotProcessorFn = (snapshot: any) => any\n\n/** `second` applied to `first`'s result, allocating only when both exist */\nfunction chainProcessors(\n first: SnapshotProcessorFn | undefined,\n second: SnapshotProcessorFn | undefined\n): SnapshotProcessorFn | undefined {\n return first && second\n ? snapshot => second(first(snapshot))\n : (first ?? second)\n}\n\n/**\n * @internal\n * @hidden\n */\nexport interface ModelTypeConfig {\n name?: string\n properties?: ModelPropertiesDeclaration\n initializers?: ReadonlyArray<(instance: any) => any>\n preProcessor?: SnapshotProcessorFn | undefined\n postProcessor?: SnapshotProcessorFn | undefined\n /**\n * @internal Set by cloneAndEnhance when a chain step (`.actions()`,\n * `.views()`, `.volatile()`, …) adds no new properties: `properties` is then\n * the parent type's already-converted + frozen ModelProperties, so the\n * constructor can skip the toPropertiesObject/freeze reprocessing pass, and\n * `propertyNames`/`identifierAttribute` below are the parent's already-derived\n * values (identical, since the property set is unchanged).\n */\n propertiesArePreProcessed?: boolean\n /** @internal Carried with `propertiesArePreProcessed`; see above. */\n propertyNames?: string[]\n /** @internal Carried with `propertiesArePreProcessed`; see above. */\n identifierAttribute?: string | undefined\n /**\n * @internal Set by cloneAndEnhance when new props are added: `properties` is\n * the parent's already-converted+frozen bag merged with the (freshly\n * converted) delta, so every value is already a type. The constructor then\n * skips the toPropertiesObject pass but still freezes + rederives\n * propertyNames/identifierAttribute, since the key set changed.\n */\n propertiesAreConverted?: boolean\n}\n\nconst ANONYMOUS_MODEL_NAME = \"AnonymousModel\"\n\n/**\n * A plain loop rather than a callback per property, which allocated a closure\n * and made an indirect call. This runs once per `types.model()` over every\n * declared property, and jbrowse builds a ~40-slot schema per track.\n */\nfunction findIdentifierAttribute(\n properties: ModelProperties,\n propertyNames: string[]\n): string | undefined {\n let identifierAttribute: string | undefined = undefined\n for (const propName of propertyNames) {\n if (properties[propName]!.flags & TypeFlags.Identifier) {\n if (identifierAttribute) {\n throw fail(\n `Cannot define property '${propName}' as object identifier, property '${identifierAttribute}' is already defined as identifier property`\n )\n }\n identifierAttribute = propName\n }\n }\n return identifierAttribute\n}\n\nfunction toPropertiesObject(\n declaredProps: ModelPropertiesDeclaration\n): ModelProperties {\n // loop through properties and ensures that all items are types\n return Object.keys(declaredProps).reduce(\n (props, key) => {\n // warn if user intended a HOOK\n if (key in Hook) {\n throw fail(\n `Hook '${key}' was defined as property. Hooks should be defined as part of the actions`\n )\n }\n\n // the user intended to use a view\n const descriptor = Object.getOwnPropertyDescriptor(declaredProps, key)!\n if (\"get\" in descriptor) {\n throw fail(\n \"Getters are not supported as properties. Please use views instead\"\n )\n }\n // undefined and null are not valid\n const value = descriptor.value\n if (value === null || value === undefined) {\n throw fail(\n \"The default value of an attribute cannot be null or undefined as the type cannot be inferred. Did you mean `types.maybe(someType)`?\"\n )\n }\n // its a primitive, convert to its type\n else if (isPrimitive(value)) {\n props[key] = optional(getPrimitiveFactoryFromValue(value), value)\n }\n // map defaults to empty object automatically for models\n else if (value instanceof MapType) {\n props[key] = optional(value, {})\n } else if (value instanceof ArrayType) {\n props[key] = optional(value, [])\n }\n // its already a type\n else if (isType(value)) {\n // do nothing, it's already a type\n }\n // its a function, maybe the user wanted a view?\n else if (devMode() && typeof value === \"function\") {\n throw fail(\n `Invalid type definition for property '${key}', it looks like you passed a function. Did you forget to invoke it, or did you intend to declare a view / action?`\n )\n }\n // no other complex values\n else if (devMode() && typeof value === \"object\") {\n throw fail(\n `Invalid type definition for property '${key}', it looks like you passed an object. Try passing another model type or a types.frozen.`\n )\n } else {\n throw fail(\n `Invalid type definition for property '${key}', cannot infer a type from a value like '${value}' (${typeof value})`\n )\n }\n\n return props\n },\n // seeded with the raw declaration; every key is either replaced by its\n // converted type below, left alone because it already is one, or throws\n { ...declaredProps } as ModelProperties\n )\n}\n\n/**\n * @internal\n * @hidden\n */\nexport class ModelType<\n PROPS extends ModelProperties,\n OTHERS,\n CustomC,\n CustomS,\n MT extends IModelType<PROPS, OTHERS, CustomC, CustomS>\n>\n extends ComplexType<\n ModelCreationType2<PROPS, CustomC>,\n ModelSnapshotType2<PROPS, CustomS>,\n ModelInstanceType<PROPS, OTHERS>\n >\n implements IModelType<PROPS, OTHERS, CustomC, CustomS>\n{\n readonly flags = TypeFlags.Object\n\n /*\n * The original object definition\n */\n public readonly initializers: ReadonlyArray<(instance: any) => any>\n public readonly properties: PROPS\n\n readonly preProcessor?: SnapshotProcessorFn | undefined\n readonly postProcessor?: SnapshotProcessorFn | undefined\n readonly propertyNames: string[]\n // member/property name collisions are a property of the type, so we only need\n // to check the first instance we finalize (see finalizeNewInstance)\n private duplicateKeysChecked = false\n\n constructor(opts: ModelTypeConfig) {\n // `??`, not `||`: `types.model(\"\", {})` names the model \"\". The old\n // `Object.assign(this, defaults, opts)` below overwrote the `||` fallback\n // with opts.name afterwards, so that only worked by accident.\n super(opts.name ?? ANONYMOUS_MODEL_NAME)\n // Every field is assigned here, unconditionally and in a fixed order,\n // rather than by `Object.assign(this, defaultObjectOptions, opts)`. `opts`\n // carries a different key set at each of the three call sites — `model()`,\n // and cloneAndEnhance's preprocessed / converted paths — so copying it\n // wholesale gave ModelType three hidden classes, making every later read of\n // `type.properties` / `type.propertyNames` (getSnapshot's inner loop, among\n // others) polymorphic. It also left the internal `propertiesArePreProcessed`\n // / `propertiesAreConverted` plumbing on the type for its whole lifetime.\n this.initializers = opts.initializers ?? EMPTY_ARRAY\n this.preProcessor = opts.preProcessor\n this.postProcessor = opts.postProcessor\n\n const declaredProperties = (opts.properties ?? EMPTY_OBJECT) as PROPS\n if (opts.propertiesArePreProcessed) {\n // `properties` is a parent type's already-converted + frozen output\n // (chain step with no new props), so its derived propertyNames and\n // identifierAttribute are identical to the parent's — reuse them verbatim\n // (cloneAndEnhance passed them in) instead of re-running Object.keys and\n // the per-prop identifier scan, both O(props), on every step.\n this.properties = declaredProperties\n this.propertyNames = opts.propertyNames!\n this.identifierAttribute = opts.identifierAttribute\n } else {\n // `propertiesAreConverted` (set by cloneAndEnhance when props are added)\n // means every value is already a type — the parent's converted bag merged\n // with a freshly converted delta — so skip re-converting. Only raw entry\n // points (`model()`) still need the full toPropertiesObject pass.\n const properties = (\n opts.propertiesAreConverted\n ? declaredProperties\n : toPropertiesObject(declaredProperties)\n ) as PROPS\n this.properties = properties\n freeze(properties) // make sure nobody messes with it\n const propertyNames = Object.keys(properties)\n this.propertyNames = propertyNames\n this.identifierAttribute = findIdentifierAttribute(\n properties,\n propertyNames\n )\n }\n }\n\n cloneAndEnhance(opts: ModelTypeConfig): IAnyModelType {\n // Fast path: a chain step that adds no new properties (.actions/.views/\n // .volatile/.named/pre-postProcessor) reuses this type's already-converted +\n // frozen properties (and their derived names/identifier) verbatim.\n const hasNewProps =\n opts.properties !== undefined && Object.keys(opts.properties).length > 0\n if (!hasNewProps) {\n return new ModelType({\n name: opts.name || this.name,\n properties: this.properties,\n propertiesArePreProcessed: true,\n // safe to share: propertyNames is never mutated after construction\n propertyNames: this.propertyNames,\n identifierAttribute: this.identifierAttribute,\n initializers: this.initializers.concat(opts.initializers || []),\n preProcessor: opts.preProcessor || this.preProcessor,\n postProcessor: opts.postProcessor || this.postProcessor\n })\n }\n // Adding props: this type's `properties` is already converted+frozen, so only\n // the delta needs conversion. compose passes already-converted props\n // (cur.properties) and flags them; `.props()` passes a raw declaration. Either\n // way the merged bag is fully converted, so the constructor skips re-converting\n // the (potentially large) inherited set — the previous hot spot in compose.\n const convertedNewProps = opts.propertiesAreConverted\n ? opts.properties!\n : toPropertiesObject(opts.properties!)\n return new ModelType({\n name: opts.name || this.name,\n properties: Object.assign({}, this.properties, convertedNewProps),\n propertiesAreConverted: true,\n initializers: this.initializers.concat(opts.initializers || []),\n preProcessor: opts.preProcessor || this.preProcessor,\n postProcessor: opts.postProcessor || this.postProcessor\n })\n }\n\n actions<A extends ModelActions>(fn: (self: Instance<this>) => A) {\n const actionInitializer = (self: Instance<this>) => {\n this.instantiateActions(self, fn(self))\n return self\n }\n return this.cloneAndEnhance({ initializers: [actionInitializer] })\n }\n\n private instantiateActions(self: this[\"T\"], actions: ModelActions): void {\n // check if return is correct\n if (!isPlainObject(actions)) {\n throw fail(\n `actions initializer should return a plain object containing actions`\n )\n }\n\n // bind actions to the object created\n Object.keys(actions).forEach(name => {\n // warn if preprocessor was given\n if (name === PRE_PROCESS_SNAPSHOT) {\n throw fail(\n `Cannot define action '${PRE_PROCESS_SNAPSHOT}', it should be defined using 'type.preProcessSnapshot(fn)' instead`\n )\n }\n // warn if postprocessor was given\n if (name === POST_PROCESS_SNAPSHOT) {\n throw fail(\n `Cannot define action '${POST_PROCESS_SNAPSHOT}', it should be defined using 'type.postProcessSnapshot(fn)' instead`\n )\n }\n\n let action2 = actions[name]!\n\n // apply hook composition\n const baseAction = (self as any)[name]\n if (name in Hook && baseAction) {\n const specializedAction = action2\n action2 = function (...args: any[]) {\n baseAction(...args)\n specializedAction(...args)\n }\n }\n\n // the goal of this is to make sure actions using \"this\" can call themselves,\n // while still allowing the middlewares to register them\n const boundAction = action2.bind(actions)\n boundAction._isFlowAction = action2._isFlowAction ?? false\n boundAction.$mst_middleware = action2.$mst_middleware\n const actionInvoker = createActionInvoker(self as any, name, boundAction)\n actions[name] = actionInvoker\n\n // See #646, allow models to be mocked\n ;(!devMode() ? addHiddenFinalProp : addHiddenWritableProp)(\n self,\n name,\n actionInvoker\n )\n })\n }\n\n declare named: MT[\"named\"]\n\n declare props: MT[\"props\"]\n\n volatile<TP extends object>(fn: (self: Instance<this>) => TP) {\n if (typeof fn !== \"function\") {\n throw fail(\n `You passed an ${typeof fn} to volatile state as an argument, when function is expected`\n )\n }\n const stateInitializer = (self: Instance<this>) => {\n this.instantiateVolatileState(self, fn(self))\n return self\n }\n return this.cloneAndEnhance({ initializers: [stateInitializer] })\n }\n\n private instantiateVolatileState(\n self: this[\"T\"],\n state: {\n [key: string]: any\n }\n ): void {\n // check views return\n if (!isPlainObject(state)) {\n throw fail(\n `volatile state initializer should return a plain object containing state`\n )\n }\n set(self, state)\n }\n\n extend<\n A extends ModelActions = {},\n V extends object = {},\n VS extends object = {}\n >(fn: (self: Instance<this>) => { actions?: A; views?: V; state?: VS }) {\n const initializer = (self: Instance<this>) => {\n this.applyExtension(self, fn(self), \"The `extend` function\")\n return self\n }\n return this.cloneAndEnhance({ initializers: [initializer] })\n }\n\n views<V extends object>(fn: (self: Instance<this>) => V) {\n const viewInitializer = (self: Instance<this>) => {\n this.instantiateViews(self, fn(self))\n return self\n }\n return this.cloneAndEnhance({ initializers: [viewInitializer] })\n }\n\n /**\n * @internal\n * @hidden\n * Materializes an additional actions/views/state extension onto an\n * already-created instance, using the same machinery as `.extend()` runs at\n * creation time. Powers {@link extendInstance}; callers must ensure the writes\n * are permitted (see extendInstance, which runs this in an action context).\n */\n applyExtensionToInstance(\n self: this[\"T\"],\n extension: { actions?: ModelActions; views?: object; state?: object }\n ): void {\n this.applyExtension(self, extension, \"extendInstance\")\n }\n\n /**\n * Materializes an `{ actions, views, state }` bundle onto an instance. Shared\n * by `.extend()` (at creation time) and `applyExtensionToInstance` (on a live\n * instance); `subject` only names the caller in the invalid-key error.\n */\n private applyExtension(\n self: this[\"T\"],\n extension: { actions?: ModelActions; views?: object; state?: object },\n subject: string\n ): void {\n const { actions, views, state, ...rest } = extension\n for (const key in rest) {\n throw fail(\n `${subject} should return an object with a subset of the fields 'actions', 'views' and 'state'. Found invalid key '${key}'`\n )\n }\n if (state) {\n this.instantiateVolatileState(self, state)\n }\n if (views) {\n this.instantiateViews(self, views)\n }\n if (actions) {\n this.instantiateActions(self, actions)\n }\n }\n\n private instantiateViews(self: this[\"T\"], views: object): void {\n // check views return\n if (!isPlainObject(views)) {\n throw fail(\n `views initializer should return a plain object containing views`\n )\n }\n Object.getOwnPropertyNames(views).forEach(key => {\n // is this a computed property?\n const descriptor = Object.getOwnPropertyDescriptor(views, key)!\n if (\"get\" in descriptor) {\n defineProperty(self, key, descriptor)\n makeObservable(self, { [key]: computed } as any)\n } else if (typeof descriptor.value === \"function\") {\n // this is a view function, merge as is!\n // See #646, allow models to be mocked\n ;(!devMode() ? addHiddenFinalProp : addHiddenWritableProp)(\n self,\n key,\n descriptor.value\n )\n } else {\n throw fail(\n `A view member should either be a function or getter based property`\n )\n }\n })\n }\n\n declare preProcessSnapshot: MT[\"preProcessSnapshot\"]\n\n declare postProcessSnapshot: MT[\"postProcessSnapshot\"]\n\n instantiate(\n parent: AnyObjectNode | null,\n subpath: string,\n environment: any,\n initialValue: this[\"C\"] | this[\"T\"]\n ): this[\"N\"] {\n const value = isStateTreeNode(initialValue)\n ? initialValue\n : this.applySnapshotPreProcessor(initialValue)\n return createObjectNode(this, parent, subpath, environment, value)\n }\n\n initializeChildNodes(\n objNode: this[\"N\"],\n initialSnapshot: any = {}\n ): IChildNodesMap {\n const type = objNode.type as this\n const properties = type.properties\n const result: IChildNodesMap = {}\n for (const name of type.propertyNames) {\n result[name] = properties[name]!.instantiate(\n objNode,\n name,\n undefined,\n initialSnapshot[name]\n )\n }\n return result\n }\n\n createNewInstance(childNodes: IChildNodesMap): this[\"T\"] {\n const options = { ...mobxShallow, name: this.name }\n return observable.object(childNodes, EMPTY_OBJECT, options) as any\n }\n\n finalizeNewInstance(node: this[\"N\"], instance: this[\"T\"]): void {\n addHiddenFinalProp(instance, \"toString\", objectTypeToString)\n\n // `_interceptReads(instance, name, ...)` assigns exactly this `dehancer`,\n // but reaches the ObservableValue via getAtom — several proxy-trap reads\n // per property (see getPropObservables). Resolve the map once instead.\n const observables = getPropObservables(instance)\n if (observables) {\n for (const name of this.propertyNames) {\n observables.get(name)!.dehancer = node.unbox\n }\n } else {\n for (const name of this.propertyNames) {\n _interceptReads(instance, name, node.unbox)\n }\n }\n\n this.initializers.reduce((self, fn) => fn(self), instance)\n\n // views, actions and volatile share the instance namespace with properties,\n // so a view/action reusing a property name silently clobbers that property's\n // observable value. It's a type-level mistake (identical for every instance),\n // so we check just the first one we finalize: a healthy property stays a\n // plain observable, a shadowing getter becomes a computed, and a shadowing\n // function/value stops being observable at all. The flag is only set on\n // success so a broken type keeps throwing on every create.\n if (!this.duplicateKeysChecked) {\n for (const name of this.propertyNames) {\n if (\n isComputedProp(instance, name) ||\n !isObservableProp(instance, name)\n ) {\n throw fail(`${name} property is declared twice`)\n }\n }\n this.duplicateKeysChecked = true\n }\n\n intercept(instance, this.willChange)\n observe(instance, this.didChange)\n }\n\n private willChange(change: IObjectWillChange): IObjectWillChange | null {\n const node = getStateTreeNode(change.object)\n const subpath = change.name as string\n node.assertWritable({ subpath })\n // MST's removeChild sets the property to undefined rather than deleting it,\n // so mobx only ever delivers \"update\"/\"add\" changes here, never \"remove\".\n if (change.type !== \"remove\") {\n const childType = (node.type as this).properties[subpath]\n // only properties are typed, state are stored as-is references\n if (childType) {\n typecheckInternal(childType, change.newValue)\n change.newValue = childType.reconcile(\n node.getChildNode(subpath),\n change.newValue,\n node,\n subpath\n )\n }\n }\n return change\n }\n\n private didChange(change: IObjectDidChange) {\n const childNode = getStateTreeNode(change.object)\n const childType = (childNode.type as this).properties[change.name as string]\n // skip volatile state (no childType) and never-actually-occurring \"remove\" changes\n if (childType && change.type !== \"remove\") {\n const oldChildValue =\n change.type === \"update\" ? change.oldValue.snapshot : undefined\n childNode.emitPatch(\n {\n op: \"replace\",\n path: escapeJsonPath(change.name as string),\n value: change.newValue.snapshot,\n oldValue: oldChildValue\n },\n childNode\n )\n }\n }\n\n getChildren(node: this[\"N\"]): ReadonlyArray<AnyNode> {\n const names = this.propertyNames\n const storedValue = node.storedValue\n const observables = getPropObservables(storedValue)\n const res: AnyNode[] = new Array(names.length)\n for (let i = 0; i < names.length; i++) {\n const name = names[i]!\n const childNode = (\n observables\n ? observables.get(name)\n : getPropObservable(storedValue, name)\n )?.raw()\n if (!childNode) {\n throw fail(`Node not available for property ${name}`)\n }\n res[i] = childNode\n }\n return res\n }\n\n getChildNode(node: this[\"N\"], key: string): AnyNode {\n if (!(key in this.properties)) {\n throw fail(`Not a value property: ${key}`)\n }\n const childNode = getPropObservable(node.storedValue, key).raw()\n if (!childNode) {\n throw fail(`Node not available for property ${key}`)\n }\n return childNode\n }\n\n override getSnapshot(node: this[\"N\"], applyPostProcess = true): this[\"S\"] {\n const res = {} as any\n const storedValue = node.storedValue\n const properties = this.properties\n const observables = getPropObservables(storedValue)\n for (const name of this.propertyNames) {\n // One mobx lookup serves both purposes: reportObserved so the snapshot\n // computed recomputes when the child is reassigned (raw() below does not\n // track), and raw() to read the child node. Going through getChildNode\n // would repeat the same lookup for every property.\n const observable = observables\n ? observables.get(name)\n : getPropObservable(storedValue, name)\n observable?.reportObserved()\n const childNode = observable?.raw()\n if (!childNode) {\n throw fail(`Node not available for property ${name}`)\n }\n const snapshot = childNode.snapshot\n // strip-default optionals omit their key when equal to the default\n if (!shouldStripChildFromSnapshot(properties[name]!, snapshot)) {\n res[name] = snapshot\n }\n }\n if (applyPostProcess) {\n return this.applySnapshotPostProcessor(res)\n }\n return res\n }\n\n processInitialSnapshot(childNodes: IChildNodesMap): this[\"S\"] {\n const processed = {} as any\n Object.keys(childNodes).forEach(key => {\n const snapshot = childNodes[key]!.getSnapshot()\n // strip-default optionals omit their key when equal to the default; this\n // mirrors getSnapshot for nodes serialized before they become observable\n // instances (e.g. array/map children that were never accessed)\n if (!shouldStripChildFromSnapshot(this.properties[key]!, snapshot)) {\n processed[key] = snapshot\n }\n })\n return this.applySnapshotPostProcessor(processed)\n }\n\n applyPatchLocally(node: this[\"N\"], subpath: string, patch: IJsonPatch): void {\n if (!(patch.op === \"replace\" || patch.op === \"add\")) {\n throw fail(`object does not support operation ${patch.op}`)\n }\n ;(node.storedValue as any)[subpath] = patch.value\n }\n\n applySnapshot(node: this[\"N\"], snapshot: this[\"C\"]): void {\n typecheckInternal(this, snapshot)\n const preProcessedSnapshot = this.applySnapshotPreProcessor(snapshot)\n for (const name of this.propertyNames) {\n ;(node.storedValue as any)[name] = preProcessedSnapshot[name]\n }\n }\n\n applySnapshotPreProcessor(snapshot: any) {\n const preProcessor = this.preProcessor\n return preProcessor ? preProcessor(snapshot) : snapshot\n }\n\n applySnapshotPostProcessor(snapshot: any) {\n const postProcessor = this.postProcessor\n return postProcessor ? postProcessor(snapshot) : snapshot\n }\n\n getChildType(propertyName: string): IAnyType {\n assertIsString(propertyName, 1)\n\n return this.properties[propertyName]!\n }\n\n isValidSnapshot(\n value: this[\"C\"],\n context: IValidationContext\n ): IValidationResult {\n const snapshot = this.applySnapshotPreProcessor(value)\n\n if (!isPlainObject(snapshot)) {\n return typeCheckFailure(context, snapshot, \"Value is not a plain object\")\n }\n\n for (const key of this.propertyNames) {\n const propType = this.properties[key]!\n getContextForPath(context, key, propType)\n const errors = propType.validate(snapshot[key], context)\n popContext(context)\n if (errors.length > 0) {\n return errors\n }\n }\n return typeCheckSuccess()\n }\n\n override describe() {\n return `{ ${this.propertyNames\n .map(key => `${key}: ${this.properties[key]!.describe()}`)\n .join(\"; \")} }`\n }\n\n getDefaultSnapshot(): this[\"C\"] {\n return EMPTY_OBJECT as this[\"C\"]\n }\n\n removeChild(node: this[\"N\"], subpath: string) {\n ;(node.storedValue as any)[subpath] = undefined\n }\n}\nModelType.prototype.applySnapshot = action(ModelType.prototype.applySnapshot)\n\ntype ModelTypeSelf = ModelType<\n ModelProperties,\n unknown,\n unknown,\n unknown,\n IAnyModelType\n>\n\n// Chain steps shared by every model type; see the field declarations in the\n// class for why they are not own slots.\nObject.assign(ModelType.prototype as object, {\n named(this: ModelTypeSelf, name: string) {\n return this.cloneAndEnhance({ name })\n },\n props(this: ModelTypeSelf, properties: ModelPropertiesDeclaration) {\n return this.cloneAndEnhance({ properties })\n },\n // a newly added pre-processor sees the raw snapshot first; a newly added\n // post-processor sees what the existing one produced\n preProcessSnapshot(this: ModelTypeSelf, preProcessor: SnapshotProcessorFn) {\n return this.cloneAndEnhance({\n preProcessor: chainProcessors(preProcessor, this.preProcessor)\n })\n },\n postProcessSnapshot(this: ModelTypeSelf, postProcessor: SnapshotProcessorFn) {\n return this.cloneAndEnhance({\n postProcessor: chainProcessors(this.postProcessor, postProcessor)\n })\n }\n})\n\nexport function model<P extends ModelPropertiesDeclaration = {}>(\n name: string,\n properties?: P\n): IModelType<ModelPropertiesDeclarationToProperties<P>, {}>\nexport function model<P extends ModelPropertiesDeclaration = {}>(\n properties?: P\n): IModelType<ModelPropertiesDeclarationToProperties<P>, {}>\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 */\nexport function model(...args: any[]): any {\n if (devMode() && typeof args[0] !== \"string\" && args[1]) {\n throw fail(\n \"Model creation failed. First argument must be a string when two arguments are provided\"\n )\n }\n\n const name = typeof args[0] === \"string\" ? args.shift() : ANONYMOUS_MODEL_NAME\n const properties = args.shift() || {}\n return new ModelType({ name, properties })\n}\n\n/** @hidden */\nexport type _ComposableParts = readonly [\n IAnyModelType,\n IAnyModelType,\n ...IAnyModelType[]\n]\n\n/**\n * Props override left to right, as `compose` merges them at runtime.\n * @hidden\n */\nexport type _ComposedProps<\n Acc extends ModelProperties,\n Rest\n> = Rest extends readonly [IModelType<infer P, any, any, any>, ...infer Tail]\n ? _ComposedProps<_OverrideProps<Acc, P>, Tail>\n : Acc\n\n/** @hidden */\nexport type _ComposedOthers<Parts> = Parts extends readonly [\n IModelType<any, infer O, any, any>,\n ...infer Tail\n]\n ? O & _ComposedOthers<Tail>\n : unknown\n\n/**\n * A composed part's snapshot processors are handed the whole snapshot but own\n * only their part's keys, passing the other parts' through — the only way a\n * part can process without knowing what it is composed with. So a part with a\n * custom creation (`\"C\"`) or snapshot (`\"S\"`) type replaces its own props' keys\n * in the merged type. `_NotCustomized` when no part customizes.\n * @hidden\n */\nexport type _ComposedCustom<\n Parts,\n Which extends \"C\" | \"S\",\n Acc,\n Customized extends boolean = false\n> = Parts extends readonly [\n IModelType<infer P, any, infer C, infer S>,\n ...infer Tail\n]\n ? (Which extends \"C\" ? C : S) extends _NotCustomized\n ? _ComposedCustom<Tail, Which, Acc, Customized>\n : _ComposedCustom<\n Tail,\n Which,\n Omit<Acc, keyof P> & (Which extends \"C\" ? C : S),\n true\n >\n : Customized extends true\n ? Acc\n : _NotCustomized\n\n/** @hidden */\nexport type _ComposedModel<Props extends ModelProperties, Parts> = IModelType<\n Props,\n _ComposedOthers<Parts>,\n _ComposedCustom<Parts, \"C\", ModelCreationType<ExtractCFromProps<Props>>>,\n _ComposedCustom<Parts, \"S\", ModelSnapshotType<Props>>\n>\n\n/** @hidden */\n/**\n * A part typed `any` makes the composition `any`-shaped: inferring from `any`\n * would yield the parameters' constraints instead, an empty model.\n * @hidden\n */\nexport type _Composed<Parts extends _ComposableParts> =\n true extends _IsAny<Parts[number]>\n ? IAnyModelType\n : Parts extends readonly [IModelType<infer P, any, any, any>, ...infer Tail]\n ? _ComposedModel<_ComposedProps<P, Tail>, Parts>\n : never\n\nexport function compose<Parts extends _ComposableParts>(\n name: string,\n ...parts: Parts\n): _Composed<Parts>\nexport function compose<Parts extends _ComposableParts>(\n ...parts: Parts\n): _Composed<Parts>\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 */\nexport function compose(...args: any[]): any {\n const hasTypename = typeof args[0] === \"string\"\n const typeName: string = hasTypename ? args[0] : ANONYMOUS_MODEL_NAME\n if (hasTypename) {\n args.shift()\n }\n\n // exactly a model type: each part's own properties and initializers are\n // read below, and a wrapper around a model has neither\n if (devMode()) {\n args.forEach((type, i) => {\n assertArg(\n type,\n t => t instanceof ModelType,\n \"mobx-state-tree model type\",\n hasTypename ? i + 2 : i + 1\n )\n })\n }\n\n return args\n .reduce((prev, cur) =>\n prev.cloneAndEnhance({\n properties: cur.properties,\n // cur.properties is another ModelType's already-converted+frozen bag\n propertiesAreConverted: true,\n initializers: cur.initializers,\n preProcessor: chainProcessors(prev.preProcessor, cur.preProcessor),\n postProcessor: chainProcessors(prev.postProcessor, cur.postProcessor)\n })\n )\n .named(typeName)\n}\n\n/**\n * Returns if a type is a model type, or wraps or unions one. For the model\n * type itself, use {@link asModelType}.\n */\nexport function isModelType(type: IAnyType): boolean {\n return isType(type) && (type.flags & TypeFlags.Object) > 0\n}\n\n/**\n * The model type `type` builds its values with, seeing through the wrappers\n * {@link unwrapType} does, or `undefined` if that is not a model type.\n */\nexport function asModelType(type: IAnyType): IAnyModelType | undefined {\n const unwrapped = unwrapType(type)\n return unwrapped instanceof ModelType ? unwrapped : undefined\n}\n\n/**\n * `extendInstance` - attaches additional actions, views and volatile state to an\n * already-created model instance, using the same instantiation machinery as\n * `.extend()`. This enables lazily loading a model's views/actions chain: create\n * the model with only its base props (plus any critical-path members), then attach\n * the rest at runtime — e.g. from a dynamically imported module — without rebuilding\n * the type or re-hydrating the tree.\n *\n * The extension is applied inside an action context, so it works on protected trees.\n * Attached views are computeds (reactive, memoized) and attached actions get a full\n * MST action context, exactly like members declared in the original chain.\n *\n * Note: the attached members are NOT part of the instance's *static* type. If you\n * need them typed, declare the augmented shape separately (an `import type` of the\n * chain's return type is erased at build time, so it costs nothing in the bundle).\n *\n * @param instance a live model instance\n * @param fn receives the instance and returns `{ actions?, views?, state? }`\n * @returns the same instance\n */\nexport function extendInstance<T extends IAnyStateTreeNode>(\n instance: T,\n fn: (self: T) => { actions?: ModelActions; views?: object; state?: object }\n): T {\n if (!isStateTreeNode(instance)) {\n throw fail(\"extendInstance expects a mobx-state-tree node\")\n }\n const type: IAnyType = getStateTreeNode(instance).type\n if (!(type instanceof ModelType)) {\n throw fail(\"extendInstance can only be used on model instances\")\n }\n // Views/actions/volatile are installed via defineProperty + makeObservable — the\n // same \"add\" operations the initializers perform at creation, before the\n // write-protection interceptor is attached (see finalizeNewInstance). On a live\n // instance that interceptor is already active, so run the attach inside an action\n // context: isRunningAction() then short-circuits assertWritable.\n const attach = createActionInvoker(instance, \"@@extendInstance\", (() => {\n type.applyExtensionToInstance(instance, fn(instance))\n }) as FunctionWithFlag)\n attach()\n return instance\n}\n","import {\n SimpleType,\n TypeFlags,\n createScalarNode,\n fail,\n identity,\n isPrimitive,\n isType,\n typeCheckFailure,\n typeCheckSuccess\n} from \"../internal.ts\"\n\nimport type {\n AnyNode,\n AnyObjectNode,\n IAnyType,\n ISimpleType,\n IType,\n IValidationContext,\n IValidationResult\n} from \"../internal.ts\"\n\n// TODO: implement CoreType using types.custom ?\n/**\n * @internal\n * @hidden\n */\nexport class CoreType<C, S, T> extends SimpleType<C, S, T> {\n constructor(\n name: string,\n readonly flags: TypeFlags,\n private readonly checker: (value: C) => boolean,\n private readonly initializer: (v: C) => T = identity\n ) {\n super(name)\n }\n\n instantiate(\n parent: AnyObjectNode | null,\n subpath: string,\n environment: any,\n initialValue: C\n ): this[\"N\"] {\n return createScalarNode(this, parent, subpath, environment, initialValue)\n }\n\n override createNewInstance(snapshot: C) {\n return this.initializer(snapshot)\n }\n\n isValidSnapshot(value: C, context: IValidationContext): IValidationResult {\n if (isPrimitive(value) && this.checker(value)) {\n return typeCheckSuccess()\n }\n const typeName =\n this.name === \"Date\" ? \"Date or a unix milliseconds timestamp\" : this.name\n return typeCheckFailure(context, value, `Value is not a ${typeName}`)\n }\n}\n\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 */\nexport const string: ISimpleType<string> = new CoreType<string, string, string>(\n \"string\",\n TypeFlags.String,\n v => typeof v === \"string\"\n)\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 */\nexport const number: ISimpleType<number> = new CoreType<number, number, number>(\n \"number\",\n TypeFlags.Number,\n v => typeof v === \"number\"\n)\n\n/**\n * `types.integer` - Creates a type that can only contain an integer value.\n *\n * Example:\n * ```ts\n * const Size = types.model({\n * width: types.integer,\n * height: 10\n * })\n * ```\n */\nexport const integer: ISimpleType<number> = new CoreType<\n number,\n number,\n number\n>(\"integer\", TypeFlags.Integer, Number.isInteger)\n\n/**\n * `types.float` - Creates a type that can only contain an float value.\n *\n * Example:\n * ```ts\n * const Size = types.model({\n * width: types.float,\n * height: 10\n * })\n * ```\n */\nexport const float: ISimpleType<number> = new CoreType<number, number, number>(\n \"float\",\n TypeFlags.Float,\n v => Number(v) === v && v % 1 !== 0\n)\n\n/**\n * `types.finite` - Creates a type that can only contain an finite value.\n *\n * Example:\n * ```ts\n * const Size = types.model({\n * width: types.finite,\n * height: 10\n * })\n * ```\n */\nexport const finite: ISimpleType<number> = new CoreType<number, number, number>(\n \"finite\",\n TypeFlags.Finite,\n Number.isFinite\n)\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 */\nexport const boolean: ISimpleType<boolean> = new CoreType<\n boolean,\n boolean,\n boolean\n>(\"boolean\", TypeFlags.Boolean, v => typeof v === \"boolean\")\n\n/**\n * `types.null` - The type of the value `null`\n */\nexport const nullType: ISimpleType<null> = new CoreType<null, null, null>(\n \"null\",\n TypeFlags.Null,\n v => v === null\n)\n\n/**\n * `types.undefined` - The type of the value `undefined`\n */\nexport const undefinedType: ISimpleType<undefined> = new CoreType<\n undefined,\n undefined,\n undefined\n>(\"undefined\", TypeFlags.Undefined, v => v === undefined)\n\nconst _DatePrimitive = new CoreType<number | Date, number, Date>(\n \"Date\",\n TypeFlags.Date,\n v => typeof v === \"number\" || v instanceof Date,\n v => (v instanceof Date ? v : new Date(v))\n)\n_DatePrimitive.getSnapshot = function (node: AnyNode) {\n return node.storedValue.getTime()\n}\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 */\nexport const DatePrimitive: IType<number | Date, number, Date> = _DatePrimitive\n\n/**\n * @internal\n * @hidden\n */\nexport function getPrimitiveFactoryFromValue(value: any): ISimpleType<any> {\n switch (typeof value) {\n case \"string\":\n return string\n case \"number\":\n return number // In the future, isInteger(value) ? integer : number would be interesting, but would be too breaking for now\n case \"boolean\":\n return boolean\n case \"object\":\n if (value instanceof Date) {\n return DatePrimitive\n }\n }\n throw fail(`Cannot determine primitive type from value ${value}`)\n}\n\n/**\n * Returns if a given value represents a primitive type.\n *\n * Like every `isXType` guard it reads the type's flags, which wrappers and\n * unions inherit from what they hold, so it is also true for a type that wraps\n * or unions one. Use {@link unwrapType} to get at the type itself.\n *\n * @param type\n * @returns\n */\nexport function isPrimitiveType(type: IAnyType): boolean {\n return (\n isType(type) &&\n (type.flags &\n (TypeFlags.String |\n TypeFlags.Number |\n TypeFlags.Integer |\n TypeFlags.Float |\n TypeFlags.Finite |\n TypeFlags.Boolean |\n TypeFlags.Date)) >\n 0\n )\n}\n","import {\n type AnyObjectNode,\n type IAnyType,\n type ISimpleType,\n type IValidationContext,\n type IValidationResult,\n type Primitives,\n SimpleType,\n TypeFlags,\n createScalarNode,\n isPrimitive,\n isType,\n typeCheckFailure,\n typeCheckSuccess\n} from \"../../internal.ts\"\nimport { assertArg } from \"../../utils.ts\"\n\n/**\n * @internal\n * @hidden\n */\nexport class Literal<T> extends SimpleType<T, T, T> {\n readonly value: T\n readonly flags = TypeFlags.Literal\n\n constructor(value: T) {\n super()\n this.value = value\n }\n\n protected override computeName(): string {\n return JSON.stringify(this.value)\n }\n\n instantiate(\n parent: AnyObjectNode | null,\n subpath: string,\n environment: any,\n initialValue: this[\"C\"]\n ): this[\"N\"] {\n return createScalarNode(this, parent, subpath, environment, initialValue)\n }\n\n isValidSnapshot(\n value: this[\"C\"],\n context: IValidationContext\n ): IValidationResult {\n if (isPrimitive(value) && value === this.value) {\n return typeCheckSuccess()\n }\n return typeCheckFailure(\n context,\n value,\n `Value is not a literal ${JSON.stringify(this.value)}`\n )\n }\n}\n\n/**\n * A literal type, which additionally publishes the exact value it matches.\n * `getUnionSubtypes` of an enumeration returns these, so the members can be\n * mapped back to their values without a hand-declared interface.\n */\nexport interface ILiteralType<S extends Primitives> extends ISimpleType<S> {\n readonly value: S\n}\n\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 */\nexport function literal<S extends Primitives>(value: S): ILiteralType<S> {\n // check that the given value is a primitive\n assertArg(value, isPrimitive, \"primitive\", 1)\n\n return new Literal<S>(value)\n}\n\n/**\n * Returns if a given value represents a literal type.\n *\n * Like every `isXType` guard it reads the type's flags, which wrappers and\n * unions inherit from what they hold, so it is also true for a type that wraps\n * or unions one. Use {@link unwrapType} to get at the type itself.\n *\n * @param type\n * @returns\n */\nexport function isLiteralType(type: IAnyType): boolean {\n return isType(type) && (type.flags & TypeFlags.Literal) > 0\n}\n","import {\n type AnyObjectNode,\n BaseType,\n type ExtractNodeType,\n type IAnyType,\n type IValidationContext,\n type IValidationResult,\n TypeFlags,\n assertIsType,\n getStateTreeNode,\n isStateTreeNode,\n isType,\n typeCheckFailure,\n typeCheckSuccess\n} from \"../../internal.ts\"\nimport { assertIsFunction, assertIsString } from \"../../utils.ts\"\n\nclass Refinement<IT extends IAnyType> extends BaseType<\n IT[\"CreationType\"],\n IT[\"SnapshotType\"],\n IT[\"TypeWithoutSTN\"],\n ExtractNodeType<IT>\n> {\n get flags() {\n return this._subtype.flags | TypeFlags.Refinement\n }\n\n constructor(\n name: string,\n private readonly _subtype: IT,\n private readonly _predicate: (v: IT[\"CreationType\"]) => boolean,\n private readonly _message: (v: IT[\"CreationType\"]) => string\n ) {\n super(name)\n }\n\n instantiate(\n parent: AnyObjectNode | null,\n subpath: string,\n environment: any,\n initialValue: this[\"C\"] | this[\"T\"]\n ): this[\"N\"] {\n // create the child type\n return this._subtype.instantiate(\n parent,\n subpath,\n environment,\n initialValue\n ) as any\n }\n\n override isAssignableFrom(type: IAnyType) {\n return this._subtype.isAssignableFrom(type)\n }\n\n isValidSnapshot(\n value: this[\"C\"],\n context: IValidationContext\n ): IValidationResult {\n const subtypeErrors = this._subtype.validate(value, context)\n if (subtypeErrors.length > 0) {\n return subtypeErrors\n }\n\n const snapshot = isStateTreeNode(value)\n ? getStateTreeNode(value).snapshot\n : value\n\n if (!this._predicate(snapshot)) {\n return typeCheckFailure(context, value, this._message(value))\n }\n\n return typeCheckSuccess()\n }\n\n reconcile(\n current: this[\"N\"],\n newValue: this[\"C\"] | this[\"T\"],\n parent: AnyObjectNode,\n subpath: string\n ): this[\"N\"] {\n return this._subtype.reconcile(current, newValue, parent, subpath) as any\n }\n\n getSubTypes() {\n return this._subtype\n }\n}\n\nexport function refinement<IT extends IAnyType>(\n name: string,\n type: IT,\n predicate: (snapshot: IT[\"CreationType\"]) => boolean,\n message?: string | ((v: IT[\"CreationType\"]) => string)\n): IT\nexport function refinement<IT extends IAnyType>(\n type: IT,\n predicate: (snapshot: IT[\"CreationType\"]) => boolean,\n message?: string | ((v: IT[\"CreationType\"]) => string)\n): IT\n\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 */\nexport function refinement(...args: any[]): IAnyType {\n const name =\n typeof args[0] === \"string\"\n ? args.shift()\n : isType(args[0])\n ? args[0].name\n : null\n const type = args[0]\n const predicate = args[1]\n const message = args[2]\n ? args[2]\n : (_v: any) => \"Value does not respect the refinement predicate\"\n // ensures all parameters are correct\n assertIsType(type, [1, 2])\n assertIsString(name, 1)\n assertIsFunction(predicate, [2, 3])\n assertIsFunction(message, [3, 4])\n\n return new Refinement(name, type, predicate, message)\n}\n\n/**\n * Returns if a given value is a refinement type.\n *\n * Like every `isXType` guard it reads the type's flags, which wrappers and\n * unions inherit from what they hold, so it is also true for a type that wraps\n * or unions one. Use {@link unwrapType} to get at the type itself.\n *\n * @param type\n * @returns\n */\nexport function isRefinementType(type: IAnyType): boolean {\n return isType(type) && (type.flags & TypeFlags.Refinement) > 0\n}\n","import {\n type ISimpleType,\n Union,\n assertIsString,\n devMode,\n literal\n} from \"../../internal.ts\"\n\n/** @hidden */\nexport type UnionStringArray<T extends readonly string[]> = T[number]\n\nexport function enumeration<T extends string>(\n options: readonly T[]\n): ISimpleType<T>\nexport function enumeration<T extends string>(\n name: string,\n options: readonly T[]\n): ISimpleType<T>\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 * The member type is inferred from the options, so a literal array, an\n * `as const` array and `Object.values(SomeStringEnum)` all produce the exact\n * union; only an array already typed `string[]` falls back to `string`.\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 */\nexport function enumeration(\n nameOrOptions: string | readonly string[],\n maybeOptions?: readonly string[]\n): ISimpleType<string> {\n const name = typeof nameOrOptions === \"string\" ? nameOrOptions : undefined\n const options =\n typeof nameOrOptions === \"string\" ? maybeOptions! : nameOrOptions\n if (devMode()) {\n options.forEach((option, i) => {\n assertIsString(option, i + 1)\n })\n }\n // built directly rather than through union(): its members are fresh\n // literals, so interning could never share it, and the name belongs to this\n // union alone\n return new Union(\n options.map(option => literal(`${option}`)),\n name === undefined ? undefined : { name }\n )\n}\n","import {\n type AnyObjectNode,\n BaseType,\n formatValidationErrorLines,\n type IAnyType,\n type IType,\n type IValidationContext,\n type IValidationResult,\n Literal,\n ModelType,\n Resilient,\n TypeFlags,\n type _NotCustomized,\n assertArg,\n assertIsType,\n devMode,\n fail,\n isPlainObject,\n isStateTreeNode,\n isType,\n isTypeCheckingEnabled,\n unwrapType,\n typeCheckFailure,\n typeCheckSuccess\n} from \"../../internal.ts\"\n\nexport type ITypeDispatcher = (snapshot: any) => IAnyType\n\nexport interface UnionOptions {\n eager?: boolean\n dispatcher?: ITypeDispatcher\n // Late-bound membership: the union re-reads this thunk on every operation, so\n // members registered after construction participate in dispatch, validation\n // and — critically — reference resolution (`isAssignableFrom` is how the\n // identifier cache decides whether a node can satisfy a reference). Cannot be\n // combined with positional member types. See DynamicUnion below.\n members?: () => IAnyType[]\n // With `members` the folded name would be a moving target, so a stable\n // explicit name is offered; it is honored on any options union.\n name?: string\n}\n\ntype AnyModelType = ModelType<any, any, any, any, any>\n\n// The model a member is meant for: the one under its wrappers, and for a\n// `resilient` member the one it tries first. Matching a snapshot to a member\n// (quick-match dispatch, discriminator scoping) keys on that model's props,\n// and real-world members are rarely bare models (jbrowse config schemas are\n// always optional(model) or optional(snapshotProcessor(model))).\n// Misses are cached too, unless the member holds a `late` type: that has no\n// subtype until its definition evaluates, so its miss must stay retryable.\nconst intendedModelTypes = new WeakMap<IAnyType, AnyModelType | null>()\n\nfunction resolveModelType(type: IAnyType): AnyModelType | undefined {\n const cached = intendedModelTypes.get(type)\n if (cached !== undefined) {\n return cached ?? undefined\n }\n const model = findIntendedModelType(type)\n if (model || !(type.flags & TypeFlags.Late)) {\n intendedModelTypes.set(type, model ?? null)\n }\n return model\n}\n\nfunction findIntendedModelType(type: IAnyType): AnyModelType | undefined {\n const unwrapped = unwrapType(type)\n if (unwrapped instanceof ModelType) {\n return unwrapped\n }\n return unwrapped instanceof Resilient\n ? findIntendedModelType(unwrapped.primaryType)\n : undefined\n}\n\n// The quick-match paths below already know a type carries TypeFlags.Literal,\n// but `is()` still routes through BaseType.validate — a context array, an entry\n// object and a `$treenode` probe per property, per candidate member. A real\n// `Literal` stores its primitive, and its isValidSnapshot is exactly value\n// equality against it, so compare directly. The `instanceof` gate is load\n// bearing: wrappers (optional, refinement, snapshotProcessor, late, union)\n// inherit the Literal flag from what they wrap and must keep the full check.\nfunction matchesLiteral(type: IAnyType, value: unknown): boolean {\n return type instanceof Literal ? type.value === value : type.is(value)\n}\n\n/**\n * @internal\n * @hidden\n */\nexport class Union extends BaseType<any, any, any> {\n // These, plus `_discriminatorCache` and `_allMembersDiscriminated` below,\n // live on the prototype and only become own slots on the union that needs\n // one. An eager, dispatcher-less union that is never instantiated and never\n // fails a typecheck carries none of them — which is every union jbrowse\n // builds per config slot, tens of thousands per session load. Same reasoning\n // as `BaseType.isType`; see agent-docs/adr/0003.\n declare private readonly _dispatcher?: ITypeDispatcher\n declare private readonly _eager: boolean\n\n private _flags?: TypeFlags\n\n // Memoized, but only once the fold is known to be stable. A `types.late`\n // member reports 0 for its subtype until its definition resolves, so a union\n // containing one must keep recomputing — and every wrapper ORs its subtype's\n // flags upward, so `Late` in the *result* is an exact test for \"some member\n // may still change\" however deeply it is nested. A resolved late still\n // reports Late, so such a union simply never caches; that is conservative in\n // the safe direction and no real-world union is built out of late members.\n //\n // This reverses an earlier decision to leave it uncached, which was sized at\n // ~4% \"on union creation alone\". That understated it: the reads are what\n // cost, not the creation. `ModelType._getIdentifierAttribute` folds every\n // property's flags on each `types.model()`, and jbrowse's config slots are\n // unions under a stripDefault, so building one schema re-folded every slot's\n // union. See agent-docs/adr/0003.\n get flags(): TypeFlags {\n const cached = this._flags\n if (cached !== undefined) {\n return cached\n }\n const result = this.foldFlags()\n if (!(result & TypeFlags.Late)) {\n this._flags = result\n }\n return result\n }\n\n protected foldFlags(): TypeFlags {\n let result: TypeFlags = TypeFlags.Union\n for (const type of this.members()) {\n result |= type.flags\n }\n return result\n }\n\n protected override computeName(): string {\n return `(${this.members()\n .map(type => type.name)\n .join(\" | \")})`\n }\n\n constructor(\n private readonly _types: IAnyType[],\n options?: UnionOptions\n ) {\n super()\n // read the options directly rather than spreading defaults into a fresh\n // object: this constructor runs once per config slot in jbrowse, and the\n // merged object was allocated only to be read twice and dropped\n if (options !== undefined) {\n if (options.dispatcher !== undefined) {\n this._dispatcher = options.dispatcher\n }\n if (options.eager === false) {\n this._eager = false\n }\n if (options.name !== undefined) {\n this.name = options.name\n }\n }\n }\n\n // The one point membership is read through, so DynamicUnion can substitute\n // its thunk without duplicating any of the scanning logic below.\n protected members(): IAnyType[] {\n return this._types\n }\n\n override isAssignableFrom(type: IAnyType) {\n return this.members().some(subType => subType.isAssignableFrom(type))\n }\n\n override describe() {\n return `(${this.members()\n .map(factory => factory.describe())\n .join(\" | \")})`\n }\n\n instantiate(\n parent: AnyObjectNode | null,\n subpath: string,\n environment: any,\n initialValue: this[\"C\"] | this[\"T\"]\n ): this[\"N\"] {\n const type = this.determineType(initialValue, undefined)\n if (!type) {\n throw fail(this.noMatchMessage(initialValue))\n } // can happen in prod builds\n return type.instantiate(parent, subpath, environment, initialValue)\n }\n\n reconcile(\n current: this[\"N\"],\n newValue: this[\"C\"] | this[\"T\"],\n parent: AnyObjectNode,\n subpath: string\n ): this[\"N\"] {\n const type = this.determineType(newValue, current.getReconciliationType())\n if (!type) {\n throw fail(this.noMatchMessage(newValue))\n } // can happen in prod builds\n return type.reconcile(current, newValue, parent, subpath)\n }\n\n private noMatchMessage(value: unknown): string {\n const base = `No matching type for union ${this.name}`\n if (!isPlainObject(value)) {\n return base\n }\n const discriminator = (value as { type?: unknown }).type\n if (typeof discriminator !== \"string\") {\n return base\n }\n const baseWithDiscriminator = `${base} for snapshot with type \"${discriminator}\"`\n // If exactly one union member has a literal `type` property matching the\n // snapshot's discriminator, run its validate() so we can append the\n // property-level reasons it didn't match. This converts the bare prod-build\n // \"no matching type\" into something diagnosable (e.g. which field was the\n // wrong type, which required field was missing) without re-bloating the\n // message back to every-member's full describe() output.\n const candidate = this._findCandidateByTypeDiscriminator(discriminator)\n if (!candidate) {\n return baseWithDiscriminator\n }\n const errors = candidate.validate(value as any, [\n { path: \"\", type: candidate }\n ])\n if (errors.length === 0) {\n return baseWithDiscriminator\n }\n return `${baseWithDiscriminator}:\\n ${formatValidationErrorLines(\n errors\n ).join(\"\\n \")}`\n }\n\n // Memoizes the discriminator -> member scan below. Union membership is fixed\n // at construction, so the result for a given `type` string never changes.\n // Without this, validating a config with many elements drawn from a wide\n // pluggable union (e.g. jbrowse's 30+ track/adapter types) re-scans every\n // member — and calls resolveModelType + literal.is() on each — once per\n // element. With it, each distinct discriminator scans once; the rest are\n // O(1) map hits. `undefined` (no match OR ambiguous) is cached too.\n declare private _discriminatorCache?: Map<string, IAnyType | undefined>\n protected _findCandidateByTypeDiscriminator(\n discriminator: string\n ): IAnyType | undefined {\n const cache = (this._discriminatorCache ??= new Map())\n if (cache.has(discriminator)) {\n return cache.get(discriminator)\n }\n const found = this._scanForTypeDiscriminator(discriminator)\n cache.set(discriminator, found)\n return found\n }\n\n protected _scanForTypeDiscriminator(\n discriminator: string\n ): IAnyType | undefined {\n let found: IAnyType | undefined\n for (const t of this.members()) {\n const model = resolveModelType(t)\n if (!model) {\n continue\n }\n const typeProp = (\n model.properties as Record<string, IAnyType | undefined>\n )[\"type\"]\n if (\n !typeProp ||\n !(typeProp.flags & TypeFlags.Literal) ||\n !matchesLiteral(typeProp, discriminator)\n ) {\n continue\n }\n if (found) {\n // Ambiguous (two members declare the same `type` literal). Fall back\n // to the short message rather than picking arbitrarily.\n return undefined\n }\n // Return the original (possibly wrapped) member, not the unwrapped\n // model, so validate()/is() still apply optional defaults and any\n // snapshotProcessor pre-processing.\n found = t\n }\n return found\n }\n\n // True when every member resolves to a model carrying a literal `type`\n // discriminator — i.e. a fully discriminated union, where a snapshot's `type`\n // uniquely identifies the intended member and no untagged catch-all member\n // could also accept it. Cached: membership is fixed at construction.\n declare private _allMembersDiscriminated?: boolean\n protected allMembersDiscriminated(): boolean {\n if (this._allMembersDiscriminated === undefined) {\n this._allMembersDiscriminated = this.computeAllMembersDiscriminated()\n }\n return this._allMembersDiscriminated\n }\n\n protected computeAllMembersDiscriminated(): boolean {\n return this.members().every(t => {\n const model = resolveModelType(t)\n const typeProp =\n model &&\n (model.properties as Record<string, IAnyType | undefined>)[\"type\"]\n return !!typeProp && (typeProp.flags & TypeFlags.Literal) !== 0\n })\n }\n\n determineType(\n value: this[\"C\"] | this[\"T\"],\n reconcileCurrentType: IAnyType | undefined\n ): IAnyType | undefined {\n // try the dispatcher, if defined\n if (this._dispatcher) {\n return this._dispatcher(value)\n }\n\n // fast path: when type checking is disabled, try quick structural matching\n // first. This skips full recursive validation of every property value, a\n // meaningful win for wide model members (e.g. jbrowse config schemas).\n if (!isTypeCheckingEnabled()) {\n const quickMatch = this.tryQuickMatch(value, reconcileCurrentType)\n if (quickMatch) {\n return quickMatch\n }\n }\n\n // find the most accomodating type\n // if we are using reconciliation try the current node type first (fix for #1045)\n if (reconcileCurrentType) {\n if (reconcileCurrentType.is(value)) {\n return reconcileCurrentType\n }\n return this.members().find(\n type => type !== reconcileCurrentType && type.is(value)\n )\n }\n return this.members().find(type => type.is(value))\n }\n\n private tryQuickMatch(\n value: any,\n reconcileCurrentType: IAnyType | undefined\n ): IAnyType | undefined {\n // state tree nodes need full type compatibility checking\n // (e.g., A.is(B.create()) must return false even if snapshots are compatible)\n if (isStateTreeNode(value)) {\n return undefined\n }\n\n // for non-object values, try primitive matching\n if (!isPlainObject(value)) {\n return this.tryMatchPrimitive(value)\n }\n\n // for objects, try structural matching against model types, preferring the\n // reconciliation type (checked first, then skipped in the main pass) so a\n // reconcile keeps its current member when it still fits — without building\n // the reordered candidate list this used to allocate on every call\n if (\n reconcileCurrentType &&\n this.snapshotLooksLikeType(value, reconcileCurrentType)\n ) {\n return reconcileCurrentType\n }\n for (const type of this.members()) {\n if (\n type !== reconcileCurrentType &&\n this.snapshotLooksLikeType(value, type)\n ) {\n return type\n }\n }\n return undefined\n }\n\n private tryMatchPrimitive(value: any): IAnyType | undefined {\n const valueType = typeof value\n for (const type of this.members()) {\n const flags = type.flags\n if (\n (valueType === \"string\" && flags & TypeFlags.String) ||\n (valueType === \"number\" &&\n flags &\n (TypeFlags.Number |\n TypeFlags.Integer |\n TypeFlags.Float |\n TypeFlags.Finite)) ||\n (valueType === \"boolean\" && flags & TypeFlags.Boolean) ||\n (value === null && flags & TypeFlags.Null) ||\n (value === undefined && flags & TypeFlags.Undefined)\n ) {\n return type\n }\n // for literals, check exact value match\n if (flags & TypeFlags.Literal) {\n if (matchesLiteral(type, value)) {\n return type\n }\n }\n }\n return undefined\n }\n\n private snapshotLooksLikeType(value: any, type: IAnyType): boolean {\n // for model types, check if snapshot has all the required property keys\n // and that any literal-typed properties match exactly. Unwrap optional() /\n // snapshotProcessor() / refinement() / late() so wrapped members (e.g.\n // jbrowse config schemas, which are always optional(model)) still match.\n const model = resolveModelType(type)\n if (model) {\n const props = model.properties\n // use cached propertyNames from ModelType instead of Object.keys()\n for (const key of model.propertyNames) {\n const propType = props[key]!\n // `flags` is a recomputed getter on the wrapper types (optional,\n // snapshotProcessor, late, union), so read it once per property\n const flags = propType.flags\n const propValue = value[key]\n\n // check required properties exist and are not undefined\n // (unless the type accepts undefined, which Optional types do)\n if (!(flags & TypeFlags.Optional)) {\n if (!(key in value) || propValue === undefined) {\n return false\n }\n }\n\n // for literal types, verify the value matches exactly\n // this is critical for discriminated unions\n if (flags & TypeFlags.Literal) {\n if (!matchesLiteral(propType, propValue)) {\n return false\n }\n }\n }\n return true\n }\n return false\n }\n\n isValidSnapshot(\n value: this[\"C\"],\n context: IValidationContext\n ): IValidationResult {\n if (this._dispatcher) {\n return this._dispatcher(value).validate(value, context)\n }\n\n // For plain-object snapshots carrying a `type` discriminator, validate only\n // the single member whose literal `type` matches.\n // - Clean validation short-circuits to success only when it is sound to skip\n // the other members: an eager union (first match wins) or a fully\n // discriminated one (no untagged catch-all could also match). A non-eager\n // union with a catch-all must still fall through so ambiguity is counted.\n // - A failure is the definitive, scoped error only when every member is\n // discriminated; otherwise a catch-all could still accept the value, so\n // fall through to full validation.\n const isSnapshotObject = isPlainObject(value) && !isStateTreeNode(value)\n if (isSnapshotObject) {\n const discriminator = (value as { type?: unknown }).type\n if (typeof discriminator === \"string\") {\n const candidate = this._findCandidateByTypeDiscriminator(discriminator)\n if (candidate) {\n const errors = candidate.validate(value, context)\n const cleanAndUnique = errors.length === 0 && this._eager\n if (cleanAndUnique || this.allMembersDiscriminated()) {\n return errors\n }\n }\n }\n }\n\n // for plain-object snapshots, prefer union members whose literal-typed\n // discriminator properties match the value (e.g. {type: \"MsaView\"})\n // so error output is scoped to the intended branch instead of every member\n const members = this.members()\n const candidates = isSnapshotObject\n ? members.filter(t => this.snapshotLooksLikeType(value, t))\n : []\n const typesToValidate = candidates.length > 0 ? candidates : members\n\n const allErrors: IValidationResult[] = []\n let applicableTypes = 0\n for (const type of typesToValidate) {\n const errors = type.validate(value, context)\n if (errors.length === 0) {\n if (this._eager) {\n return typeCheckSuccess()\n } else {\n applicableTypes++\n }\n } else {\n allErrors.push(errors)\n }\n }\n\n if (applicableTypes === 1) {\n return typeCheckSuccess()\n }\n return typeCheckFailure(\n context,\n value,\n \"No type is applicable for the union\"\n ).concat(allErrors.flat())\n }\n\n getSubTypes() {\n return this.members()\n }\n}\n\n// Defaults shared by every union; see the field declarations at the top of the\n// class for why they are not own slots.\nObject.assign(Union.prototype as object, {\n _dispatcher: undefined,\n _eager: true,\n _discriminatorCache: undefined,\n _allMembersDiscriminated: undefined\n})\n\n/**\n * @internal\n * @hidden\n *\n * A union whose membership is read fresh from a thunk on every operation, so\n * members that come into existence after the union was built — a registry of\n * pluggable types whose modules load on demand — still dispatch, validate, and\n * satisfy references. That last one is the reason this exists: reference\n * resolution asks the target type `isAssignableFrom(node.type)` through the\n * identifier cache, and a membership list frozen at construction would reject\n * every late-loaded member's instances.\n *\n * Every membership-derived cache the base class keeps is bypassed here: flags\n * and the folded name are recomputed per read, and the discriminator scan is\n * uncached so a miss stays retryable once the missing member registers. A hit\n * for a given discriminator is assumed stable — registering two members with\n * the same `type` literal at different times can leave a stale unambiguous\n * answer where the base class would have reported ambiguity.\n */\nclass DynamicUnion extends Union {\n private readonly _members: () => IAnyType[]\n\n // `declare` + the setter below, not a field: a field initializer would run\n // after super() and clobber the name the Union constructor assigns through\n // the overridden setter.\n declare private _explicitName?: string\n\n constructor(members: () => IAnyType[], options: UnionOptions) {\n super([], options)\n this._members = members\n }\n\n protected override members() {\n return this._members()\n }\n\n override get flags(): TypeFlags {\n return this.foldFlags()\n }\n\n override get name(): string {\n return this._explicitName !== undefined\n ? this._explicitName\n : this.computeName()\n }\n\n override set name(value: string) {\n this._explicitName = value\n }\n\n protected override _findCandidateByTypeDiscriminator(discriminator: string) {\n return this._scanForTypeDiscriminator(discriminator)\n }\n\n protected override allMembersDiscriminated() {\n return this.computeAllMembersDiscriminated()\n }\n}\n\n// Structurally identical unions are the same object. A union built without\n// options is a pure function of its member list — `_types` is the members,\n// `_flags`, `_name`, `_discriminatorCache` and `_allMembersDiscriminated` are\n// all folds over them, and `_dispatcher`/`_eager` come only from the options\n// overload, which is never interned because a dispatcher closure is not\n// comparable. Types carry no parent, so one object can serve every use.\n//\n// jbrowse builds a union per config slot — ~20k per session load — from a\n// handful of module-level singletons, so the member tuples number in the\n// dozens. A trie of WeakMaps keyed on member identity keeps dynamically built\n// members collectable: a node is reachable only through its own key, and the\n// union it terminates is reachable only through the node.\ninterface UnionInternNode {\n union?: Union\n next?: WeakMap<IAnyType, UnionInternNode>\n}\n\nconst unionInternRoot: UnionInternNode = {}\n\nfunction internUnion(types: IAnyType[]): Union {\n let node = unionInternRoot\n for (const type of types) {\n const level = (node.next ??= new WeakMap())\n const existing = level.get(type)\n if (existing) {\n node = existing\n } else {\n node = {}\n level.set(type, node)\n }\n }\n return (node.union ??= new Union(types))\n}\n\n/**\n * Transform _NotCustomized | _NotCustomized... to _NotCustomized, _NotCustomized | A | B to A | B\n * @hidden\n */\nexport type _CustomCSProcessor<T> =\n Exclude<T, _NotCustomized> extends never\n ? _NotCustomized\n : Exclude<T, _NotCustomized>\n\n/** @hidden */\nexport interface ITypeUnion<C, S, T> extends IType<\n _CustomCSProcessor<C>,\n _CustomCSProcessor<S>,\n T\n> {}\n\n// Variadic-tuple signatures in place of the 2-to-9-member overload block that\n// `scripts/generate-union-types.js` used to emit: the member types are captured\n// as a tuple, so the result stays precise past nine members instead of falling\n// through to the `IAnyType` signature below.\n//\n// The member projections go through a mapped tuple indexed by `number` rather\n// than the direct `Types[number][\"CreationType\"]`. Both describe the same set,\n// but the direct form is one indexed access over a *union* of type parameters,\n// which TypeScript leaves deferred; mapping first resolves each member in its\n// own tuple position, so the result reduces to a plain union.\n/** @hidden */\nexport type _UnionMembersCreationType<Types extends readonly IAnyType[]> = {\n [K in keyof Types]: Types[K][\"CreationType\"]\n}[number]\n/** @hidden */\nexport type _UnionMembersSnapshotType<Types extends readonly IAnyType[]> = {\n [K in keyof Types]: Types[K][\"SnapshotType\"]\n}[number]\n/** @hidden */\nexport type _UnionMembersTypeWithoutSTN<Types extends readonly IAnyType[]> = {\n [K in keyof Types]: Types[K][\"TypeWithoutSTN\"]\n}[number]\n\n// The two-member form keeps one type parameter per member, ahead of the\n// variadic signatures. Reducing the mapped tuple still leaves each member's C/S/T\n// as an indexed access, and when a member is itself a bare type parameter —\n// `union(reference(schema), schema)` inside a generic function, which is how\n// jbrowse's `ConfigurationReference` is written — `S[\"CreationType\"]` is a\n// deferred lookup that TypeScript will not relate to the `SnapshotIn<S>` such a\n// function declares as its return. Inferring C/S/T through `IType` reads them\n// off the argument's constraint instead of deferring a lookup, so the result is\n// a type the checker can relate — at the cost of a member that is itself a bare\n// parameter contributing its constraint's C/S/T rather than its own. Two members\n// is where such call sites sit (`maybe`/`maybeNull` included); wider unions keep\n// the variadic precision.\nexport function union<CA, SA, TA, CB, SB, TB>(\n A: IType<CA, SA, TA>,\n B: IType<CB, SB, TB>\n): ITypeUnion<CA | CB, SA | SB, TA | TB>\nexport function union<Types extends [IAnyType, ...IAnyType[]]>(\n ...types: Types\n): ITypeUnion<\n _UnionMembersCreationType<Types>,\n _UnionMembersSnapshotType<Types>,\n _UnionMembersTypeWithoutSTN<Types>\n>\nexport function union<Types extends [IAnyType, ...IAnyType[]]>(\n options: UnionOptions,\n ...types: Types\n): ITypeUnion<\n _UnionMembersCreationType<Types>,\n _UnionMembersSnapshotType<Types>,\n _UnionMembersTypeWithoutSTN<Types>\n>\nexport function union<Types extends readonly IAnyType[]>(\n options: UnionOptions & { members: () => Types }\n): ITypeUnion<\n _UnionMembersCreationType<Types>,\n _UnionMembersSnapshotType<Types>,\n _UnionMembersTypeWithoutSTN<Types>\n>\n\n// members only known as IAnyType[], e.g. a spread array: nothing to infer\nexport function union(...types: IAnyType[]): IAnyType\nexport function union(\n dispatchOrType: UnionOptions | IAnyType,\n ...otherTypes: IAnyType[]\n): IAnyType\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 * Passing `members: () => Type[]` in the options (with no positional member\n * types) creates a union whose membership is re-read from the thunk on every\n * operation, so types registered after construction — e.g. from a lazily\n * loaded module — participate in dispatch, validation and reference\n * resolution. Pair it with a `dispatcher` for snapshot dispatch and a `name`\n * for stable error messages.\n *\n * @param optionsOrType\n * @param otherTypes\n * @returns\n */\nexport function union(...args: (UnionOptions | IAnyType)[]): IAnyType {\n // One rest array, handed straight to the Union in the common case. Splitting\n // the leading argument out — whether by a `(first, ...rest)` signature that\n // rebuilds `[first, ...rest]`, or by `rest.unshift(first)` — allocates a\n // second array per union, and jbrowse builds one union per config slot. (The\n // `unshift` form is worse still: V8 inlines the spread and calls out to the\n // builtin, so it measured 3x the spread on a two-member union.) Only the\n // options overload, which nothing hot uses, pays for a copy.\n const firstIsType = isType(args[0])\n const options = firstIsType ? undefined : (args[0] as UnionOptions)\n const types = (firstIsType ? args : args.slice(1)) as IAnyType[]\n // the name is folded from the members on demand — see Union.computeName\n\n // check all options\n if (devMode()) {\n if (options) {\n assertArg(\n options,\n o => isPlainObject(o),\n \"object { eager?: boolean, dispatcher?: Function, members?: Function, name?: string }\",\n 1\n )\n }\n types.forEach((type, i) => {\n assertIsType(type, options ? i + 2 : i + 1)\n })\n }\n if (options?.members !== undefined) {\n if (types.length > 0) {\n throw fail(\n \"union(): the members option cannot be combined with positional member types\"\n )\n }\n return new DynamicUnion(options.members, options)\n }\n return options === undefined ? internUnion(types) : new Union(types, options)\n}\n\n/**\n * Returns if a given value represents a union type.\n *\n * Like every `isXType` guard it reads the type's flags, which wrappers and\n * unions inherit from what they hold, so it is also true for a type that wraps\n * or unions one. Use {@link unwrapType} to get at the type itself.\n *\n * @param type\n * @returns\n */\nexport function isUnionType(type: IAnyType): boolean {\n return isType(type) && (type.flags & TypeFlags.Union) > 0\n}\n\n/**\n * Returns the member types of a union, seeing through the wrappers\n * {@link unwrapType} does: `isUnionType` is also true for e.g. an\n * optional-of-union.\n *\n * @param type a type for which `isUnionType` is true\n * @returns the array of member types of the underlying union\n */\nexport function getUnionSubtypes(type: IAnyType): IAnyType[] {\n if (!isUnionType(type)) {\n throw fail(\"expected a union type\")\n }\n const union = unwrapType(type)\n if (!(union instanceof Union)) {\n throw fail(\"could not extract subtypes from union type\")\n }\n return union.getSubTypes()\n}\n","import {\n type AnyObjectNode,\n BaseType,\n type ExtractCSTWithSTN,\n type IAnyType,\n type IType,\n type IValidationContext,\n type IValidationResult,\n TypeFlags,\n asModelType,\n assertIsType,\n devMode,\n fail,\n isStateTreeNode,\n isType,\n typeCheckSuccess,\n typecheckInternal\n} from \"../../internal.ts\"\n\ntype IFunctionReturn<T> = () => T\n\ntype IOptionalValue<C, T> = C | IFunctionReturn<C | T>\n\n/** @hidden */\nexport type ValidOptionalValue = string | boolean | number | null | undefined\n\n/** @hidden */\nexport type ValidOptionalValues = [ValidOptionalValue, ...ValidOptionalValue[]]\n\n/**\n * @hidden\n * @internal\n */\nexport class OptionalValue<\n IT extends IAnyType,\n OptionalVals extends ValidOptionalValues\n> extends BaseType<\n IT[\"CreationType\"] | OptionalVals[number],\n IT[\"SnapshotType\"],\n IT[\"TypeWithoutSTN\"]\n> {\n private _flags?: TypeFlags\n\n // memoized once stable; see the same guard on Union.flags for why `Late` in\n // the folded result is the exact test for \"may still change\"\n get flags(): TypeFlags {\n const cached = this._flags\n if (cached !== undefined) {\n return cached\n }\n const result = this._subtype.flags | TypeFlags.Optional\n if (!(result & TypeFlags.Late)) {\n this._flags = result\n }\n return result\n }\n\n constructor(\n private readonly _subtype: IT,\n private readonly _defaultValue: IOptionalValue<\n IT[\"CreationType\"],\n IT[\"Type\"]\n >,\n readonly optionalValues: OptionalVals\n ) {\n // no name argument: reading `_subtype.name` here would force the name of\n // whatever is wrapped, and jbrowse wraps a union per config slot\n super()\n }\n\n protected override computeName(): string {\n return this._subtype.name\n }\n\n override describe() {\n return `${this._subtype.describe()}?`\n }\n\n instantiate(\n parent: AnyObjectNode | null,\n subpath: string,\n environment: any,\n initialValue: this[\"C\"] | this[\"T\"]\n ): this[\"N\"] {\n if (this.optionalValues.includes(initialValue)) {\n const defaultInstanceOrSnapshot = this.getDefaultInstanceOrSnapshot()\n return this._subtype.instantiate(\n parent,\n subpath,\n environment,\n defaultInstanceOrSnapshot\n )\n }\n return this._subtype.instantiate(parent, subpath, environment, initialValue)\n }\n\n reconcile(\n current: this[\"N\"],\n newValue: this[\"C\"] | this[\"T\"],\n parent: AnyObjectNode,\n subpath: string\n ): this[\"N\"] {\n return this._subtype.reconcile(\n current,\n !this.optionalValues.includes(newValue) && this._subtype.is(newValue)\n ? newValue\n : this.getDefaultInstanceOrSnapshot(),\n parent,\n subpath\n )\n }\n\n getDefaultInstanceOrSnapshot(): this[\"C\"] | this[\"T\"] {\n const defaultValue = this._defaultValue\n if (typeof defaultValue !== \"function\") {\n // static values are already snapshots, checked once by types.optional\n return defaultValue\n }\n const generated = (defaultValue as IFunctionReturn<this[\"C\"] | this[\"T\"]>)()\n // generator functions must always be rechecked just in case\n typecheckInternal(this, generated)\n return generated\n }\n\n isValidSnapshot(\n value: this[\"C\"],\n context: IValidationContext\n ): IValidationResult {\n // defaulted values can be skipped\n if (this.optionalValues.includes(value)) {\n return typeCheckSuccess()\n }\n // bounce validation to the sub-type\n return this._subtype.validate(value, context)\n }\n\n override isAssignableFrom(type: IAnyType) {\n return this._subtype.isAssignableFrom(type)\n }\n\n getSubTypes() {\n return this._subtype\n }\n}\n\n/** @hidden */\nexport type OptionalDefaultValueOrFunction<IT extends IAnyType> =\n | IT[\"CreationType\"]\n | IT[\"SnapshotType\"]\n | (() => ExtractCSTWithSTN<IT>)\n\n/** @hidden */\nexport interface IOptionalIType<\n IT extends IAnyType = IAnyType,\n OptionalVals extends ValidOptionalValues = ValidOptionalValues\n> extends IType<\n IT[\"CreationType\"] | OptionalVals[number],\n IT[\"SnapshotType\"],\n IT[\"TypeWithoutSTN\"]\n> {\n getDefaultInstanceOrSnapshot(): IT[\"CreationType\"] | IT[\"SnapshotType\"]\n}\n\nfunction checkOptionalPreconditions<IT extends IAnyType>(\n type: IAnyType,\n defaultValueOrFunction: OptionalDefaultValueOrFunction<IT>\n) {\n // make sure we never pass direct instances. A node is always an object, so\n // the typeof narrows first: most defaults are primitives, and reading\n // `$treenode` off a string or a number is a megamorphic miss that this runs\n // once per config slot.\n if (\n typeof defaultValueOrFunction === \"object\" &&\n isStateTreeNode(defaultValueOrFunction)\n ) {\n throw fail(\n \"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 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\nexport function optional<IT extends IAnyType>(\n type: IT,\n defaultValueOrFunction: OptionalDefaultValueOrFunction<IT>\n): IOptionalIType<IT, [undefined]>\nexport function optional<\n IT extends IAnyType,\n OptionalVals extends ValidOptionalValues\n>(\n type: IT,\n defaultValueOrFunction: OptionalDefaultValueOrFunction<IT>,\n optionalValues: OptionalVals\n): IOptionalIType<IT, OptionalVals>\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 */\nexport function optional<\n IT extends IAnyType,\n OptionalVals extends ValidOptionalValues\n>(\n type: IT,\n defaultValueOrFunction: OptionalDefaultValueOrFunction<IT>,\n optionalValues?: OptionalVals\n): IOptionalIType<IT, OptionalVals> {\n checkOptionalPreconditions(type, defaultValueOrFunction)\n\n return new OptionalValue(\n type,\n defaultValueOrFunction,\n optionalValues ? optionalValues : undefinedAsOptionalValues\n )\n}\n\nconst undefinedAsOptionalValues: [undefined] = [undefined]\n\n/**\n * Returns if a value represents an optional type.\n *\n * Like every `isXType` guard it reads the type's flags, which wrappers and\n * unions inherit from what they hold, so it is also true for a type that wraps\n * or unions one. Use {@link unwrapType} to get at the type itself.\n *\n * @param type\n * @returns\n */\nexport function isOptionalType(type: IAnyType): boolean {\n return isType(type) && (type.flags & TypeFlags.Optional) > 0\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null\n}\n\n/**\n * Compare a child snapshot to a stripped-default's reference snapshot: identity\n * for primitives, structural for objects/arrays.\n *\n * Walks the two snapshots in parallel and bails at the first difference. The\n * previous implementation compared `JSON.stringify(a) === JSON.stringify(b)`\n * behind a size guard, which is O(whole snapshot) on both sides — plus two\n * string allocations — even when the very first key differs. That is the normal\n * case for an identified sub-model: its snapshot has exactly the same shape as\n * the default and differs only in the identifier, so the size guard never fires\n * and every `getSnapshot` of the parent serialized both trees just to answer\n * \"no\".\n *\n * Snapshots are frozen, acyclic, JSON-ish plain data, so a plain recursive walk\n * is safe. Key order is compared too, matching what stringify comparison did:\n * the point is to answer \"is this still the default\", and the only unsafe answer\n * is a false positive (a key gets dropped from the snapshot that shouldn't be),\n * so where this can't reproduce stringify exactly — `{a: undefined}` vs\n * `{b: undefined}`, or `NaN` nested in a frozen value, both of which stringify\n * flattened into equal text — it errs toward \"not equal\" and simply keeps the\n * key. Neither shape is reachable from a model snapshot, whose key set and order\n * are fixed by its type.\n */\nfunction defaultSnapshotEquals(a: unknown, b: unknown): boolean {\n if (a === b) {\n return true\n }\n if (\n typeof a !== \"object\" ||\n a === null ||\n typeof b !== \"object\" ||\n b === null\n ) {\n return false\n }\n const aIsArray = Array.isArray(a)\n if (aIsArray !== Array.isArray(b)) {\n return false\n }\n if (aIsArray) {\n const arrayA = a as unknown[]\n const arrayB = b as unknown[]\n if (arrayA.length !== arrayB.length) {\n return false\n }\n for (let i = 0; i < arrayA.length; i++) {\n if (!defaultSnapshotEquals(arrayA[i], arrayB[i])) {\n return false\n }\n }\n return true\n }\n const objectA = a as Record<string, unknown>\n const objectB = b as Record<string, unknown>\n const keysA = Object.keys(objectA)\n const keysB = Object.keys(objectB)\n if (keysA.length !== keysB.length) {\n return false\n }\n for (let i = 0; i < keysA.length; i++) {\n const key = keysA[i]!\n if (\n key !== keysB[i] ||\n !defaultSnapshotEquals(objectA[key], objectB[key])\n ) {\n return false\n }\n }\n return true\n}\n\n/**\n * An optional type that additionally omits its key from a parent model's\n * snapshot when the value equals the (snapshotted) default. The comparison is\n * against the default *snapshot* — i.e. the subtype is instantiated with the\n * default once and its post-processed snapshot is cached — so a default whose\n * normalized form gains fields (e.g. a fileLocation gaining `locationType`)\n * still strips correctly.\n *\n * @hidden\n * @internal\n */\nexport class StripDefaultValue<\n IT extends IAnyType,\n OptionalVals extends ValidOptionalValues\n> extends OptionalValue<IT, OptionalVals> {\n // all three live on the prototype until a strip actually happens; jbrowse\n // builds one of these per config slot and most are never serialized. See\n // `BaseType.isType`.\n declare private _defaultSnapshot?: { value: IT[\"SnapshotType\"] }\n declare private _identifierAttribute?: string | null\n declare private _equalsDefaultCache?: WeakMap<object, boolean>\n\n private equalsDefault(snapshot: unknown, defaultSnapshot: unknown): boolean {\n let identifierAttribute = this._identifierAttribute\n if (identifierAttribute === undefined) {\n // null when not wrapping an identified model; an unresolved late member\n // also lands here, which only costs the short-circuit below\n identifierAttribute =\n asModelType(this.getSubTypes())?.identifierAttribute ?? null\n this._identifierAttribute = identifierAttribute\n }\n // an identified model's snapshot normally has the same shape as the default\n // and differs only here, so answering from one key beats walking every key\n // (including nested objects) until the walk reaches it\n return identifierAttribute !== null &&\n isRecord(snapshot) &&\n isRecord(defaultSnapshot) &&\n snapshot[identifierAttribute] !== defaultSnapshot[identifierAttribute]\n ? false\n : defaultSnapshotEquals(snapshot, defaultSnapshot)\n }\n\n shouldStripFromSnapshot(snapshot: IT[\"SnapshotType\"]): boolean {\n if (!this._defaultSnapshot) {\n // instantiate the subtype detached with the default and read the node's\n // snapshot, which normalizes (fills model defaults, applies the subtype's\n // own postProcess). Cached on the (singleton) type after first use.\n const node = this.getSubTypes().instantiate(\n null,\n \"\",\n undefined,\n this.getDefaultInstanceOrSnapshot()\n )\n this._defaultSnapshot = { value: node.snapshot }\n }\n const defaultSnapshot = this._defaultSnapshot.value\n let result: boolean\n if (isRecord(snapshot)) {\n // a child node's snapshot is a keepAlive computed, so a stable reference\n // means unchanged content: the same object always gets the same answer\n let cache = this._equalsDefaultCache\n if (!cache) {\n cache = new WeakMap()\n this._equalsDefaultCache = cache\n }\n const cached = cache.get(snapshot)\n if (cached === undefined) {\n result = this.equalsDefault(snapshot, defaultSnapshot)\n cache.set(snapshot, result)\n } else {\n result = cached\n }\n } else {\n result = defaultSnapshotEquals(snapshot, defaultSnapshot)\n }\n return result\n }\n}\n\nObject.assign(StripDefaultValue.prototype as object, {\n _defaultSnapshot: undefined,\n _identifierAttribute: undefined,\n _equalsDefaultCache: undefined\n})\n\n/**\n * Whether `type` is a strip-default optional whose current child `snapshot`\n * equals its default and should therefore be omitted from the parent model's\n * snapshot. Used by `ModelType.getSnapshot`.\n *\n * @hidden\n * @internal\n */\nexport function shouldStripChildFromSnapshot(\n type: IAnyType,\n snapshot: unknown\n): boolean {\n return (\n type instanceof StripDefaultValue && type.shouldStripFromSnapshot(snapshot)\n )\n}\n\n/**\n * `types.stripDefault` - Like `types.optional`, but the property is omitted from\n * a parent model's snapshot entirely when its value equals the default (instead\n * of being serialized with the default value). Lets a model produce minimal\n * snapshots without a bespoke `postProcessSnapshot`.\n *\n * @param type\n * @param defaultValueOrFunction\n * @returns\n */\nexport function stripDefault<IT extends IAnyType>(\n type: IT,\n defaultValueOrFunction: OptionalDefaultValueOrFunction<IT>\n): IOptionalIType<IT, [undefined]> {\n checkOptionalPreconditions(type, defaultValueOrFunction)\n return new StripDefaultValue(\n type,\n defaultValueOrFunction,\n undefinedAsOptionalValues\n )\n}\n","import {\n type IAnyType,\n type IType,\n assertIsType,\n nullType,\n optional,\n undefinedType,\n union\n} from \"../../internal.ts\"\n\nconst optionalUndefinedType = optional(undefinedType, undefined)\nconst optionalNullType = optional(nullType, null)\n\n/** @hidden */\nexport interface IMaybeIType<IT extends IAnyType, C, O> extends IType<\n IT[\"CreationType\"] | C,\n IT[\"SnapshotType\"] | O,\n IT[\"TypeWithoutSTN\"] | O\n> {}\n\n/** @hidden */\nexport interface IMaybe<IT extends IAnyType> extends IMaybeIType<\n IT,\n undefined,\n undefined\n> {}\n\n/** @hidden */\nexport interface IMaybeNull<IT extends IAnyType> extends IMaybeIType<\n IT,\n null | undefined,\n null\n> {}\n\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 */\nexport function maybe<IT extends IAnyType>(type: IT): IMaybe<IT> {\n assertIsType(type, 1)\n\n return union(type, optionalUndefinedType)\n}\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 */\nexport function maybeNull<IT extends IAnyType>(type: IT): IMaybeNull<IT> {\n assertIsType(type, 1)\n\n return union(type, optionalNullType)\n}\n","import {\n type AnyObjectNode,\n BaseType,\n type ExtractNodeType,\n type IAnyType,\n type IValidationContext,\n type IValidationResult,\n TypeFlags,\n cannotDetermineSubtype,\n devMode,\n fail,\n isType,\n typeCheckSuccess\n} from \"../../internal.ts\"\n\nclass Late<IT extends IAnyType> extends BaseType<\n IT[\"CreationType\"],\n IT[\"SnapshotType\"],\n IT[\"TypeWithoutSTN\"],\n ExtractNodeType<IT>\n> {\n private _subType?: IT\n\n get flags() {\n return (this._subType ? this._subType.flags : 0) | TypeFlags.Late\n }\n\n getSubType(mustSucceed: true): IT\n getSubType(mustSucceed: false): IT | undefined\n getSubType(mustSucceed: boolean): IT | undefined {\n if (!this._subType) {\n let t: IT | undefined\n try {\n t = this._definition()\n } catch (e) {\n // a self-referencing definition can read its binding before it is\n // initialized; that is \"not defined yet\", like returning undefined\n if (!(e instanceof ReferenceError)) {\n throw e\n }\n }\n if (mustSucceed && t === undefined) {\n throw fail(\n \"Late type seems to be used too early, the definition (still) returns undefined\"\n )\n }\n if (t) {\n if (devMode() && !isType(t)) {\n throw fail(\n \"Failed to determine subtype, make sure types.late returns a type definition.\"\n )\n }\n this._subType = t\n }\n }\n return this._subType\n }\n\n constructor(\n private readonly _definition: () => IT,\n name?: string\n ) {\n super(name)\n }\n\n // the unnamed form is named after the definition's source text, which is\n // only worth building if something reads it\n protected override computeName(): string {\n return `late(${this._definition.toString()})`\n }\n\n instantiate(\n parent: AnyObjectNode | null,\n subpath: string,\n environment: any,\n initialValue: this[\"C\"] | this[\"T\"]\n ): this[\"N\"] {\n return this.getSubType(true).instantiate(\n parent,\n subpath,\n environment,\n initialValue\n ) as any\n }\n\n reconcile(\n current: this[\"N\"],\n newValue: this[\"C\"] | this[\"T\"],\n parent: AnyObjectNode,\n subpath: string\n ): this[\"N\"] {\n return this.getSubType(true).reconcile(\n current,\n newValue,\n parent,\n subpath\n ) as any\n }\n\n override describe() {\n const t = this.getSubType(false)\n return t ? t.name : \"<unknown late type>\"\n }\n\n isValidSnapshot(\n value: this[\"C\"],\n context: IValidationContext\n ): IValidationResult {\n const t = this.getSubType(false)\n if (!t) {\n // See #916; the variable the definition closure is pointing to wasn't defined yet, so can't be evaluted yet here\n return typeCheckSuccess()\n }\n return t.validate(value, context)\n }\n\n override isAssignableFrom(type: IAnyType) {\n const t = this.getSubType(false)\n return t ? t.isAssignableFrom(type) : false\n }\n\n getSubTypes() {\n return this.getSubType(false) ?? cannotDetermineSubtype\n }\n}\n\nexport function late<T extends IAnyType>(type: () => T): T\nexport function late<T extends IAnyType>(name: string, type: () => T): T\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<typeof Node>\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 */\nexport function late(\n nameOrType: string | (() => IAnyType),\n maybeType?: () => IAnyType\n): IAnyType {\n const name = typeof nameOrType === \"string\" ? nameOrType : undefined\n const type = typeof nameOrType === \"string\" ? maybeType! : nameOrType\n if (devMode()) {\n if (!(typeof type === \"function\" && type.length === 0)) {\n throw fail(\n `Invalid late type, expected a function with zero arguments that returns a type, got: ${\n type\n }`\n )\n }\n }\n return new Late(type, name)\n}\n\n/**\n * Returns if a given value represents a late type.\n *\n * Like every `isXType` guard it reads the type's flags, which wrappers and\n * unions inherit from what they hold, so it is also true for a type that wraps\n * or unions one. Use {@link unwrapType} to get at the type itself.\n *\n * @param type\n * @returns\n */\nexport function isLateType(type: IAnyType): boolean {\n return isType(type) && (type.flags & TypeFlags.Late) > 0\n}\n","import { type IObservableArray, action, observable, when } from \"mobx\"\n\nimport {\n type AnyNode,\n type AnyObjectNode,\n type IAnyType,\n type IType,\n type IValidationContext,\n type IValidationResult,\n SimpleType,\n TypeFlags,\n createScalarNode,\n deepFreeze,\n isSerializable,\n typeCheckFailure,\n typeCheckSuccess\n} from \"../../internal.ts\"\n\ninterface LazyOptions<T extends IType<any, any, any>, U> {\n loadType: () => Promise<T>\n shouldLoadPredicate: (parent: U) => boolean\n}\n\nexport function lazy<T extends IType<any, any, any>, U>(\n name: string,\n options: LazyOptions<T, U>\n): T {\n // a lazy type stands in for the type it loads, down to that type's own\n // methods (a model's `.props`, say), which the placeholder does not have\n return new Lazy(name, options) as unknown as T\n}\n\n/**\n * @internal\n * @hidden\n */\nexport class Lazy<T extends IType<any, any, any>, U> extends SimpleType<\n T[\"CreationType\"],\n T[\"SnapshotType\"],\n T[\"TypeWithoutSTN\"]\n> {\n readonly flags = TypeFlags.Lazy\n\n private loadedType: T | null = null\n private pendingNodeList: IObservableArray<AnyNode> = observable.array()\n\n constructor(\n name: string,\n private readonly options: LazyOptions<T, U>\n ) {\n super(name)\n\n when(\n () =>\n this.pendingNodeList.length > 0 &&\n this.pendingNodeList.some(\n node =>\n node.isAlive &&\n this.options.shouldLoadPredicate(\n node.parent ? node.parent.value : null\n )\n ),\n () => {\n this.options.loadType().then(\n action((type: T) => {\n this.loadedType = type\n this.pendingNodeList.forEach(node => {\n if (!node.parent) {\n return\n }\n if (!this.loadedType) {\n return\n }\n\n node.parent.applyPatches([\n {\n op: \"replace\",\n path: `/${node.subpath}`,\n value: node.snapshot\n }\n ])\n })\n })\n )\n }\n )\n }\n\n override describe() {\n return `<lazy ${this.name}>`\n }\n\n instantiate(\n parent: AnyObjectNode | null,\n subpath: string,\n environment: any,\n value: this[\"C\"]\n ): this[\"N\"] {\n if (this.loadedType) {\n return this.loadedType.instantiate(\n parent,\n subpath,\n environment,\n value\n ) as this[\"N\"]\n }\n\n const node = createScalarNode(\n this,\n parent,\n subpath,\n environment,\n deepFreeze(value)\n )\n this.pendingNodeList.push(node)\n\n when(\n () => !node.isAlive,\n () => {\n // guard the index: splice(-1, 1) would drop an unrelated pending node\n const index = this.pendingNodeList.indexOf(node)\n if (index >= 0) {\n this.pendingNodeList.splice(index, 1)\n }\n }\n )\n\n return node\n }\n\n isValidSnapshot(\n value: this[\"C\"],\n context: IValidationContext\n ): IValidationResult {\n if (this.loadedType) {\n return this.loadedType.validate(value, context)\n }\n if (!isSerializable(value)) {\n return typeCheckFailure(\n context,\n value,\n \"Value is not serializable and cannot be lazy\"\n )\n }\n return typeCheckSuccess()\n }\n\n override reconcile(\n current: this[\"N\"],\n value: this[\"C\"],\n parent: AnyObjectNode,\n subpath: string\n ): this[\"N\"] {\n if (this.loadedType) {\n // a node created after load carries the loaded type: let it reconcile so\n // the instance survives applySnapshot instead of dying on every write\n const loaded: IAnyType = this.loadedType\n const currentType: IAnyType = current.type\n if (currentType === loaded) {\n return this.loadedType.reconcile(\n current,\n value,\n parent,\n subpath\n ) as this[\"N\"]\n }\n current.die()\n return this.loadedType.instantiate(\n parent,\n subpath,\n parent.environment,\n value\n ) as this[\"N\"]\n }\n return super.reconcile(current, value, parent, subpath)\n }\n}\n","import {\n type AnyObjectNode,\n type IAnyType,\n type IType,\n type IValidationContext,\n type IValidationResult,\n SimpleType,\n TypeFlags,\n createScalarNode,\n deepFreeze,\n isSerializable,\n isType,\n optional,\n typeCheckFailure,\n typeCheckSuccess\n} from \"../../internal.ts\"\n\n/**\n * @internal\n * @hidden\n */\nexport class Frozen<T> extends SimpleType<T, T, T> {\n readonly flags = TypeFlags.Frozen\n\n constructor(private subType?: IAnyType) {\n super(subType ? undefined : \"frozen\")\n }\n\n protected override computeName(): string {\n return `frozen(${this.subType!.name})`\n }\n\n override describe() {\n return \"<any immutable value>\"\n }\n\n instantiate(\n parent: AnyObjectNode | null,\n subpath: string,\n environment: any,\n value: this[\"C\"]\n ): this[\"N\"] {\n // create the node\n return createScalarNode(\n this,\n parent,\n subpath,\n environment,\n deepFreeze(value)\n )\n }\n\n isValidSnapshot(\n value: this[\"C\"],\n context: IValidationContext\n ): IValidationResult {\n if (!isSerializable(value)) {\n return typeCheckFailure(\n context,\n value,\n \"Value is not serializable and cannot be frozen\"\n )\n }\n if (this.subType) {\n return this.subType.validate(value, context)\n }\n return typeCheckSuccess()\n }\n}\n\nconst untypedFrozenInstance = new Frozen()\n\nexport function frozen<C>(subType: IType<C, any, any>): IType<C, C, C>\nexport function frozen<T>(defaultValue: T): IType<T | undefined | null, T, T>\nexport function frozen<T = any>(): IType<T, T, T> // do not assume undefined by default, let the user specify it if needed\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<TypeScriptType>()` - 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<Point>()\n * })\n * ```\n *\n * @param defaultValueOrType\n * @returns\n */\nexport function frozen(arg?: any): any {\n if (arguments.length === 0) {\n return untypedFrozenInstance\n } else if (isType(arg)) {\n return new Frozen(arg)\n } else {\n return optional(untypedFrozenInstance, arg)\n }\n}\n\n/**\n * Returns if a given value represents a frozen type.\n *\n * Like every `isXType` guard it reads the type's flags, which wrappers and\n * unions inherit from what they hold, so it is also true for a type that wraps\n * or unions one. Use {@link unwrapType} to get at the type itself.\n *\n * @param type\n * @returns\n */\nexport function isFrozenType(type: IAnyType): boolean {\n return isType(type) && (type.flags & TypeFlags.Frozen) > 0\n}\n","import {\n type AnyNode,\n type AnyObjectNode,\n Hook,\n type IAnyComplexType,\n type IAnyStateTreeNode,\n type IAnyType,\n type IDisposer,\n type IMaybe,\n type IStateTreeNode,\n type IType,\n type IValidationContext,\n type IValidationResult,\n NodeLifeCycle,\n type ReferenceIdentifier,\n SimpleType,\n TypeFlags,\n applyPatch,\n assertIsType,\n createScalarNode,\n devMode,\n fail,\n getIdentifier,\n getStateTreeNode,\n isModelType,\n isStateTreeNode,\n isType,\n isValidIdentifier,\n maybe,\n normalizeIdentifier,\n typeCheckFailure,\n typeCheckSuccess\n} from \"../../internal.ts\"\n\nexport type OnReferenceInvalidatedEvent<STN extends IAnyStateTreeNode> = {\n parent: IAnyStateTreeNode\n invalidTarget: STN | undefined\n invalidId: ReferenceIdentifier\n replaceRef: (newRef: STN | null | undefined) => void\n removeRef: () => void\n cause: \"detach\" | \"destroy\" | \"invalidSnapshotReference\"\n}\n\nexport type OnReferenceInvalidated<STN extends IAnyStateTreeNode> = (\n event: OnReferenceInvalidatedEvent<STN>\n) => void\n\nfunction getInvalidationCause(hook: Hook): \"detach\" | \"destroy\" | undefined {\n switch (hook) {\n case Hook.beforeDestroy:\n return \"destroy\"\n case Hook.beforeDetach:\n return \"detach\"\n default:\n return undefined\n }\n}\n\n/** @hidden */\nexport type ReferenceT<IT extends IAnyType> = IT[\"TypeWithoutSTN\"] &\n IStateTreeNode<IReferenceType<IT>>\n\nclass StoredReference<IT extends IAnyType> {\n readonly identifier!: ReferenceIdentifier\n node!: AnyNode\n\n private resolvedReference?: {\n node: AnyObjectNode\n lastCacheModification: string\n }\n\n constructor(\n value: ReferenceT<IT> | ReferenceIdentifier,\n private readonly targetType: IT\n ) {\n if (isValidIdentifier(value)) {\n this.identifier = value\n } else if (isStateTreeNode(value)) {\n const targetNode = getStateTreeNode(value)\n if (!targetNode.identifierAttribute) {\n throw fail(\n `Can only store references with a defined identifier attribute.`\n )\n }\n const id = targetNode.unnormalizedIdentifier\n if (id === null || id === undefined) {\n throw fail(\n `Can only store references to tree nodes with a defined identifier.`\n )\n }\n this.identifier = id\n } else {\n throw fail(\n `Can only store references to tree nodes or identifiers, got: '${value}'`\n )\n }\n }\n\n private updateResolvedReference(node: AnyNode) {\n const normalizedId = normalizeIdentifier(this.identifier)\n const root = node.root\n const lastCacheModification =\n root.identifierCache!.getLastCacheModificationPerId(normalizedId)\n if (\n this.resolvedReference?.lastCacheModification !== lastCacheModification\n ) {\n const { targetType } = this\n // reference was initialized with the identifier of the target\n\n const target = root.identifierCache!.resolve(targetType, normalizedId)\n\n if (!target) {\n throw new InvalidReferenceError(\n `[mobx-state-tree] Failed to resolve reference '${this.identifier}' to type '${this.targetType.name}' (from node: ${node.path})`\n )\n }\n\n this.resolvedReference = {\n node: target,\n lastCacheModification\n }\n }\n }\n\n get resolvedValue(): ReferenceT<IT> {\n this.updateResolvedReference(this.node)\n return this.resolvedReference!.node.value\n }\n}\n\n/**\n * @internal\n * @hidden\n */\nexport class InvalidReferenceError extends Error {\n constructor(m: string) {\n super(m)\n\n Object.setPrototypeOf(this, InvalidReferenceError.prototype)\n }\n}\n\n/**\n * @internal\n * @hidden\n */\nexport abstract class BaseReferenceType<\n IT extends IAnyComplexType\n> extends SimpleType<\n ReferenceIdentifier,\n ReferenceIdentifier,\n IT[\"TypeWithoutSTN\"]\n> {\n readonly flags = TypeFlags.Reference\n\n constructor(\n protected readonly targetType: IT,\n private readonly onInvalidated?: OnReferenceInvalidated<ReferenceT<IT>>\n ) {\n super()\n }\n\n protected override computeName(): string {\n return `reference(${this.targetType.name})`\n }\n\n override isAssignableFrom(type: IAnyType): boolean {\n return this.targetType.isAssignableFrom(type)\n }\n\n isValidSnapshot(\n value: this[\"C\"],\n context: IValidationContext\n ): IValidationResult {\n return isValidIdentifier(value)\n ? typeCheckSuccess()\n : typeCheckFailure(\n context,\n value,\n \"Value is not a valid identifier, which is a string or a number\"\n )\n }\n\n private fireInvalidated(\n cause: \"detach\" | \"destroy\" | \"invalidSnapshotReference\",\n storedRefNode: this[\"N\"],\n referenceId: ReferenceIdentifier,\n refTargetNode: AnyObjectNode | null\n ) {\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 const storedRefParentNode = storedRefNode.parent\n if (!storedRefParentNode?.isAlive) {\n return\n }\n const storedRefParentValue = storedRefParentNode.storedValue\n if (!storedRefParentValue) {\n return\n }\n this.onInvalidated!({\n cause,\n parent: storedRefParentValue,\n invalidTarget: refTargetNode ? refTargetNode.storedValue : undefined,\n invalidId: referenceId,\n replaceRef(newRef) {\n applyPatch(storedRefNode.root.storedValue, {\n op: \"replace\",\n value: newRef,\n path: storedRefNode.path\n })\n },\n removeRef() {\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 private addTargetNodeWatcher(\n storedRefNode: this[\"N\"],\n referenceId: ReferenceIdentifier\n ): IDisposer | undefined {\n // this will make sure the target node becomes created\n const refTargetValue = this.getValue(storedRefNode)\n if (!refTargetValue) {\n return undefined\n }\n const refTargetNode = getStateTreeNode(refTargetValue)\n\n const hookHandler = (subject: AnyNode, refTargetNodeHook: Hook) => {\n const cause = getInvalidationCause(refTargetNodeHook)\n // a reference detached along with its target still resolves it\n if (!cause || (cause === \"detach\" && storedRefNode.isWithin(subject))) {\n return\n }\n this.fireInvalidated(cause, storedRefNode, referenceId, refTargetNode)\n }\n\n const refTargetDetachHookDisposer = refTargetNode.registerHook(\n Hook.beforeDetach,\n hookHandler\n )\n const refTargetDestroyHookDisposer = refTargetNode.registerHook(\n Hook.beforeDestroy,\n hookHandler\n )\n\n return () => {\n refTargetDetachHookDisposer()\n refTargetDestroyHookDisposer()\n }\n }\n\n protected watchTargetNodeForInvalidations(\n storedRefNode: this[\"N\"],\n identifier: ReferenceIdentifier,\n customGetSet: ReferenceOptionsGetSet<IT> | undefined\n ) {\n if (!this.onInvalidated) {\n return\n }\n\n let onRefTargetDestroyedHookDisposer: IDisposer | undefined\n\n // get rid of the watcher hook when the stored ref node is destroyed\n // detached is ignored since scalar nodes (where the reference resides) cannot be detached\n storedRefNode.registerHook(Hook.beforeDestroy, () => {\n if (onRefTargetDestroyedHookDisposer) {\n onRefTargetDestroyedHookDisposer()\n }\n })\n\n const startWatching = (sync: boolean) => {\n // re-create hook in case the stored ref gets reattached\n if (onRefTargetDestroyedHookDisposer) {\n onRefTargetDestroyedHookDisposer()\n }\n\n // make sure the target node is actually there and initialized\n const storedRefParentNode = storedRefNode.parent\n const storedRefParentValue = storedRefParentNode?.storedValue\n if (\n storedRefParentNode &&\n storedRefParentNode.isAlive &&\n storedRefParentValue\n ) {\n let refTargetNodeExists: boolean\n if (customGetSet) {\n refTargetNodeExists = !!customGetSet.get(\n identifier,\n storedRefParentValue\n )\n } else {\n refTargetNodeExists = storedRefNode.root.identifierCache!.has(\n this.targetType,\n normalizeIdentifier(identifier)\n )\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(\n \"invalidSnapshotReference\",\n storedRefNode,\n identifier,\n null\n )\n }\n } else {\n onRefTargetDestroyedHookDisposer = this.addTargetNodeWatcher(\n storedRefNode,\n identifier\n )\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, () => {\n // make sure to attach it so it can start listening\n if (storedRefNode.parent) {\n storedRefNode.parent.createObservableInstanceIfNeeded()\n }\n })\n }\n // start watching once the node is attached somewhere / parent changes\n storedRefNode.registerHook(Hook.afterAttach, () => {\n startWatching(false)\n })\n }\n }\n}\n\n/**\n * @internal\n * @hidden\n */\nexport class IdentifierReferenceType<\n IT extends IAnyComplexType\n> extends BaseReferenceType<IT> {\n override getValue(storedRefNode: this[\"N\"]) {\n if (!storedRefNode.isAlive) {\n return undefined\n }\n const storedRef: StoredReference<IT> = storedRefNode.storedValue\n return storedRef.resolvedValue as any\n }\n\n override getSnapshot(storedRefNode: this[\"N\"]) {\n const ref: StoredReference<IT> = storedRefNode.storedValue\n return ref.identifier\n }\n\n instantiate(\n parent: AnyObjectNode | null,\n subpath: string,\n environment: any,\n initialValue: this[\"C\"] | this[\"T\"]\n ): this[\"N\"] {\n const identifier = isStateTreeNode(initialValue)\n ? getIdentifier(initialValue)!\n : initialValue\n const storedRef = new StoredReference(initialValue, this.targetType as any)\n const storedRefNode: this[\"N\"] = createScalarNode(\n this,\n parent,\n subpath,\n environment,\n storedRef as any\n )\n storedRef.node = storedRefNode\n this.watchTargetNodeForInvalidations(\n storedRefNode,\n identifier as string,\n undefined\n )\n return storedRefNode\n }\n\n override reconcile(\n current: this[\"N\"],\n newValue: this[\"C\"] | this[\"T\"],\n parent: AnyObjectNode,\n subpath: string\n ): this[\"N\"] {\n if (!current.isDetaching && current.type === this) {\n const compareByValue = isStateTreeNode(newValue)\n const ref: StoredReference<IT> = current.storedValue\n if (\n (!compareByValue && ref.identifier === newValue) ||\n (compareByValue && ref.resolvedValue === newValue)\n ) {\n current.setParent(parent, subpath)\n return current\n }\n }\n const newNode = this.instantiate(parent, subpath, undefined, newValue)\n current.die() // noop if detaching\n return newNode\n }\n}\n\n/**\n * @internal\n * @hidden\n */\nexport class CustomReferenceType<\n IT extends IAnyComplexType\n> extends BaseReferenceType<IT> {\n constructor(\n targetType: IT,\n private readonly options: ReferenceOptionsGetSet<IT>,\n onInvalidated?: OnReferenceInvalidated<ReferenceT<IT>>\n ) {\n super(targetType, onInvalidated)\n }\n\n override getValue(storedRefNode: this[\"N\"]) {\n if (!storedRefNode.isAlive) {\n return undefined as any\n }\n const referencedNode = this.options.get(\n storedRefNode.storedValue,\n storedRefNode.parent ? storedRefNode.parent.storedValue : null\n )\n return referencedNode\n }\n\n override getSnapshot(storedRefNode: this[\"N\"]) {\n return storedRefNode.storedValue\n }\n\n instantiate(\n parent: AnyObjectNode | null,\n subpath: string,\n environment: any,\n newValue: this[\"C\"] | this[\"T\"]\n ): this[\"N\"] {\n const identifier = isStateTreeNode(newValue)\n ? this.options.set(newValue, parent ? parent.storedValue : null)\n : newValue\n const storedRefNode: this[\"N\"] = createScalarNode(\n this,\n parent,\n subpath,\n environment,\n identifier as any\n )\n this.watchTargetNodeForInvalidations(\n storedRefNode,\n identifier as string,\n this.options\n )\n return storedRefNode\n }\n\n override reconcile(\n current: this[\"N\"],\n newValue: this[\"C\"] | this[\"T\"],\n parent: AnyObjectNode,\n subpath: string\n ): this[\"N\"] {\n const newIdentifier = isStateTreeNode(newValue)\n ? this.options.set(newValue, current ? current.storedValue : null)\n : newValue\n if (\n !current.isDetaching &&\n current.type === this &&\n current.storedValue === newIdentifier\n ) {\n current.setParent(parent, subpath)\n return current\n }\n const newNode = this.instantiate(parent, subpath, undefined, newIdentifier)\n current.die() // noop if detaching\n return newNode\n }\n}\n\nexport interface ReferenceOptionsGetSet<IT extends IAnyComplexType> {\n get(\n identifier: ReferenceIdentifier,\n parent: IAnyStateTreeNode | null\n ): ReferenceT<IT>\n set(\n value: ReferenceT<IT>,\n parent: IAnyStateTreeNode | null\n ): ReferenceIdentifier\n}\n\nexport interface ReferenceOptionsOnInvalidated<IT extends IAnyComplexType> {\n // called when the current reference is about to become invalid\n onInvalidated: OnReferenceInvalidated<ReferenceT<IT>>\n}\n\nexport type ReferenceOptions<IT extends IAnyComplexType> =\n | ReferenceOptionsGetSet<IT>\n | ReferenceOptionsOnInvalidated<IT>\n | (ReferenceOptionsGetSet<IT> & ReferenceOptionsOnInvalidated<IT>)\n\n/** @hidden */\nexport interface IReferenceType<IT extends IAnyComplexType> extends IType<\n ReferenceIdentifier,\n ReferenceIdentifier,\n IT[\"TypeWithoutSTN\"]\n> {}\n\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 */\nexport function reference<IT extends IAnyComplexType>(\n subType: IT,\n options?: ReferenceOptions<IT>\n): IReferenceType<IT> {\n assertIsType(subType, 1)\n if (devMode()) {\n if (options && typeof options === \"string\") {\n // istanbul ignore next\n throw fail(\n \"References with base path are no longer supported. Please remove the base path.\"\n )\n }\n }\n\n const getSetOptions = options\n ? (options as ReferenceOptionsGetSet<IT>)\n : undefined\n const onInvalidated = options\n ? (options as ReferenceOptionsOnInvalidated<IT>).onInvalidated\n : undefined\n\n if (getSetOptions && (getSetOptions.get || getSetOptions.set)) {\n if (devMode()) {\n if (!getSetOptions.get || !getSetOptions.set) {\n throw fail(\n \"reference options must either contain both a 'get' and a 'set' method or none of them\"\n )\n }\n }\n\n return new CustomReferenceType(\n subType,\n {\n get: getSetOptions.get,\n set: getSetOptions.set\n },\n onInvalidated\n )\n } else {\n return new IdentifierReferenceType(subType, onInvalidated)\n }\n}\n\n/**\n * Returns if a given value represents a reference type.\n *\n * Like every `isXType` guard it reads the type's flags, which wrappers and\n * unions inherit from what they hold, so it is also true for a type that wraps\n * or unions one. Use {@link unwrapType} to get at the type itself.\n *\n * @param type\n * @returns\n */\nexport function isReferenceType(type: IAnyType): boolean {\n return isType(type) && (type.flags & TypeFlags.Reference) > 0\n}\n\nexport function safeReference<IT extends IAnyComplexType>(\n subType: IT,\n options: (ReferenceOptionsGetSet<IT> | object) & {\n acceptsUndefined: false\n onInvalidated?: OnReferenceInvalidated<ReferenceT<IT>>\n }\n): IReferenceType<IT>\nexport function safeReference<IT extends IAnyComplexType>(\n subType: IT,\n options?: (ReferenceOptionsGetSet<IT> | object) & {\n acceptsUndefined?: boolean\n onInvalidated?: OnReferenceInvalidated<ReferenceT<IT>>\n }\n): IMaybe<IReferenceType<IT>>\n/**\n * `types.safeReference` - A safe reference is like a standard reference, except that it accepts the undefined value by default\n * and automatically sets itself to undefined (when the parent is a model) / removes itself from arrays and maps\n * when the reference it is pointing to gets detached/destroyed.\n *\n * The optional options parameter object accepts a parameter named `acceptsUndefined`, which is set to true by default, so it is suitable\n * for model properties.\n * When used inside collections (arrays/maps), it is recommended to set this option to false so it can't take undefined as value,\n * which is usually the desired in those cases.\n * Additionally, the optional options parameter object accepts a parameter named `onInvalidated`, which will be called when the reference target node that the reference is pointing to is about to be detached/destroyed\n *\n * Strictly speaking it is a `types.maybe(types.reference(X))` (when `acceptsUndefined` is set to true, the default) and\n * `types.reference(X)` (when `acceptsUndefined` is set to false), both of them with a customized `onInvalidated` option.\n *\n * @param subType\n * @param options\n * @returns\n */\nexport function safeReference<IT extends IAnyComplexType>(\n subType: IT,\n options?: (ReferenceOptionsGetSet<IT> | object) & {\n acceptsUndefined?: boolean\n onInvalidated?: OnReferenceInvalidated<ReferenceT<IT>>\n }\n): IReferenceType<IT> | IMaybe<IReferenceType<IT>> {\n const refType = reference(subType, {\n ...options,\n onInvalidated(ev) {\n if (options && options.onInvalidated) {\n options.onInvalidated(ev)\n }\n ev.removeRef()\n }\n })\n\n if (options && options.acceptsUndefined === false) {\n return refType\n } else {\n return maybe(refType)\n }\n}\n","import {\n type AnyObjectNode,\n type IAnyType,\n type ISimpleType,\n type IValidationContext,\n type IValidationResult,\n ModelType,\n SimpleType,\n TypeFlags,\n assertArg,\n createScalarNode,\n fail,\n isType,\n typeCheckFailure,\n typeCheckSuccess\n} from \"../../internal.ts\"\n\nabstract class BaseIdentifierType<T> extends SimpleType<T, T, T> {\n readonly flags = TypeFlags.Identifier\n\n constructor(\n name: string,\n private readonly validType: \"string\" | \"number\"\n ) {\n super(name)\n }\n\n instantiate(\n parent: AnyObjectNode | null,\n subpath: string,\n environment: any,\n initialValue: this[\"C\"]\n ): this[\"N\"] {\n if (!parent || !(parent.type instanceof ModelType)) {\n throw fail(\n `Identifier types can only be instantiated as direct child of a model type`\n )\n }\n\n return createScalarNode(this, parent, subpath, environment, initialValue)\n }\n\n override reconcile(\n current: this[\"N\"],\n newValue: this[\"C\"],\n parent: AnyObjectNode,\n subpath: string\n ) {\n // we don't consider detaching here since identifier are scalar nodes, and scalar nodes cannot be detached\n if (current.storedValue !== newValue) {\n throw fail(\n `Tried to change identifier from '${current.storedValue}' to '${newValue}'. Changing identifiers is not allowed.`\n )\n }\n current.setParent(parent, subpath)\n return current\n }\n\n isValidSnapshot(\n value: this[\"C\"],\n context: IValidationContext\n ): IValidationResult {\n if (typeof value !== this.validType) {\n return typeCheckFailure(\n context,\n value,\n `Value is not a valid ${this.describe()}, expected a ${this.validType}`\n )\n }\n return typeCheckSuccess()\n }\n}\n\n/**\n * @internal\n * @hidden\n */\nexport class IdentifierType extends BaseIdentifierType<string> {\n constructor() {\n super(`identifier`, \"string\")\n }\n}\n\n/**\n * @internal\n * @hidden\n */\nexport class IdentifierNumberType extends BaseIdentifierType<number> {\n constructor() {\n super(\"identifierNumber\", \"number\")\n }\n}\n\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 */\nexport const identifier: ISimpleType<string> = new IdentifierType()\n\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 */\nexport const identifierNumber: ISimpleType<number> = new IdentifierNumberType()\n\n/**\n * Returns if a given value represents an identifier type.\n *\n * Like every `isXType` guard it reads the type's flags, which wrappers and\n * unions inherit from what they hold, so it is also true for a type that wraps\n * or unions one. Use {@link unwrapType} to get at the type itself.\n *\n * @param type\n * @returns\n */\nexport function isIdentifierType(type: IAnyType): boolean {\n return isType(type) && (type.flags & TypeFlags.Identifier) > 0\n}\n\n/**\n * Valid types for identifiers.\n */\nexport type ReferenceIdentifier = string | number\n\n/**\n * @internal\n * @hidden\n */\nexport function normalizeIdentifier(id: ReferenceIdentifier): string {\n return `${id}`\n}\n\n/**\n * @internal\n * @hidden\n */\nexport function isValidIdentifier(id: any): id is ReferenceIdentifier {\n return typeof id === \"string\" || typeof id === \"number\"\n}\n\n/**\n * @internal\n * @hidden\n */\nexport function assertIsValidIdentifier(\n id: ReferenceIdentifier,\n argNumber: number | number[]\n) {\n assertArg(id, isValidIdentifier, \"string or number (identifier)\", argNumber)\n}\n","import {\n type AnyObjectNode,\n type IType,\n type IValidationContext,\n type IValidationResult,\n SimpleType,\n TypeFlags,\n createScalarNode,\n typeCheckFailure,\n typeCheckSuccess\n} from \"../../internal.ts\"\n\nexport interface CustomTypeOptions<S, T> {\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): boolean\n /** a non empty string is assumed to be a validation error */\n getValidationMessage(snapshot: S): string\n // TODO: isSnapshotEqual\n // TODO: isValueEqual\n}\n\n/**\n * `types.custom` - Creates a custom type. Custom types can be used for arbitrary immutable values, that have a serializable representation. For example, to create your own Date representation, Decimal type etc.\n *\n * The signature of the options is:\n * ```ts\n * export interface CustomTypeOptions<S, T> {\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<string, Decimal>({\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 */\nexport function custom<S, T>(\n options: CustomTypeOptions<S, T>\n): IType<S | T, S, T> {\n return new CustomType<S, T>(options)\n}\n\n/**\n * @internal\n * @hidden\n */\nexport class CustomType<S, T> extends SimpleType<S | T, S, T> {\n readonly flags = TypeFlags.Custom\n\n constructor(protected readonly options: CustomTypeOptions<S, T>) {\n super(options.name)\n }\n\n isValidSnapshot(\n value: this[\"C\"],\n context: IValidationContext\n ): IValidationResult {\n if (this.options.isTargetType(value)) {\n return typeCheckSuccess()\n }\n\n const typeError: string = this.options.getValidationMessage(value as S)\n if (typeError) {\n return typeCheckFailure(\n context,\n value,\n `Invalid value for type '${this.name}': ${typeError}`\n )\n }\n return typeCheckSuccess()\n }\n\n override getSnapshot(node: this[\"N\"]): S {\n return this.options.toSnapshot(node.storedValue)\n }\n\n instantiate(\n parent: AnyObjectNode | null,\n subpath: string,\n environment: any,\n initialValue: S | T\n ): this[\"N\"] {\n const valueToStore: T = this.options.isTargetType(initialValue)\n ? (initialValue as T)\n : this.options.fromSnapshot(initialValue as S, parent?.root.environment)\n return createScalarNode(this, parent, subpath, environment, valueToStore)\n }\n\n override reconcile(\n current: this[\"N\"],\n value: S | T,\n parent: AnyObjectNode,\n subpath: string\n ): this[\"N\"] {\n const isSnapshot = !this.options.isTargetType(value)\n // in theory customs use scalar nodes which cannot be detached, but still...\n if (!current.isDetaching) {\n const unchanged =\n current.type === this &&\n (isSnapshot\n ? value === current.snapshot\n : value === current.storedValue)\n if (unchanged) {\n current.setParent(parent, subpath)\n return current\n }\n }\n const valueToStore: T = isSnapshot\n ? this.options.fromSnapshot(value as S, parent.root.environment)\n : (value as T)\n const newNode = this.instantiate(parent, subpath, undefined, valueToStore)\n current.die() // noop if detaching\n return newNode\n }\n}\n","import {\n type AnyObjectNode,\n BaseType,\n type ExtractNodeType,\n type IAnyType,\n type IType,\n type IValidationContext,\n type IValidationResult,\n assertIsType,\n fail,\n isStateTreeNode,\n isType,\n typeCheckSuccess\n} from \"../../internal.ts\"\n\n/**\n * @internal\n * @hidden\n */\nexport class Resilient<\n IT extends IAnyType,\n FT extends IAnyType\n> extends BaseType<\n IT[\"CreationType\"] | FT[\"CreationType\"],\n IT[\"SnapshotType\"] | FT[\"SnapshotType\"],\n IT[\"TypeWithoutSTN\"] | FT[\"TypeWithoutSTN\"],\n ExtractNodeType<IT> | ExtractNodeType<FT>\n> {\n get flags() {\n return this._subtype.flags\n }\n\n /** the type tried first; the fallback takes over only when it fails */\n get primaryType(): IT {\n return this._subtype\n }\n\n constructor(\n private readonly _subtype: IT,\n private readonly _fallbackType: FT,\n private readonly _createFallbackSnapshot: (\n error: unknown,\n snapshot: unknown\n ) => FT[\"CreationType\"]\n ) {\n super()\n }\n\n protected override computeName(): string {\n return `resilient(${this._subtype.name})`\n }\n\n override describe() {\n return `resilient(${this._subtype.describe()})`\n }\n\n private _instantiateFallback(\n parent: AnyObjectNode | null,\n subpath: string,\n environment: any,\n originalSnapshot: any,\n originalError: unknown\n ): this[\"N\"] {\n let fallbackSnapshot: FT[\"CreationType\"]\n try {\n fallbackSnapshot = this._createFallbackSnapshot(\n originalError,\n originalSnapshot\n )\n } catch (e) {\n throw fail(\n `resilient: createFallbackSnapshot threw while handling error for '${this._subtype.name}': ${originalError}. createFallbackSnapshot error: ${e}`\n )\n }\n try {\n return this._fallbackType.instantiate(\n parent,\n subpath,\n environment,\n fallbackSnapshot\n ) as this[\"N\"]\n } catch (e) {\n throw fail(\n `resilient: fallback type '${this._fallbackType.name}' failed to instantiate while handling error for '${this._subtype.name}': ${originalError}. Fallback error: ${e}`\n )\n }\n }\n\n instantiate(\n parent: AnyObjectNode | null,\n subpath: string,\n environment: any,\n initialValue: this[\"C\"] | this[\"T\"]\n ): this[\"N\"] {\n if (isStateTreeNode(initialValue)) {\n return this._subtype.instantiate(\n parent,\n subpath,\n environment,\n initialValue\n ) as this[\"N\"]\n }\n try {\n return this._subtype.instantiate(\n parent,\n subpath,\n environment,\n initialValue\n ) as this[\"N\"]\n } catch (e) {\n return this._instantiateFallback(\n parent,\n subpath,\n environment,\n initialValue,\n e\n )\n }\n }\n\n reconcile(\n current: this[\"N\"],\n newValue: this[\"C\"] | this[\"T\"],\n parent: AnyObjectNode,\n subpath: string\n ): this[\"N\"] {\n if (isStateTreeNode(newValue)) {\n return this._subtype.reconcile(\n current,\n newValue,\n parent,\n subpath\n ) as this[\"N\"]\n }\n if (this._fallbackType.isAssignableFrom(current.type)) {\n // `current` holds the fallback. Try the real type again, but keep the\n // fallback node around while doing so — it is what the catch reconciles.\n let recovered: this[\"N\"]\n try {\n recovered = this._subtype.instantiate(\n parent,\n subpath,\n undefined,\n newValue\n ) as this[\"N\"]\n } catch (e) {\n return this._fallbackType.reconcile(\n current,\n this._createFallbackSnapshot(e, newValue),\n parent,\n subpath\n ) as this[\"N\"]\n }\n // the fallback node has been replaced, so it has to die: otherwise it\n // stays alive in the tree and its identifier stays in the root's cache,\n // where it collides with the recovered node's\n current.die()\n return recovered\n }\n try {\n return this._subtype.reconcile(\n current,\n newValue,\n parent,\n subpath\n ) as this[\"N\"]\n } catch (e) {\n current.die()\n return this._instantiateFallback(parent, subpath, undefined, newValue, e)\n }\n }\n\n isValidSnapshot(\n _value: this[\"C\"],\n _context: IValidationContext\n ): IValidationResult {\n return typeCheckSuccess()\n }\n\n override is(thing: unknown): thing is any {\n if (isType(thing)) {\n return (\n this._subtype.isAssignableFrom(thing) ||\n this._fallbackType.isAssignableFrom(thing)\n )\n }\n try {\n if (this._subtype.is(thing)) {\n return true\n }\n } catch (_e) {\n // subtype.is() may throw (e.g. union dispatcher)\n }\n try {\n return this._fallbackType.is(thing)\n } catch (_e) {\n return false\n }\n }\n\n override isAssignableFrom(type: IAnyType) {\n return (\n this._subtype.isAssignableFrom(type) ||\n this._fallbackType.isAssignableFrom(type)\n )\n }\n\n getSubTypes() {\n return [this._subtype, this._fallbackType]\n }\n\n override getSnapshot(node: this[\"N\"]): this[\"S\"] {\n return node.snapshot\n }\n}\n\nexport interface IResilientType<\n IT extends IAnyType,\n FT extends IAnyType\n> extends IType<\n IT[\"CreationType\"] | FT[\"CreationType\"],\n IT[\"SnapshotType\"] | FT[\"SnapshotType\"],\n IT[\"TypeWithoutSTN\"] | FT[\"TypeWithoutSTN\"]\n> {}\n\n/**\n * `types.resilient` - Wraps a type so that instantiation errors are caught\n * and a fallback type is used instead. This is useful for loading data that\n * may contain unknown or invalid subtrees (e.g., plugin types that are not\n * installed) without crashing the entire state tree.\n *\n * The `createFallbackSnapshot` callback receives the caught error and the\n * original snapshot, and must return a valid snapshot for the fallback type.\n *\n * @param type The type to wrap.\n * @param fallbackType The fallback type to use when instantiation fails.\n * @param createFallbackSnapshot Callback that produces a fallback snapshot from the error and original snapshot.\n * @returns A resilient type.\n */\nexport function resilient<IT extends IAnyType, FT extends IAnyType>(\n type: IT,\n fallbackType: FT,\n createFallbackSnapshot: (\n error: unknown,\n snapshot: unknown\n ) => FT[\"CreationType\"]\n): IResilientType<IT, FT> {\n assertIsType(type, 1)\n assertIsType(fallbackType, 2)\n return new Resilient(type, fallbackType, createFallbackSnapshot)\n}\n","// we import the types to re-export them inside types.\nimport {\n DatePrimitive,\n array,\n boolean,\n compose,\n custom,\n enumeration,\n finite,\n float,\n frozen,\n identifier,\n identifierNumber,\n integer,\n late,\n lazy,\n literal,\n map,\n maybe,\n maybeNull,\n model,\n nullType,\n number,\n optional,\n stripDefault,\n reference,\n refinement,\n safeReference,\n resilient,\n snapshotProcessor,\n string,\n undefinedType,\n union\n} from \"../internal.ts\"\n\nexport const types = {\n enumeration,\n model,\n compose,\n custom,\n reference,\n safeReference,\n union,\n optional,\n stripDefault,\n literal,\n maybe,\n maybeNull,\n refinement,\n string,\n boolean,\n number,\n integer,\n float,\n finite,\n Date: DatePrimitive,\n map,\n array,\n frozen,\n identifier,\n identifierNumber,\n late,\n lazy,\n undefined: undefinedType,\n null: nullType,\n snapshotProcessor,\n resilient\n}\n"],"names":["mobxAction","mobxDefineProperty","defineProperty"],"mappings":";;AAQA,IAAI,kBAAkB,GAAmB,MAAM;AAE/C;;;;;;AAMG;AACG,SAAU,qBAAqB,CAAC,IAAoB,EAAA;IACxD,kBAAkB,GAAG,IAAI;AAC3B;AAEA;;;;AAIG;SACa,qBAAqB,GAAA;AACnC,IAAA,OAAO,kBAAkB;AAC3B;AAQA;;;;;;;;;AASG;AACG,SAAU,qBAAqB,CAAC,IAAoB,EAAA;IACxD,qBAAqB,CAAC,IAAI,CAAC;AAC7B;;AChDA;;AAEG;AACH,IAAY,IAMX;AAND,CAAA,UAAY,IAAI,EAAA;AACd,IAAA,IAAA,CAAA,aAAA,CAAA,GAAA,aAA2B;AAC3B,IAAA,IAAA,CAAA,aAAA,CAAA,GAAA,aAA2B;AAC3B,IAAA,IAAA,CAAA,2BAAA,CAAA,GAAA,2BAAuD;AACvD,IAAA,IAAA,CAAA,cAAA,CAAA,GAAA,cAA6B;AAC7B,IAAA,IAAA,CAAA,eAAA,CAAA,GAAA,eAA+B;AACjC,CAAC,EANW,IAAI,KAAJ,IAAI,GAAA,EAAA,CAAA,CAAA;;AC2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