@jbrowse/mobx-state-tree 5.7.1 → 5.8.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (253) hide show
  1. package/README.md +0 -10
  2. package/dist/index.d.ts +2135 -2
  3. package/dist/mobx-state-tree.cjs +6894 -0
  4. package/dist/mobx-state-tree.cjs.map +1 -0
  5. package/dist/mobx-state-tree.mjs +6814 -0
  6. package/dist/mobx-state-tree.mjs.map +1 -0
  7. package/package.json +30 -26
  8. package/dist/core/action.d.ts +0 -87
  9. package/dist/core/action.js +0 -228
  10. package/dist/core/action.js.map +0 -1
  11. package/dist/core/actionContext.d.ts +0 -27
  12. package/dist/core/actionContext.js +0 -42
  13. package/dist/core/actionContext.js.map +0 -1
  14. package/dist/core/flow.d.ts +0 -69
  15. package/dist/core/flow.js +0 -180
  16. package/dist/core/flow.js.map +0 -1
  17. package/dist/core/json-patch.d.ts +0 -46
  18. package/dist/core/json-patch.js +0 -133
  19. package/dist/core/json-patch.js.map +0 -1
  20. package/dist/core/mst-operations.d.ts +0 -459
  21. package/dist/core/mst-operations.js +0 -885
  22. package/dist/core/mst-operations.js.map +0 -1
  23. package/dist/core/node/BaseNode.d.ts +0 -62
  24. package/dist/core/node/BaseNode.js +0 -152
  25. package/dist/core/node/BaseNode.js.map +0 -1
  26. package/dist/core/node/Hook.d.ts +0 -17
  27. package/dist/core/node/Hook.js +0 -15
  28. package/dist/core/node/Hook.js.map +0 -1
  29. package/dist/core/node/create-node.d.ts +0 -16
  30. package/dist/core/node/create-node.js +0 -41
  31. package/dist/core/node/create-node.js.map +0 -1
  32. package/dist/core/node/identifier-cache.d.ts +0 -19
  33. package/dist/core/node/identifier-cache.js +0 -115
  34. package/dist/core/node/identifier-cache.js.map +0 -1
  35. package/dist/core/node/livelinessChecking.d.ts +0 -37
  36. package/dist/core/node/livelinessChecking.js +0 -38
  37. package/dist/core/node/livelinessChecking.js.map +0 -1
  38. package/dist/core/node/node-utils.d.ts +0 -83
  39. package/dist/core/node/node-utils.js +0 -165
  40. package/dist/core/node/node-utils.js.map +0 -1
  41. package/dist/core/node/object-node.d.ts +0 -101
  42. package/dist/core/node/object-node.js +0 -546
  43. package/dist/core/node/object-node.js.map +0 -1
  44. package/dist/core/node/scalar-node.d.ts +0 -21
  45. package/dist/core/node/scalar-node.js +0 -90
  46. package/dist/core/node/scalar-node.js.map +0 -1
  47. package/dist/core/process.d.ts +0 -50
  48. package/dist/core/process.js +0 -39
  49. package/dist/core/process.js.map +0 -1
  50. package/dist/core/type/type-checker.d.ts +0 -69
  51. package/dist/core/type/type-checker.js +0 -154
  52. package/dist/core/type/type-checker.js.map +0 -1
  53. package/dist/core/type/type.d.ts +0 -317
  54. package/dist/core/type/type.js +0 -251
  55. package/dist/core/type/type.js.map +0 -1
  56. package/dist/index.js +0 -85
  57. package/dist/index.js.map +0 -1
  58. package/dist/internal.d.ts +0 -39
  59. package/dist/internal.js +0 -60
  60. package/dist/internal.js.map +0 -1
  61. package/dist/middlewares/create-action-tracking-middleware.d.ts +0 -24
  62. package/dist/middlewares/create-action-tracking-middleware.js +0 -81
  63. package/dist/middlewares/create-action-tracking-middleware.js.map +0 -1
  64. package/dist/middlewares/createActionTrackingMiddleware2.d.ts +0 -34
  65. package/dist/middlewares/createActionTrackingMiddleware2.js +0 -133
  66. package/dist/middlewares/createActionTrackingMiddleware2.js.map +0 -1
  67. package/dist/middlewares/on-action.d.ts +0 -87
  68. package/dist/middlewares/on-action.js +0 -215
  69. package/dist/middlewares/on-action.js.map +0 -1
  70. package/dist/package.json +0 -1
  71. package/dist/types/complex-types/array.d.ts +0 -81
  72. package/dist/types/complex-types/array.js +0 -353
  73. package/dist/types/complex-types/array.js.map +0 -1
  74. package/dist/types/complex-types/map.d.ts +0 -111
  75. package/dist/types/complex-types/map.js +0 -362
  76. package/dist/types/complex-types/map.js.map +0 -1
  77. package/dist/types/complex-types/model.d.ts +0 -193
  78. package/dist/types/complex-types/model.js +0 -478
  79. package/dist/types/complex-types/model.js.map +0 -1
  80. package/dist/types/index.d.ts +0 -33
  81. package/dist/types/index.js +0 -38
  82. package/dist/types/index.js.map +0 -1
  83. package/dist/types/primitives.d.ts +0 -125
  84. package/dist/types/primitives.js +0 -183
  85. package/dist/types/primitives.js.map +0 -1
  86. package/dist/types/utility-types/custom.d.ts +0 -75
  87. package/dist/types/utility-types/custom.js +0 -111
  88. package/dist/types/utility-types/custom.js.map +0 -1
  89. package/dist/types/utility-types/enumeration.d.ts +0 -5
  90. package/dist/types/utility-types/enumeration.js +0 -34
  91. package/dist/types/utility-types/enumeration.js.map +0 -1
  92. package/dist/types/utility-types/frozen.d.ts +0 -24
  93. package/dist/types/utility-types/frozen.js +0 -98
  94. package/dist/types/utility-types/frozen.js.map +0 -1
  95. package/dist/types/utility-types/identifier.d.ts +0 -87
  96. package/dist/types/utility-types/identifier.js +0 -130
  97. package/dist/types/utility-types/identifier.js.map +0 -1
  98. package/dist/types/utility-types/late.d.ts +0 -10
  99. package/dist/types/utility-types/late.js +0 -110
  100. package/dist/types/utility-types/late.js.map +0 -1
  101. package/dist/types/utility-types/lazy.d.ts +0 -23
  102. package/dist/types/utility-types/lazy.js +0 -77
  103. package/dist/types/utility-types/lazy.js.map +0 -1
  104. package/dist/types/utility-types/literal.d.ts +0 -38
  105. package/dist/types/utility-types/literal.js +0 -64
  106. package/dist/types/utility-types/literal.js.map +0 -1
  107. package/dist/types/utility-types/maybe.d.ts +0 -26
  108. package/dist/types/utility-types/maybe.js +0 -30
  109. package/dist/types/utility-types/maybe.js.map +0 -1
  110. package/dist/types/utility-types/optional.d.ts +0 -42
  111. package/dist/types/utility-types/optional.js +0 -141
  112. package/dist/types/utility-types/optional.js.map +0 -1
  113. package/dist/types/utility-types/reference.d.ts +0 -90
  114. package/dist/types/utility-types/reference.js +0 -393
  115. package/dist/types/utility-types/reference.js.map +0 -1
  116. package/dist/types/utility-types/refinement.d.ts +0 -10
  117. package/dist/types/utility-types/refinement.js +0 -86
  118. package/dist/types/utility-types/refinement.js.map +0 -1
  119. package/dist/types/utility-types/resilient.d.ts +0 -18
  120. package/dist/types/utility-types/resilient.js +0 -121
  121. package/dist/types/utility-types/resilient.js.map +0 -1
  122. package/dist/types/utility-types/snapshotProcessor.d.ts +0 -63
  123. package/dist/types/utility-types/snapshotProcessor.js +0 -162
  124. package/dist/types/utility-types/snapshotProcessor.js.map +0 -1
  125. package/dist/types/utility-types/union.d.ts +0 -78
  126. package/dist/types/utility-types/union.js +0 -246
  127. package/dist/types/utility-types/union.js.map +0 -1
  128. package/dist/utils.d.ts +0 -230
  129. package/dist/utils.js +0 -483
  130. package/dist/utils.js.map +0 -1
  131. package/esm/core/action.d.ts +0 -87
  132. package/esm/core/action.js +0 -219
  133. package/esm/core/action.js.map +0 -1
  134. package/esm/core/actionContext.d.ts +0 -27
  135. package/esm/core/actionContext.js +0 -37
  136. package/esm/core/actionContext.js.map +0 -1
  137. package/esm/core/flow.d.ts +0 -69
  138. package/esm/core/flow.js +0 -173
  139. package/esm/core/flow.js.map +0 -1
  140. package/esm/core/json-patch.d.ts +0 -46
  141. package/esm/core/json-patch.js +0 -125
  142. package/esm/core/json-patch.js.map +0 -1
  143. package/esm/core/mst-operations.d.ts +0 -459
  144. package/esm/core/mst-operations.js +0 -844
  145. package/esm/core/mst-operations.js.map +0 -1
  146. package/esm/core/node/BaseNode.d.ts +0 -62
  147. package/esm/core/node/BaseNode.js +0 -148
  148. package/esm/core/node/BaseNode.js.map +0 -1
  149. package/esm/core/node/Hook.d.ts +0 -17
  150. package/esm/core/node/Hook.js +0 -12
  151. package/esm/core/node/Hook.js.map +0 -1
  152. package/esm/core/node/create-node.d.ts +0 -16
  153. package/esm/core/node/create-node.js +0 -36
  154. package/esm/core/node/create-node.js.map +0 -1
  155. package/esm/core/node/identifier-cache.d.ts +0 -19
  156. package/esm/core/node/identifier-cache.js +0 -111
  157. package/esm/core/node/identifier-cache.js.map +0 -1
  158. package/esm/core/node/livelinessChecking.d.ts +0 -37
  159. package/esm/core/node/livelinessChecking.js +0 -33
  160. package/esm/core/node/livelinessChecking.js.map +0 -1
  161. package/esm/core/node/node-utils.d.ts +0 -83
  162. package/esm/core/node/node-utils.js +0 -153
  163. package/esm/core/node/node-utils.js.map +0 -1
  164. package/esm/core/node/object-node.d.ts +0 -101
  165. package/esm/core/node/object-node.js +0 -542
  166. package/esm/core/node/object-node.js.map +0 -1
  167. package/esm/core/node/scalar-node.d.ts +0 -21
  168. package/esm/core/node/scalar-node.js +0 -86
  169. package/esm/core/node/scalar-node.js.map +0 -1
  170. package/esm/core/process.d.ts +0 -50
  171. package/esm/core/process.js +0 -35
  172. package/esm/core/process.js.map +0 -1
  173. package/esm/core/type/type-checker.d.ts +0 -69
  174. package/esm/core/type/type-checker.js +0 -144
  175. package/esm/core/type/type-checker.js.map +0 -1
  176. package/esm/core/type/type.d.ts +0 -317
  177. package/esm/core/type/type.js +0 -243
  178. package/esm/core/type/type.js.map +0 -1
  179. package/esm/index.d.ts +0 -2
  180. package/esm/index.js +0 -2
  181. package/esm/index.js.map +0 -1
  182. package/esm/internal.d.ts +0 -39
  183. package/esm/internal.js +0 -44
  184. package/esm/internal.js.map +0 -1
  185. package/esm/middlewares/create-action-tracking-middleware.d.ts +0 -24
  186. package/esm/middlewares/create-action-tracking-middleware.js +0 -78
  187. package/esm/middlewares/create-action-tracking-middleware.js.map +0 -1
  188. package/esm/middlewares/createActionTrackingMiddleware2.d.ts +0 -34
  189. package/esm/middlewares/createActionTrackingMiddleware2.js +0 -130
  190. package/esm/middlewares/createActionTrackingMiddleware2.js.map +0 -1
  191. package/esm/middlewares/on-action.d.ts +0 -87
  192. package/esm/middlewares/on-action.js +0 -210
  193. package/esm/middlewares/on-action.js.map +0 -1
  194. package/esm/types/complex-types/array.d.ts +0 -81
  195. package/esm/types/complex-types/array.js +0 -347
  196. package/esm/types/complex-types/array.js.map +0 -1
  197. package/esm/types/complex-types/map.d.ts +0 -111
  198. package/esm/types/complex-types/map.js +0 -356
  199. package/esm/types/complex-types/map.js.map +0 -1
  200. package/esm/types/complex-types/model.d.ts +0 -193
  201. package/esm/types/complex-types/model.js +0 -471
  202. package/esm/types/complex-types/model.js.map +0 -1
  203. package/esm/types/index.d.ts +0 -33
  204. package/esm/types/index.js +0 -35
  205. package/esm/types/index.js.map +0 -1
  206. package/esm/types/primitives.d.ts +0 -125
  207. package/esm/types/primitives.js +0 -177
  208. package/esm/types/primitives.js.map +0 -1
  209. package/esm/types/utility-types/custom.d.ts +0 -75
  210. package/esm/types/utility-types/custom.js +0 -106
  211. package/esm/types/utility-types/custom.js.map +0 -1
  212. package/esm/types/utility-types/enumeration.d.ts +0 -5
  213. package/esm/types/utility-types/enumeration.js +0 -31
  214. package/esm/types/utility-types/enumeration.js.map +0 -1
  215. package/esm/types/utility-types/frozen.d.ts +0 -24
  216. package/esm/types/utility-types/frozen.js +0 -92
  217. package/esm/types/utility-types/frozen.js.map +0 -1
  218. package/esm/types/utility-types/identifier.d.ts +0 -87
  219. package/esm/types/utility-types/identifier.js +0 -121
  220. package/esm/types/utility-types/identifier.js.map +0 -1
  221. package/esm/types/utility-types/late.d.ts +0 -10
  222. package/esm/types/utility-types/late.js +0 -106
  223. package/esm/types/utility-types/late.js.map +0 -1
  224. package/esm/types/utility-types/lazy.d.ts +0 -23
  225. package/esm/types/utility-types/lazy.js +0 -72
  226. package/esm/types/utility-types/lazy.js.map +0 -1
  227. package/esm/types/utility-types/literal.d.ts +0 -38
  228. package/esm/types/utility-types/literal.js +0 -58
  229. package/esm/types/utility-types/literal.js.map +0 -1
  230. package/esm/types/utility-types/maybe.d.ts +0 -26
  231. package/esm/types/utility-types/maybe.js +0 -26
  232. package/esm/types/utility-types/maybe.js.map +0 -1
  233. package/esm/types/utility-types/optional.d.ts +0 -42
  234. package/esm/types/utility-types/optional.js +0 -135
  235. package/esm/types/utility-types/optional.js.map +0 -1
  236. package/esm/types/utility-types/reference.d.ts +0 -90
  237. package/esm/types/utility-types/reference.js +0 -383
  238. package/esm/types/utility-types/reference.js.map +0 -1
  239. package/esm/types/utility-types/refinement.d.ts +0 -10
  240. package/esm/types/utility-types/refinement.js +0 -82
  241. package/esm/types/utility-types/refinement.js.map +0 -1
  242. package/esm/types/utility-types/resilient.d.ts +0 -18
  243. package/esm/types/utility-types/resilient.js +0 -118
  244. package/esm/types/utility-types/resilient.js.map +0 -1
  245. package/esm/types/utility-types/snapshotProcessor.d.ts +0 -63
  246. package/esm/types/utility-types/snapshotProcessor.js +0 -159
  247. package/esm/types/utility-types/snapshotProcessor.js.map +0 -1
  248. package/esm/types/utility-types/union.d.ts +0 -78
  249. package/esm/types/utility-types/union.js +0 -240
  250. package/esm/types/utility-types/union.js.map +0 -1
  251. package/esm/utils.d.ts +0 -230
  252. package/esm/utils.js +0 -449
  253. package/esm/utils.js.map +0 -1
@@ -1,215 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.applyAction = applyAction;
4
- exports.recordActions = recordActions;
5
- exports.onAction = onAction;
6
- const mobx_1 = require("mobx");
7
- const internal_ts_1 = require("../internal.js");
8
- function serializeArgument(node, actionName, index, arg) {
9
- if (arg instanceof Date) {
10
- return { $MST_DATE: arg.getTime() };
11
- }
12
- if ((0, internal_ts_1.isPrimitive)(arg)) {
13
- return arg;
14
- }
15
- // 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
16
- // 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
17
- if ((0, internal_ts_1.isStateTreeNode)(arg)) {
18
- return serializeTheUnserializable(`[MSTNode: ${(0, internal_ts_1.getType)(arg).name}]`);
19
- }
20
- if (typeof arg === "function") {
21
- return serializeTheUnserializable(`[function]`);
22
- }
23
- if (typeof arg === "object" && !(0, internal_ts_1.isPlainObject)(arg) && !(0, internal_ts_1.isArray)(arg)) {
24
- return serializeTheUnserializable(`[object ${(arg && arg.constructor && arg.constructor.name) ||
25
- "Complex Object"}]`);
26
- }
27
- try {
28
- // Check if serializable, cycle free etc...
29
- // MWE: there must be a better way....
30
- JSON.stringify(arg); // or throws
31
- return arg;
32
- }
33
- catch (e) {
34
- return serializeTheUnserializable("" + e);
35
- }
36
- }
37
- function deserializeArgument(adm, value) {
38
- if (value && typeof value === "object" && "$MST_DATE" in value) {
39
- return new Date(value["$MST_DATE"]);
40
- }
41
- return value;
42
- }
43
- function serializeTheUnserializable(baseType) {
44
- return {
45
- $MST_UNSERIALIZABLE: true,
46
- type: baseType
47
- };
48
- }
49
- /**
50
- * Applies an action or a series of actions in a single MobX transaction.
51
- * Does not return any value
52
- * Takes an action description as produced by the `onAction` middleware.
53
- *
54
- * @param target
55
- * @param actions
56
- */
57
- function applyAction(target, actions) {
58
- // check all arguments
59
- (0, internal_ts_1.assertIsStateTreeNode)(target, 1);
60
- (0, internal_ts_1.assertArg)(actions, a => typeof a === "object", "object or array", 2);
61
- (0, mobx_1.runInAction)(() => {
62
- (0, internal_ts_1.asArray)(actions).forEach(action => baseApplyAction(target, action));
63
- });
64
- }
65
- function baseApplyAction(target, action) {
66
- const resolvedTarget = (0, internal_ts_1.tryResolve)(target, action.path || "");
67
- if (!resolvedTarget) {
68
- throw (0, internal_ts_1.fail)(`Invalid action path: ${action.path || ""}`);
69
- }
70
- const node = (0, internal_ts_1.getStateTreeNode)(resolvedTarget);
71
- // Reserved functions
72
- if (action.name === "@APPLY_PATCHES") {
73
- return internal_ts_1.applyPatch.call(null, resolvedTarget, action.args[0]);
74
- }
75
- if (action.name === "@APPLY_SNAPSHOT") {
76
- return internal_ts_1.applySnapshot.call(null, resolvedTarget, action.args[0]);
77
- }
78
- if (!(typeof resolvedTarget[action.name] === "function")) {
79
- throw (0, internal_ts_1.fail)(`Action '${action.name}' does not exist in '${node.path}'`);
80
- }
81
- return resolvedTarget[action.name](...(action.args ? action.args.map(v => deserializeArgument(node, v)) : []));
82
- }
83
- /**
84
- * Small abstraction around `onAction` and `applyAction`, attaches an action listener to a tree and records all the actions emitted.
85
- * Returns an recorder object with the following signature:
86
- *
87
- * Example:
88
- * ```ts
89
- * export interface IActionRecorder {
90
- * // the recorded actions
91
- * actions: ISerializedActionCall[]
92
- * // true if currently recording
93
- * recording: boolean
94
- * // stop recording actions
95
- * stop(): void
96
- * // resume recording actions
97
- * resume(): void
98
- * // apply all the recorded actions on the given object
99
- * replay(target: IAnyStateTreeNode): void
100
- * }
101
- * ```
102
- *
103
- * The optional filter function allows to skip recording certain actions.
104
- *
105
- * @param subject
106
- * @returns
107
- */
108
- function recordActions(subject, filter) {
109
- // check all arguments
110
- (0, internal_ts_1.assertIsStateTreeNode)(subject, 1);
111
- const actions = [];
112
- const listener = (call) => {
113
- const recordThis = filter ? filter(call, (0, internal_ts_1.getRunningActionContext)()) : true;
114
- if (recordThis) {
115
- actions.push(call);
116
- }
117
- };
118
- let disposer;
119
- const recorder = {
120
- actions,
121
- get recording() {
122
- return !!disposer;
123
- },
124
- stop() {
125
- if (disposer) {
126
- disposer();
127
- disposer = undefined;
128
- }
129
- },
130
- resume() {
131
- if (disposer) {
132
- return;
133
- }
134
- disposer = onAction(subject, listener);
135
- },
136
- replay(target) {
137
- applyAction(target, actions);
138
- }
139
- };
140
- recorder.resume();
141
- return recorder;
142
- }
143
- /**
144
- * Registers a function that will be invoked for each action that is called on the provided model instance, or to any of its children.
145
- * 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.
146
- * Action can also be intercepted by middleware using addMiddleware to change the function call before it will be run.
147
- *
148
- * Not all action arguments might be serializable. For unserializable arguments, a struct like `{ $MST_UNSERIALIZABLE: true, type: "someType" }` will be generated.
149
- * 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).
150
- * 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.
151
- *
152
- * Example:
153
- * ```ts
154
- * const Todo = types.model({
155
- * task: types.string
156
- * })
157
- *
158
- * const TodoStore = types.model({
159
- * todos: types.array(Todo)
160
- * }).actions(self => ({
161
- * add(todo) {
162
- * self.todos.push(todo);
163
- * }
164
- * }))
165
- *
166
- * const s = TodoStore.create({ todos: [] })
167
- *
168
- * let disposer = onAction(s, (call) => {
169
- * console.log(call);
170
- * })
171
- *
172
- * s.add({ task: "Grab a coffee" })
173
- * // Logs: { name: "add", path: "", args: [{ task: "Grab a coffee" }] }
174
- * ```
175
- *
176
- * @param target
177
- * @param listener
178
- * @param attachAfter (default false) fires the listener *after* the action has executed instead of before.
179
- * @returns
180
- */
181
- function onAction(target, listener, attachAfter = false) {
182
- // check all arguments
183
- (0, internal_ts_1.assertIsStateTreeNode)(target, 1);
184
- if ((0, internal_ts_1.devMode)()) {
185
- if (!(0, internal_ts_1.isRoot)(target)) {
186
- (0, internal_ts_1.warnError)("Warning: Attaching onAction listeners to non root nodes is dangerous: No events will be emitted for actions initiated higher up in the tree.");
187
- }
188
- if (!(0, internal_ts_1.isProtected)(target)) {
189
- (0, internal_ts_1.warnError)("Warning: Attaching onAction listeners to non protected nodes is dangerous: No events will be emitted for direct modifications without action.");
190
- }
191
- }
192
- return (0, internal_ts_1.addMiddleware)(target, function handler(rawCall, next) {
193
- if (rawCall.type === "action" && rawCall.id === rawCall.rootId) {
194
- const sourceNode = (0, internal_ts_1.getStateTreeNode)(rawCall.context);
195
- const info = {
196
- name: rawCall.name,
197
- path: (0, internal_ts_1.getRelativePathBetweenNodes)((0, internal_ts_1.getStateTreeNode)(target), sourceNode),
198
- args: rawCall.args.map((arg, index) => serializeArgument(sourceNode, rawCall.name, index, arg))
199
- };
200
- if (attachAfter) {
201
- const res = next(rawCall);
202
- listener(info);
203
- return res;
204
- }
205
- else {
206
- listener(info);
207
- return next(rawCall);
208
- }
209
- }
210
- else {
211
- return next(rawCall);
212
- }
213
- });
214
- }
215
- //# sourceMappingURL=on-action.js.map
@@ -1 +0,0 @@
1
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E,KAAK,OAAO,CAAC,MAAM,EAAE,CAAC;YAC/D,MAAM,UAAU,GAAG,IAAA,8BAAgB,EAAC,OAAO,CAAC,OAAO,CAAC,CAAA;YACpD,MAAM,IAAI,GAAG;gBACX,IAAI,EAAE,OAAO,CAAC,IAAI;gBAClB,IAAI,EAAE,IAAA,yCAA2B,EAAC,IAAA,8BAAgB,EAAC,MAAM,CAAC,EAAE,UAAU,CAAC;gBACvE,IAAI,EAAE,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,GAAQ,EAAE,KAAa,EAAE,EAAE,CACjD,iBAAiB,CAAC,UAAU,EAAE,OAAO,CAAC,IAAI,EAAE,KAAK,EAAE,GAAG,CAAC,CACxD;aACF,CAAA;YACD,IAAI,WAAW,EAAE,CAAC;gBAChB,MAAM,GAAG,GAAG,IAAI,CAAC,OAAO,CAAC,CAAA;gBACzB,QAAQ,CAAC,IAAI,CAAC,CAAA;gBACd,OAAO,GAAG,CAAA;YACZ,CAAC;iBAAM,CAAC;gBACN,QAAQ,CAAC,IAAI,CAAC,CAAA;gBACd,OAAO,IAAI,CAAC,OAAO,CAAC,CAAA;YACtB,CAAC;QACH,CAAC;aAAM,CAAC;YACN,OAAO,IAAI,CAAC,OAAO,CAAC,CAAA;QACtB,CAAC;IACH,CAAC,CAAC,CAAA;AACJ,CAAC","sourcesContent":["import { runInAction } from \"mobx\"\n\nimport {\n type AnyNode,\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(\n node: AnyNode,\n actionName: string,\n index: number,\n arg: any\n): 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 ${\n (arg && (arg as any).constructor && (arg as any).constructor.name) ||\n \"Complex Object\"\n }]`\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(adm: AnyNode, 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(v => deserializeArgument(node, v)) : [])\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((arg: any, index: number) =>\n serializeArgument(sourceNode, rawCall.name, index, arg)\n )\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"]}
package/dist/package.json DELETED
@@ -1 +0,0 @@
1
- {"type": "commonjs"}
@@ -1,81 +0,0 @@
1
- import { type IArrayDidChange, type IArraySplice, type IArrayWillChange, type IArrayWillSplice, type IObservableArray } from "mobx";
2
- import { ComplexType } from "../../core/type/type.ts";
3
- import { type AnyNode, type AnyObjectNode, type ExtractCSTWithSTN, type IAnyType, type IChildNodesMap, type IHooksGetter, type IJsonPatch, type IType, type IValidationContext, type IValidationResult, TypeFlags } from "../../internal.ts";
4
- /** @hidden */
5
- export interface IMSTArray<IT extends IAnyType> extends IObservableArray<IT["Type"]> {
6
- push(...items: IT["Type"][]): number;
7
- push(...items: ExtractCSTWithSTN<IT>[]): number;
8
- concat(...items: ConcatArray<IT["Type"]>[]): IT["Type"][];
9
- concat(...items: ConcatArray<ExtractCSTWithSTN<IT>>[]): IT["Type"][];
10
- concat(...items: (IT["Type"] | ConcatArray<IT["Type"]>)[]): IT["Type"][];
11
- concat(...items: (ExtractCSTWithSTN<IT> | ConcatArray<ExtractCSTWithSTN<IT>>)[]): IT["Type"][];
12
- splice(start: number, deleteCount?: number): IT["Type"][];
13
- splice(start: number, deleteCount: number, ...items: IT["Type"][]): IT["Type"][];
14
- splice(start: number, deleteCount: number, ...items: ExtractCSTWithSTN<IT>[]): IT["Type"][];
15
- unshift(...items: IT["Type"][]): number;
16
- unshift(...items: ExtractCSTWithSTN<IT>[]): number;
17
- }
18
- /** @hidden */
19
- export interface IArrayType<IT extends IAnyType> extends IType<readonly IT["CreationType"][] | undefined, IT["SnapshotType"][], IMSTArray<IT>> {
20
- hooks(hooks: IHooksGetter<IMSTArray<IAnyType>>): IArrayType<IT>;
21
- }
22
- /**
23
- * @internal
24
- * @hidden
25
- */
26
- export declare class ArrayType<IT extends IAnyType> extends ComplexType<readonly IT["CreationType"][] | undefined, IT["SnapshotType"][], IMSTArray<IT>> {
27
- private readonly _subType;
28
- readonly flags = TypeFlags.Array;
29
- private readonly hookInitializers;
30
- constructor(name: string, _subType: IT, hookInitializers?: Array<IHooksGetter<IMSTArray<IT>>>);
31
- hooks(hooks: IHooksGetter<IMSTArray<IT>>): ArrayType<IT>;
32
- instantiate(parent: AnyObjectNode | null, subpath: string, environment: any, initialValue: this["C"] | this["T"]): this["N"];
33
- initializeChildNodes(objNode: this["N"], snapshot?: this["C"]): IChildNodesMap;
34
- createNewInstance(childNodes: IChildNodesMap): this["T"];
35
- finalizeNewInstance(node: this["N"], instance: this["T"]): void;
36
- describe(): string;
37
- getChildren(node: this["N"]): AnyNode[];
38
- getChildNode(node: this["N"], key: string): AnyNode;
39
- willChange(change: IArrayWillChange<AnyNode> | IArrayWillSplice<AnyNode>): IArrayWillChange<AnyNode> | IArrayWillSplice<AnyNode> | null;
40
- getSnapshot(node: this["N"]): this["S"];
41
- processInitialSnapshot(childNodes: IChildNodesMap): this["S"];
42
- didChange(change: IArrayDidChange<AnyNode> | IArraySplice<AnyNode>): void;
43
- applyPatchLocally(node: this["N"], subpath: string, patch: IJsonPatch): void;
44
- applySnapshot(node: this["N"], snapshot: this["C"]): void;
45
- getChildType(): IAnyType;
46
- isValidSnapshot(value: this["C"], context: IValidationContext): IValidationResult;
47
- getDefaultSnapshot(): this["C"];
48
- removeChild(node: this["N"], subpath: string): void;
49
- }
50
- /**
51
- * `types.array` - Creates an index based collection type who's children are all of a uniform declared type.
52
- *
53
- * This type will always produce [observable arrays](https://mobx.js.org/api.html#observablearray)
54
- *
55
- * Example:
56
- * ```ts
57
- * const Todo = types.model({
58
- * task: types.string
59
- * })
60
- *
61
- * const TodoStore = types.model({
62
- * todos: types.array(Todo)
63
- * })
64
- *
65
- * const s = TodoStore.create({ todos: [] })
66
- * unprotect(s) // needed to allow modifying outside of an action
67
- * s.todos.push({ task: "Grab coffee" })
68
- * console.log(s.todos[0]) // prints: "Grab coffee"
69
- * ```
70
- *
71
- * @param subtype
72
- * @returns
73
- */
74
- export declare function array<IT extends IAnyType>(subtype: IT): IArrayType<IT>;
75
- /**
76
- * Returns if a given value represents an array type.
77
- *
78
- * @param type
79
- * @returns `true` if the type is an array type.
80
- */
81
- export declare function isArrayType<Items extends IAnyType = IAnyType>(type: IAnyType): type is IArrayType<Items>;
@@ -1,353 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ArrayType = void 0;
4
- exports.array = array;
5
- exports.isArrayType = isArrayType;
6
- const mobx_1 = require("mobx");
7
- const type_ts_1 = require("../../core/type/type.js");
8
- const internal_ts_1 = require("../../internal.js");
9
- /**
10
- * @internal
11
- * @hidden
12
- */
13
- class ArrayType extends type_ts_1.ComplexType {
14
- _subType;
15
- flags = internal_ts_1.TypeFlags.Array;
16
- hookInitializers = [];
17
- constructor(name, _subType, hookInitializers = []) {
18
- super(name);
19
- this._subType = _subType;
20
- this.hookInitializers = hookInitializers;
21
- }
22
- hooks(hooks) {
23
- const hookInitializers = this.hookInitializers.length > 0
24
- ? this.hookInitializers.concat(hooks)
25
- : [hooks];
26
- return new ArrayType(this.name, this._subType, hookInitializers);
27
- }
28
- instantiate(parent, subpath, environment, initialValue) {
29
- return (0, internal_ts_1.createObjectNode)(this, parent, subpath, environment, initialValue);
30
- }
31
- initializeChildNodes(objNode, snapshot = []) {
32
- const subType = objNode.type._subType;
33
- const result = {};
34
- snapshot.forEach((item, index) => {
35
- const subpath = "" + index;
36
- result[subpath] = subType.instantiate(objNode, subpath, undefined, item);
37
- });
38
- return result;
39
- }
40
- createNewInstance(childNodes) {
41
- const options = { ...internal_ts_1.mobxShallow, name: this.name };
42
- return mobx_1.observable.array((0, internal_ts_1.convertChildNodesToArray)(childNodes), options);
43
- }
44
- finalizeNewInstance(node, instance) {
45
- (0, mobx_1._getAdministration)(instance).dehancer = node.unbox;
46
- const type = node.type;
47
- type.hookInitializers.forEach(initializer => {
48
- const hooks = initializer(instance);
49
- Object.keys(hooks).forEach(name => {
50
- const hook = hooks[name];
51
- const actionInvoker = (0, internal_ts_1.createActionInvoker)(instance, name, hook);
52
- (!(0, internal_ts_1.devMode)() ? internal_ts_1.addHiddenFinalProp : internal_ts_1.addHiddenWritableProp)(instance, name, actionInvoker);
53
- });
54
- });
55
- (0, mobx_1.intercept)(instance, this.willChange);
56
- (0, mobx_1.observe)(instance, this.didChange);
57
- }
58
- describe() {
59
- return this.name;
60
- }
61
- getChildren(node) {
62
- return node.storedValue.slice();
63
- }
64
- getChildNode(node, key) {
65
- const index = Number(key);
66
- if (index < node.storedValue.length) {
67
- return node.storedValue[index];
68
- }
69
- throw (0, internal_ts_1.fail)("Not a child: " + key);
70
- }
71
- willChange(change) {
72
- const node = (0, internal_ts_1.getStateTreeNode)(change.object);
73
- node.assertWritable({ subpath: "" + change.index });
74
- const subType = node.type._subType;
75
- const childNodes = node.getChildren();
76
- switch (change.type) {
77
- case "update":
78
- {
79
- if (change.newValue === change.object[change.index]) {
80
- return null;
81
- }
82
- const updatedNodes = reconcileArrayChildren(node, subType, [childNodes[change.index]], [change.newValue], [change.index]);
83
- if (!updatedNodes) {
84
- return null;
85
- }
86
- change.newValue = updatedNodes[0];
87
- }
88
- break;
89
- case "splice":
90
- {
91
- const { index, removedCount, added } = change;
92
- const addedNodes = reconcileArrayChildren(node, subType, childNodes.slice(index, index + removedCount), added, added.map((_, i) => index + i));
93
- if (!addedNodes) {
94
- return null;
95
- }
96
- change.added = addedNodes;
97
- // update paths of remaining items
98
- for (let i = index + removedCount; i < childNodes.length; i++) {
99
- childNodes[i].setParent(node, "" + (i + added.length - removedCount));
100
- }
101
- }
102
- break;
103
- }
104
- return change;
105
- }
106
- getSnapshot(node) {
107
- return node.getChildren().map(childNode => childNode.snapshot);
108
- }
109
- processInitialSnapshot(childNodes) {
110
- const processed = [];
111
- Object.keys(childNodes).forEach(key => {
112
- processed.push(childNodes[key].getSnapshot());
113
- });
114
- return processed;
115
- }
116
- didChange(change) {
117
- const node = (0, internal_ts_1.getStateTreeNode)(change.object);
118
- switch (change.type) {
119
- case "update":
120
- return void node.emitPatch({
121
- op: "replace",
122
- path: "" + change.index,
123
- value: change.newValue.snapshot,
124
- oldValue: change.oldValue ? change.oldValue.snapshot : undefined
125
- }, node);
126
- case "splice":
127
- for (let i = change.removedCount - 1; i >= 0; i--) {
128
- node.emitPatch({
129
- op: "remove",
130
- path: "" + (change.index + i),
131
- oldValue: change.removed[i].snapshot
132
- }, node);
133
- }
134
- for (let i = 0; i < change.addedCount; i++) {
135
- node.emitPatch({
136
- op: "add",
137
- path: "" + (change.index + i),
138
- value: node.getChildNode("" + (change.index + i)).snapshot,
139
- oldValue: undefined
140
- }, node);
141
- }
142
- return;
143
- }
144
- }
145
- applyPatchLocally(node, subpath, patch) {
146
- const target = node.storedValue;
147
- const index = subpath === "-" ? target.length : Number(subpath);
148
- switch (patch.op) {
149
- case "replace":
150
- target[index] = patch.value;
151
- break;
152
- case "add":
153
- target.splice(index, 0, patch.value);
154
- break;
155
- case "remove":
156
- target.splice(index, 1);
157
- break;
158
- }
159
- }
160
- applySnapshot(node, snapshot) {
161
- (0, internal_ts_1.typecheckInternal)(this, snapshot);
162
- const target = node.storedValue;
163
- target.replace(snapshot);
164
- }
165
- getChildType() {
166
- return this._subType;
167
- }
168
- isValidSnapshot(value, context) {
169
- if (!(0, internal_ts_1.isArray)(value)) {
170
- return (0, internal_ts_1.typeCheckFailure)(context, value, "Value is not an array");
171
- }
172
- for (let i = 0; i < value.length; i++) {
173
- (0, internal_ts_1.getContextForPath)(context, "" + i, this._subType);
174
- const errors = this._subType.validate(value[i], context);
175
- (0, internal_ts_1.popContext)(context);
176
- if (errors.length > 0) {
177
- return errors;
178
- }
179
- }
180
- return (0, internal_ts_1.typeCheckSuccess)();
181
- }
182
- getDefaultSnapshot() {
183
- return internal_ts_1.EMPTY_ARRAY;
184
- }
185
- removeChild(node, subpath) {
186
- node.storedValue.splice(Number(subpath), 1);
187
- }
188
- }
189
- exports.ArrayType = ArrayType;
190
- ArrayType.prototype.applySnapshot = (0, mobx_1.action)(ArrayType.prototype.applySnapshot);
191
- /**
192
- * `types.array` - Creates an index based collection type who's children are all of a uniform declared type.
193
- *
194
- * This type will always produce [observable arrays](https://mobx.js.org/api.html#observablearray)
195
- *
196
- * Example:
197
- * ```ts
198
- * const Todo = types.model({
199
- * task: types.string
200
- * })
201
- *
202
- * const TodoStore = types.model({
203
- * todos: types.array(Todo)
204
- * })
205
- *
206
- * const s = TodoStore.create({ todos: [] })
207
- * unprotect(s) // needed to allow modifying outside of an action
208
- * s.todos.push({ task: "Grab coffee" })
209
- * console.log(s.todos[0]) // prints: "Grab coffee"
210
- * ```
211
- *
212
- * @param subtype
213
- * @returns
214
- */
215
- function array(subtype) {
216
- (0, internal_ts_1.assertIsType)(subtype, 1);
217
- return new ArrayType(`${subtype.name}[]`, subtype);
218
- }
219
- function reconcileArrayChildren(parent, childType, oldNodes, newValues, newPaths) {
220
- let nothingChanged = true;
221
- for (let i = 0;; i++) {
222
- const hasNewNode = i <= newValues.length - 1;
223
- const oldNode = oldNodes[i];
224
- let newValue = hasNewNode ? newValues[i] : undefined;
225
- const newPath = "" + newPaths[i];
226
- // for some reason, instead of newValue we got a node, fallback to the storedValue
227
- // TODO: https://github.com/mobxjs/mobx-state-tree/issues/340#issuecomment-325581681
228
- if ((0, internal_ts_1.isNode)(newValue)) {
229
- newValue = newValue.storedValue;
230
- }
231
- if (!oldNode && !hasNewNode) {
232
- // both are empty, end
233
- break;
234
- }
235
- else if (!hasNewNode) {
236
- // new one does not exists
237
- nothingChanged = false;
238
- oldNodes.splice(i, 1);
239
- if (oldNode instanceof internal_ts_1.ObjectNode) {
240
- // since it is going to be returned by pop/splice/shift better create it before killing it
241
- // so it doesn't end up in an undead state
242
- oldNode.createObservableInstanceIfNeeded();
243
- }
244
- oldNode.die();
245
- i--;
246
- }
247
- else if (!oldNode) {
248
- // there is no old node, create it
249
- // check if already belongs to the same parent. if so, avoid pushing item in. only swapping can occur.
250
- if ((0, internal_ts_1.isStateTreeNode)(newValue) &&
251
- (0, internal_ts_1.getStateTreeNode)(newValue).parent === parent) {
252
- // this node is owned by this parent, but not in the reconcilable set, so it must be double
253
- throw (0, internal_ts_1.fail)(`Cannot add an object to a state tree if it is already part of the same or another state tree. Tried to assign an object to '${parent.path}/${newPath}', but it lives already at '${(0, internal_ts_1.getStateTreeNode)(newValue).path}'`);
254
- }
255
- nothingChanged = false;
256
- const newNode = valueAsNode(childType, parent, newPath, newValue);
257
- oldNodes.splice(i, 0, newNode);
258
- }
259
- else if (areSame(oldNode, newValue)) {
260
- // both are the same, reconcile
261
- oldNodes[i] = valueAsNode(childType, parent, newPath, newValue, oldNode);
262
- }
263
- else {
264
- // nothing to do, try to reorder
265
- let oldMatch = undefined;
266
- // find a possible candidate to reuse
267
- for (let j = i; j < oldNodes.length; j++) {
268
- if (areSame(oldNodes[j], newValue)) {
269
- oldMatch = oldNodes.splice(j, 1)[0];
270
- break;
271
- }
272
- }
273
- nothingChanged = false;
274
- const newNode = valueAsNode(childType, parent, newPath, newValue, oldMatch);
275
- oldNodes.splice(i, 0, newNode);
276
- }
277
- }
278
- return nothingChanged ? null : oldNodes;
279
- }
280
- /**
281
- * Convert a value to a node at given parent and subpath. Attempts to reuse old node if possible and given.
282
- */
283
- function valueAsNode(childType, parent, subpath, newValue, oldNode) {
284
- // ensure the value is valid-ish
285
- (0, internal_ts_1.typecheckInternal)(childType, newValue);
286
- function getNewNode() {
287
- // the new value has a MST node
288
- if ((0, internal_ts_1.isStateTreeNode)(newValue)) {
289
- const childNode = (0, internal_ts_1.getStateTreeNode)(newValue);
290
- childNode.assertAlive(internal_ts_1.EMPTY_OBJECT);
291
- // the node lives here
292
- if (childNode.parent !== null && childNode.parent === parent) {
293
- childNode.setParent(parent, subpath);
294
- return childNode;
295
- }
296
- }
297
- // there is old node and new one is a value/snapshot
298
- if (oldNode) {
299
- return childType.reconcile(oldNode, newValue, parent, subpath);
300
- }
301
- // nothing to do, create from scratch
302
- return childType.instantiate(parent, subpath, undefined, newValue);
303
- }
304
- const newNode = getNewNode();
305
- if (oldNode && oldNode !== newNode) {
306
- if (oldNode instanceof internal_ts_1.ObjectNode) {
307
- // since it is going to be returned by pop/splice/shift better create it before killing it
308
- // so it doesn't end up in an undead state
309
- oldNode.createObservableInstanceIfNeeded();
310
- }
311
- oldNode.die();
312
- }
313
- return newNode;
314
- }
315
- /**
316
- * Check if a node holds a value.
317
- */
318
- function areSame(oldNode, newValue) {
319
- // never consider dead old nodes for reconciliation
320
- if (!oldNode.isAlive) {
321
- return false;
322
- }
323
- // the new value has the same node
324
- if ((0, internal_ts_1.isStateTreeNode)(newValue)) {
325
- const newNode = (0, internal_ts_1.getStateTreeNode)(newValue);
326
- return newNode.isAlive && newNode === oldNode;
327
- }
328
- // the provided value is the snapshot of the old node
329
- if (oldNode.snapshot === newValue) {
330
- return true;
331
- }
332
- // Non object nodes don't get reconciled
333
- if (!(oldNode instanceof internal_ts_1.ObjectNode)) {
334
- return false;
335
- }
336
- const oldNodeType = oldNode.getReconciliationType();
337
- // new value is a snapshot with the correct identifier
338
- return (oldNode.identifier !== null &&
339
- oldNode.identifierAttribute &&
340
- (0, internal_ts_1.isPlainObject)(newValue) &&
341
- oldNodeType.is(newValue) &&
342
- oldNodeType.isMatchingSnapshotId(oldNode, newValue));
343
- }
344
- /**
345
- * Returns if a given value represents an array type.
346
- *
347
- * @param type
348
- * @returns `true` if the type is an array type.
349
- */
350
- function isArrayType(type) {
351
- return (0, internal_ts_1.isType)(type) && (type.flags & internal_ts_1.TypeFlags.Array) > 0;
352
- }
353
- //# sourceMappingURL=array.js.map