mobx-state-tree 3.14.1 → 3.17.2

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.
@@ -2,7 +2,7 @@
2
2
  typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('mobx')) :
3
3
  typeof define === 'function' && define.amd ? define(['exports', 'mobx'], factory) :
4
4
  (global = global || self, factory(global.mobxStateTree = {}, global.mobx));
5
- }(this, function (exports, mobx) { 'use strict';
5
+ }(this, (function (exports, mobx) { 'use strict';
6
6
 
7
7
  var livelinessChecking = "warn";
8
8
  /**
@@ -38,7 +38,6 @@
38
38
  }
39
39
 
40
40
  /**
41
- * @internal
42
41
  * @hidden
43
42
  */
44
43
  var Hook;
@@ -51,18 +50,18 @@
51
50
  })(Hook || (Hook = {}));
52
51
 
53
52
  /*! *****************************************************************************
54
- Copyright (c) Microsoft Corporation. All rights reserved.
55
- Licensed under the Apache License, Version 2.0 (the "License"); you may not use
56
- this file except in compliance with the License. You may obtain a copy of the
57
- License at http://www.apache.org/licenses/LICENSE-2.0
53
+ Copyright (c) Microsoft Corporation.
58
54
 
59
- THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
60
- KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
61
- WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
62
- MERCHANTABLITY OR NON-INFRINGEMENT.
55
+ Permission to use, copy, modify, and/or distribute this software for any
56
+ purpose with or without fee is hereby granted.
63
57
 
64
- See the Apache Version 2.0 License for specific language governing permissions
65
- and limitations under the License.
58
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
59
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
60
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
61
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
62
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
63
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
64
+ PERFORMANCE OF THIS SOFTWARE.
66
65
  ***************************************************************************** */
67
66
  /* global Reflect, Promise */
68
67
 
@@ -109,15 +108,44 @@
109
108
  return c > 3 && r && Object.defineProperty(target, key, r), r;
110
109
  }
111
110
 
111
+ function __generator(thisArg, body) {
112
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
113
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
114
+ function verb(n) { return function (v) { return step([n, v]); }; }
115
+ function step(op) {
116
+ if (f) throw new TypeError("Generator is already executing.");
117
+ while (_) try {
118
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
119
+ if (y = 0, t) op = [op[0] & 2, t.value];
120
+ switch (op[0]) {
121
+ case 0: case 1: t = op; break;
122
+ case 4: _.label++; return { value: op[1], done: false };
123
+ case 5: _.label++; y = op[1]; op = [0]; continue;
124
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
125
+ default:
126
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
127
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
128
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
129
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
130
+ if (t[2]) _.ops.pop();
131
+ _.trys.pop(); continue;
132
+ }
133
+ op = body.call(thisArg, _);
134
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
135
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
136
+ }
137
+ }
138
+
112
139
  function __values(o) {
113
- var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0;
140
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
114
141
  if (m) return m.call(o);
115
- return {
142
+ if (o && typeof o.length === "number") return {
116
143
  next: function () {
117
144
  if (o && i >= o.length) o = void 0;
118
145
  return { value: o && o[i++], done: !o };
119
146
  }
120
147
  };
148
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
121
149
  }
122
150
 
123
151
  function __read(o, n) {
@@ -825,7 +853,7 @@
825
853
  */
826
854
  function getMembers(target) {
827
855
  var type = getStateTreeNode(target).type;
828
- var reflected = __assign({}, getPropertyMembers(type), { actions: [], volatile: [], views: [] });
856
+ var reflected = __assign(__assign({}, getPropertyMembers(type)), { actions: [], volatile: [], views: [] });
829
857
  var props = Object.getOwnPropertyNames(target);
830
858
  props.forEach(function (key) {
831
859
  if (key in reflected.properties)
@@ -970,28 +998,28 @@
970
998
  get: function () {
971
999
  return this._subpath;
972
1000
  },
973
- enumerable: true,
1001
+ enumerable: false,
974
1002
  configurable: true
975
1003
  });
976
1004
  Object.defineProperty(BaseNode.prototype, "subpathUponDeath", {
977
1005
  get: function () {
978
1006
  return this._subpathUponDeath;
979
1007
  },
980
- enumerable: true,
1008
+ enumerable: false,
981
1009
  configurable: true
982
1010
  });
983
1011
  Object.defineProperty(BaseNode.prototype, "pathUponDeath", {
984
1012
  get: function () {
985
1013
  return this._pathUponDeath;
986
1014
  },
987
- enumerable: true,
1015
+ enumerable: false,
988
1016
  configurable: true
989
1017
  });
990
1018
  Object.defineProperty(BaseNode.prototype, "value", {
991
1019
  get: function () {
992
1020
  return this.type.getValue(this);
993
1021
  },
994
- enumerable: true,
1022
+ enumerable: false,
995
1023
  configurable: true
996
1024
  });
997
1025
  Object.defineProperty(BaseNode.prototype, "state", {
@@ -1006,7 +1034,7 @@
1006
1034
  this.aliveAtom.reportChanged();
1007
1035
  }
1008
1036
  },
1009
- enumerable: true,
1037
+ enumerable: false,
1010
1038
  configurable: true
1011
1039
  });
1012
1040
  BaseNode.prototype.fireInternalHook = function (name) {
@@ -1024,7 +1052,7 @@
1024
1052
  get: function () {
1025
1053
  return this._parent;
1026
1054
  },
1027
- enumerable: true,
1055
+ enumerable: false,
1028
1056
  configurable: true
1029
1057
  });
1030
1058
  BaseNode.prototype.baseSetParent = function (parent, subpath) {
@@ -1042,7 +1070,7 @@
1042
1070
  get: function () {
1043
1071
  return this.getEscapedPath(true);
1044
1072
  },
1045
- enumerable: true,
1073
+ enumerable: false,
1046
1074
  configurable: true
1047
1075
  });
1048
1076
  BaseNode.prototype.getEscapedPath = function (reportObserved) {
@@ -1064,21 +1092,21 @@
1064
1092
  get: function () {
1065
1093
  return this.parent === null;
1066
1094
  },
1067
- enumerable: true,
1095
+ enumerable: false,
1068
1096
  configurable: true
1069
1097
  });
1070
1098
  Object.defineProperty(BaseNode.prototype, "isAlive", {
1071
1099
  get: function () {
1072
1100
  return this.state !== NodeLifeCycle.DEAD;
1073
1101
  },
1074
- enumerable: true,
1102
+ enumerable: false,
1075
1103
  configurable: true
1076
1104
  });
1077
1105
  Object.defineProperty(BaseNode.prototype, "isDetaching", {
1078
1106
  get: function () {
1079
1107
  return this.state === NodeLifeCycle.DETACHING;
1080
1108
  },
1081
- enumerable: true,
1109
+ enumerable: false,
1082
1110
  configurable: true
1083
1111
  });
1084
1112
  Object.defineProperty(BaseNode.prototype, "observableIsAlive", {
@@ -1089,11 +1117,11 @@
1089
1117
  this.aliveAtom.reportObserved();
1090
1118
  return this.isAlive;
1091
1119
  },
1092
- enumerable: true,
1120
+ enumerable: false,
1093
1121
  configurable: true
1094
1122
  });
1095
1123
  BaseNode.prototype.baseFinalizeCreation = function (whenFinalized) {
1096
- if (devMode()) {
1124
+ {
1097
1125
  if (!this.isAlive) {
1098
1126
  // istanbul ignore next
1099
1127
  throw fail("assertion failed: cannot finalize the creation of a node that is already dead");
@@ -1159,7 +1187,7 @@
1159
1187
  throw fail$1("This scalar node is not part of a tree");
1160
1188
  return this.parent.root;
1161
1189
  },
1162
- enumerable: true,
1190
+ enumerable: false,
1163
1191
  configurable: true
1164
1192
  });
1165
1193
  ScalarNode.prototype.setParent = function (newParent, subpath) {
@@ -1168,7 +1196,7 @@
1168
1196
  if (!parentChanged && !subpathChanged) {
1169
1197
  return;
1170
1198
  }
1171
- if (devMode()) {
1199
+ {
1172
1200
  if (!subpath) {
1173
1201
  // istanbul ignore next
1174
1202
  throw fail$1("assertion failed: subpath expected");
@@ -1189,7 +1217,7 @@
1189
1217
  get: function () {
1190
1218
  return freeze(this.getSnapshot());
1191
1219
  },
1192
- enumerable: true,
1220
+ enumerable: false,
1193
1221
  configurable: true
1194
1222
  });
1195
1223
  ScalarNode.prototype.getSnapshot = function () {
@@ -1288,11 +1316,13 @@
1288
1316
  this._applySnapshot(snapshot);
1289
1317
  };
1290
1318
  ObjectNode.prototype.createObservableInstanceIfNeeded = function () {
1291
- var e_1, _a;
1292
- if (this._observableInstanceState !== 0 /* UNINITIALIZED */) {
1293
- return;
1319
+ if (this._observableInstanceState === 0 /* UNINITIALIZED */) {
1320
+ this.createObservableInstance();
1294
1321
  }
1295
- if (devMode()) {
1322
+ };
1323
+ ObjectNode.prototype.createObservableInstance = function () {
1324
+ var e_1, _a;
1325
+ {
1296
1326
  if (this.state !== NodeLifeCycle.INITIALIZING) {
1297
1327
  // istanbul ignore next
1298
1328
  throw fail$1("assertion failed: the creation of the observable instance must be done on the initializing phase");
@@ -1357,7 +1387,7 @@
1357
1387
  var parent = this.parent;
1358
1388
  return parent ? parent.root : this;
1359
1389
  },
1360
- enumerable: true,
1390
+ enumerable: false,
1361
1391
  configurable: true
1362
1392
  });
1363
1393
  ObjectNode.prototype.clearParent = function () {
@@ -1386,7 +1416,7 @@
1386
1416
  if (!parentChanged && !subpathChanged) {
1387
1417
  return;
1388
1418
  }
1389
- if (devMode()) {
1419
+ {
1390
1420
  if (!subpath) {
1391
1421
  // istanbul ignore next
1392
1422
  throw fail$1("assertion failed: subpath expected");
@@ -1442,7 +1472,7 @@
1442
1472
  get: function () {
1443
1473
  return freeze(this.getSnapshot());
1444
1474
  },
1445
- enumerable: true,
1475
+ enumerable: false,
1446
1476
  configurable: true
1447
1477
  });
1448
1478
  // NOTE: we use this method to get snapshot without creating @computed overhead
@@ -1535,7 +1565,7 @@
1535
1565
  get: function () {
1536
1566
  return this.root.isProtectionEnabled;
1537
1567
  },
1538
- enumerable: true,
1568
+ enumerable: false,
1539
1569
  configurable: true
1540
1570
  });
1541
1571
  ObjectNode.prototype.assertWritable = function (context) {
@@ -1749,7 +1779,7 @@
1749
1779
  };
1750
1780
  __decorate([
1751
1781
  mobx.action
1752
- ], ObjectNode.prototype, "createObservableInstanceIfNeeded", null);
1782
+ ], ObjectNode.prototype, "createObservableInstance", null);
1753
1783
  __decorate([
1754
1784
  mobx.computed
1755
1785
  ], ObjectNode.prototype, "snapshot", null);
@@ -1835,7 +1865,7 @@
1835
1865
  // istanbul ignore next
1836
1866
  throw fail$1("Factory.Type should not be actually called. It is just a Type signature that can be used at compile time with Typescript, by using `typeof type.Type`");
1837
1867
  },
1838
- enumerable: true,
1868
+ enumerable: false,
1839
1869
  configurable: true
1840
1870
  });
1841
1871
  Object.defineProperty(BaseType.prototype, "TypeWithoutSTN", {
@@ -1843,7 +1873,7 @@
1843
1873
  // istanbul ignore next
1844
1874
  throw fail$1("Factory.TypeWithoutSTN should not be actually called. It is just a Type signature that can be used at compile time with Typescript, by using `typeof type.TypeWithoutSTN`");
1845
1875
  },
1846
- enumerable: true,
1876
+ enumerable: false,
1847
1877
  configurable: true
1848
1878
  });
1849
1879
  Object.defineProperty(BaseType.prototype, "SnapshotType", {
@@ -1851,7 +1881,7 @@
1851
1881
  // istanbul ignore next
1852
1882
  throw fail$1("Factory.SnapshotType should not be actually called. It is just a Type signature that can be used at compile time with Typescript, by using `typeof type.SnapshotType`");
1853
1883
  },
1854
- enumerable: true,
1884
+ enumerable: false,
1855
1885
  configurable: true
1856
1886
  });
1857
1887
  Object.defineProperty(BaseType.prototype, "CreationType", {
@@ -1859,7 +1889,7 @@
1859
1889
  // istanbul ignore next
1860
1890
  throw fail$1("Factory.CreationType should not be actually called. It is just a Type signature that can be used at compile time with Typescript, by using `typeof type.CreationType`");
1861
1891
  },
1862
- enumerable: true,
1892
+ enumerable: false,
1863
1893
  configurable: true
1864
1894
  });
1865
1895
  __decorate([
@@ -2096,7 +2126,7 @@
2096
2126
  get: function () {
2097
2127
  return this.flowsPending > 0;
2098
2128
  },
2099
- enumerable: true,
2129
+ enumerable: false,
2100
2130
  configurable: true
2101
2131
  });
2102
2132
  return RunningAction;
@@ -2132,7 +2162,7 @@
2132
2162
  ? runningActions.get(call.parentActionEvent)
2133
2163
  : undefined;
2134
2164
  if (call.type === "action") {
2135
- var newCall = __assign({}, call, {
2165
+ var newCall = __assign(__assign({}, call), {
2136
2166
  // make a shallow copy of the parent action env
2137
2167
  env: parentRunningAction && parentRunningAction.call.env, parentCall: parentRunningAction && parentRunningAction.call });
2138
2168
  var passesFilter = !middlewareHooks.filter || middlewareHooks.filter(newCall);
@@ -2362,7 +2392,7 @@
2362
2392
  if (attachAfter === void 0) { attachAfter = false; }
2363
2393
  // check all arguments
2364
2394
  assertIsStateTreeNode(target, 1);
2365
- if (devMode()) {
2395
+ {
2366
2396
  if (!isRoot(target))
2367
2397
  warnError("Warning: Attaching onAction listeners to non root nodes is dangerous: No events will be emitted for actions initiated higher up in the tree.");
2368
2398
  if (!isProtected(target))
@@ -2476,7 +2506,7 @@
2476
2506
  * Middleware can be used to intercept any action is invoked on the subtree where it is attached.
2477
2507
  * If a tree is protected (by default), this means that any mutation of the tree will pass through your middleware.
2478
2508
  *
2479
- * For more details, see the [middleware docs](../middleware.md)
2509
+ * For more details, see the [middleware docs](concepts/middleware.md)
2480
2510
  *
2481
2511
  * @param target Node to apply the middleware to.
2482
2512
  * @param middleware Middleware to apply.
@@ -2485,7 +2515,7 @@
2485
2515
  function addMiddleware(target, handler, includeHooks) {
2486
2516
  if (includeHooks === void 0) { includeHooks = true; }
2487
2517
  var node = getStateTreeNode(target);
2488
- if (devMode()) {
2518
+ {
2489
2519
  if (!node.isProtectionEnabled) {
2490
2520
  warnError("It is recommended to protect the state tree before attaching action middleware, as otherwise it cannot be guaranteed that all changes are passed through middleware. See `protect`");
2491
2521
  }
@@ -2543,7 +2573,7 @@
2543
2573
  get: function () {
2544
2574
  return this.middlewares.length <= 0;
2545
2575
  },
2546
- enumerable: true,
2576
+ enumerable: false,
2547
2577
  configurable: true
2548
2578
  });
2549
2579
  CollectedMiddlewares.prototype.getNextMiddleware = function () {
@@ -2596,7 +2626,7 @@
2596
2626
  result = value;
2597
2627
  }
2598
2628
  handler(call, next, abort);
2599
- if (devMode()) {
2629
+ {
2600
2630
  if (!nextInvoked && !abortInvoked) {
2601
2631
  var node2 = getStateTreeNode(call.tree);
2602
2632
  throw fail$1("Neither the next() nor the abort() callback within the middleware " + handler.name + " for the action: \"" + call.name + "\" on the node: " + node2.type.name + " was invoked.");
@@ -2735,7 +2765,7 @@
2735
2765
  */
2736
2766
  function typecheckInternal(type, value) {
2737
2767
  // runs typeChecking if it is in dev-mode or through a process.env.ENABLE_TYPE_CHECK flag
2738
- if (isTypeCheckingEnabled()) {
2768
+ {
2739
2769
  typecheck(type, value);
2740
2770
  }
2741
2771
  }
@@ -2974,10 +3004,7 @@
2974
3004
  break;
2975
3005
  }
2976
3006
  // TODO: assert that no targetParts paths are "..", "." or ""!
2977
- return (baseParts
2978
- .slice(common)
2979
- .map(doubleDot)
2980
- .join("/") + joinJsonPath(targetParts.slice(common)));
3007
+ return (baseParts.slice(common).map(doubleDot).join("/") + joinJsonPath(targetParts.slice(common)));
2981
3008
  }
2982
3009
  /**
2983
3010
  * @internal
@@ -3032,8 +3059,7 @@
3032
3059
  }
3033
3060
  }
3034
3061
  if (failIfResolveFails)
3035
- throw fail$1("Could not resolve '" + part + "' in path '" + (joinJsonPath(pathParts.slice(0, i)) ||
3036
- "/") + "' while resolving '" + joinJsonPath(pathParts) + "'");
3062
+ throw fail$1("Could not resolve '" + part + "' in path '" + (joinJsonPath(pathParts.slice(0, i)) || "/") + "' while resolving '" + joinJsonPath(pathParts) + "'");
3037
3063
  else
3038
3064
  return undefined;
3039
3065
  }
@@ -3076,7 +3102,7 @@
3076
3102
  *
3077
3103
  * @returns {Promise}
3078
3104
  */
3079
- function process$1(asyncAction) {
3105
+ function process(asyncAction) {
3080
3106
  deprecated("process", "`process()` has been renamed to `flow()`. " + DEPRECATION_MESSAGE);
3081
3107
  return flow(asyncAction);
3082
3108
  }
@@ -3197,8 +3223,6 @@
3197
3223
  * Freeze a value and return it (if not in production)
3198
3224
  */
3199
3225
  function freeze(value) {
3200
- if (!devMode())
3201
- return value;
3202
3226
  return isPrimitive(value) || mobx.isObservableArray(value) ? value : Object.freeze(value);
3203
3227
  }
3204
3228
  /**
@@ -3207,8 +3231,6 @@
3207
3231
  * Recursively freeze a value (if not in production)
3208
3232
  */
3209
3233
  function deepFreeze(value) {
3210
- if (!devMode())
3211
- return value;
3212
3234
  freeze(value);
3213
3235
  if (isPlainObject(value)) {
3214
3236
  Object.keys(value).forEach(function (propKey) {
@@ -3263,7 +3285,7 @@
3263
3285
  get: function () {
3264
3286
  return this.handlers.length > 0;
3265
3287
  },
3266
- enumerable: true,
3288
+ enumerable: false,
3267
3289
  configurable: true
3268
3290
  });
3269
3291
  EventHandler.prototype.register = function (fn, atTheBeginning) {
@@ -3385,9 +3407,6 @@
3385
3407
  * @hidden
3386
3408
  */
3387
3409
  var deprecated = function (id, message) {
3388
- // skip if running production
3389
- if (!devMode())
3390
- return;
3391
3410
  // warn if hasn't been warned before
3392
3411
  if (deprecated.ids && !deprecated.ids.hasOwnProperty(id)) {
3393
3412
  warnError("Deprecation warning: " + message);
@@ -3404,27 +3423,12 @@
3404
3423
  function warnError(msg) {
3405
3424
  console.warn(new Error("[mobx-state-tree] " + msg));
3406
3425
  }
3407
- /**
3408
- * @internal
3409
- * @hidden
3410
- */
3411
- function isTypeCheckingEnabled() {
3412
- return (devMode() ||
3413
- (typeof process !== "undefined" && process.env && process.env.ENABLE_TYPE_CHECK === "true"));
3414
- }
3415
- /**
3416
- * @internal
3417
- * @hidden
3418
- */
3419
- function devMode() {
3420
- return process.env.NODE_ENV !== "production";
3421
- }
3422
3426
  /**
3423
3427
  * @internal
3424
3428
  * @hidden
3425
3429
  */
3426
3430
  function assertArg(value, fn, typeName, argNumber) {
3427
- if (devMode()) {
3431
+ {
3428
3432
  if (!fn(value)) {
3429
3433
  // istanbul ignore next
3430
3434
  throw fail$1("expected " + typeName + " as argument " + asArray(argNumber).join(" or ") + ", got " + value + " instead");
@@ -3462,9 +3466,24 @@
3462
3466
  assertArg(value, function (s) { return s !== ""; }, "not empty string", argNumber);
3463
3467
  }
3464
3468
  }
3469
+ /**
3470
+ * @internal
3471
+ * @hidden
3472
+ */
3473
+ function setImmediateWithFallback(fn) {
3474
+ if (typeof queueMicrotask === "function") {
3475
+ queueMicrotask(fn);
3476
+ }
3477
+ else if (typeof setImmediate === "function") {
3478
+ setImmediate(fn);
3479
+ }
3480
+ else {
3481
+ setTimeout(fn, 1);
3482
+ }
3483
+ }
3465
3484
 
3466
3485
  /**
3467
- * See [asynchronous actions](https://github.com/mobxjs/mobx-state-tree/blob/master/docs/async-actions.md).
3486
+ * See [asynchronous actions](concepts/async-actions.md).
3468
3487
  *
3469
3488
  * @returns The flow as a promise.
3470
3489
  */
@@ -3472,7 +3491,8 @@
3472
3491
  return createFlowSpawner(generator.name, generator);
3473
3492
  }
3474
3493
  /**
3475
- * Used for TypeScript to make flows that return a promise return the actual promise result.
3494
+ * @deprecated Not needed since TS3.6.
3495
+ * Used for TypeScript to make flows that return a promise return the actual promise result.
3476
3496
  *
3477
3497
  * @param val
3478
3498
  * @returns
@@ -3480,6 +3500,72 @@
3480
3500
  function castFlowReturn(val) {
3481
3501
  return val;
3482
3502
  }
3503
+ /**
3504
+ * @experimental
3505
+ * experimental api - might change on minor/patch releases
3506
+ *
3507
+ * Convert a promise-returning function to a generator-returning one.
3508
+ * This is intended to allow for usage of `yield*` in async actions to
3509
+ * retain the promise return type.
3510
+ *
3511
+ * Example:
3512
+ * ```ts
3513
+ * function getDataAsync(input: string): Promise<number> { ... }
3514
+ * const getDataGen = toGeneratorFunction(getDataAsync);
3515
+ *
3516
+ * const someModel.actions(self => ({
3517
+ * someAction: flow(function*() {
3518
+ * // value is typed as number
3519
+ * const value = yield* getDataGen("input value");
3520
+ * ...
3521
+ * })
3522
+ * }))
3523
+ * ```
3524
+ */
3525
+ function toGeneratorFunction(p) {
3526
+ return function () {
3527
+ var _i;
3528
+ var args = [];
3529
+ for (_i = 0; _i < arguments.length; _i++) {
3530
+ args[_i] = arguments[_i];
3531
+ }
3532
+ return __generator(this, function (_a) {
3533
+ switch (_a.label) {
3534
+ case 0: return [4 /*yield*/, p.apply(void 0, __spread(args))];
3535
+ case 1: return [2 /*return*/, (_a.sent())];
3536
+ }
3537
+ });
3538
+ };
3539
+ }
3540
+ /**
3541
+ * @experimental
3542
+ * experimental api - might change on minor/patch releases
3543
+ *
3544
+ * Convert a promise to a generator yielding that promise
3545
+ * This is intended to allow for usage of `yield*` in async actions to
3546
+ * retain the promise return type.
3547
+ *
3548
+ * Example:
3549
+ * ```ts
3550
+ * function getDataAsync(input: string): Promise<number> { ... }
3551
+ *
3552
+ * const someModel.actions(self => ({
3553
+ * someAction: flow(function*() {
3554
+ * // value is typed as number
3555
+ * const value = yield* toGenerator(getDataAsync("input value"));
3556
+ * ...
3557
+ * })
3558
+ * }))
3559
+ * ```
3560
+ */
3561
+ function toGenerator(p) {
3562
+ return __generator(this, function (_a) {
3563
+ switch (_a.label) {
3564
+ case 0: return [4 /*yield*/, p];
3565
+ case 1: return [2 /*return*/, (_a.sent())];
3566
+ }
3567
+ });
3568
+ }
3483
3569
  /**
3484
3570
  * @internal
3485
3571
  * @hidden
@@ -3510,7 +3596,7 @@
3510
3596
  var args = arguments;
3511
3597
  function wrap(fn, type, arg) {
3512
3598
  fn.$mst_middleware = spawner.$mst_middleware; // pick up any middleware attached to the flow
3513
- runWithActionContext(__assign({}, contextBase, { type: type, args: [arg] }), fn);
3599
+ runWithActionContext(__assign(__assign({}, contextBase), { type: type, args: [arg] }), fn);
3514
3600
  }
3515
3601
  return new Promise(function (resolve, reject) {
3516
3602
  var gen;
@@ -3519,7 +3605,7 @@
3519
3605
  onFulfilled(undefined); // kick off the flow
3520
3606
  };
3521
3607
  init.$mst_middleware = spawner.$mst_middleware;
3522
- runWithActionContext(__assign({}, contextBase, { type: "flow_spawn", args: argsToArray(args) }), init);
3608
+ runWithActionContext(__assign(__assign({}, contextBase), { type: "flow_spawn", args: argsToArray(args) }), init);
3523
3609
  function onFulfilled(res) {
3524
3610
  var ret;
3525
3611
  try {
@@ -3528,7 +3614,7 @@
3528
3614
  }
3529
3615
  catch (e) {
3530
3616
  // prettier-ignore
3531
- setImmediate(function () {
3617
+ setImmediateWithFallback(function () {
3532
3618
  wrap(function (r) { reject(e); }, "flow_throw", e);
3533
3619
  });
3534
3620
  return;
@@ -3544,7 +3630,7 @@
3544
3630
  }
3545
3631
  catch (e) {
3546
3632
  // prettier-ignore
3547
- setImmediate(function () {
3633
+ setImmediateWithFallback(function () {
3548
3634
  wrap(function (r) { reject(e); }, "flow_throw", e);
3549
3635
  });
3550
3636
  return;
@@ -3554,7 +3640,7 @@
3554
3640
  function next(ret) {
3555
3641
  if (ret.done) {
3556
3642
  // prettier-ignore
3557
- setImmediate(function () {
3643
+ setImmediateWithFallback(function () {
3558
3644
  wrap(function (r) { resolve(r); }, "flow_return", ret.value);
3559
3645
  });
3560
3646
  return;
@@ -3704,7 +3790,7 @@
3704
3790
  get: function () {
3705
3791
  return this._subtype.flags | TypeFlags.SnapshotProcessor;
3706
3792
  },
3707
- enumerable: true,
3793
+ enumerable: false,
3708
3794
  configurable: true
3709
3795
  });
3710
3796
  SnapshotProcessor.prototype.describe = function () {
@@ -3759,9 +3845,12 @@
3759
3845
  return this._subtype;
3760
3846
  };
3761
3847
  SnapshotProcessor.prototype.is = function (thing) {
3762
- return (this._subtype.validate(isType(thing) ? this._subtype : this.preProcessSnapshot(thing), [
3763
- { path: "", type: this._subtype }
3764
- ]).length === 0);
3848
+ var value = isType(thing)
3849
+ ? this._subtype
3850
+ : isStateTreeNode(thing)
3851
+ ? getSnapshot(thing, false)
3852
+ : this.preProcessSnapshot(thing);
3853
+ return this._subtype.validate(value, [{ path: "", type: this._subtype }]).length === 0;
3765
3854
  };
3766
3855
  return SnapshotProcessor;
3767
3856
  }(BaseType));
@@ -3818,7 +3907,7 @@
3818
3907
  */
3819
3908
  function snapshotProcessor(type, processors, name) {
3820
3909
  assertIsType(type, 1);
3821
- if (devMode()) {
3910
+ {
3822
3911
  if (processors.postProcessor && typeof processors.postProcessor !== "function") {
3823
3912
  // istanbul ignore next
3824
3913
  throw fail("postSnapshotProcessor must be a function");
@@ -3893,7 +3982,7 @@
3893
3982
  throw fail$1("Map.put cannot be used to set empty values");
3894
3983
  if (isStateTreeNode(value)) {
3895
3984
  var node = getStateTreeNode(value);
3896
- if (devMode()) {
3985
+ {
3897
3986
  if (!node.identifierAttribute) {
3898
3987
  throw fail$1(needsIdentifierError);
3899
3988
  }
@@ -3934,15 +4023,22 @@
3934
4023
  */
3935
4024
  var MapType = /** @class */ (function (_super) {
3936
4025
  __extends(MapType, _super);
3937
- function MapType(name, _subType) {
4026
+ function MapType(name, _subType, hookInitializers) {
4027
+ if (hookInitializers === void 0) { hookInitializers = []; }
3938
4028
  var _this = _super.call(this, name) || this;
3939
4029
  _this._subType = _subType;
3940
4030
  _this.identifierMode = MapIdentifierMode.UNKNOWN;
3941
4031
  _this.mapIdentifierAttribute = undefined;
3942
4032
  _this.flags = TypeFlags.Map;
4033
+ _this.hookInitializers = [];
3943
4034
  _this._determineIdentifierMode();
4035
+ _this.hookInitializers = hookInitializers;
3944
4036
  return _this;
3945
4037
  }
4038
+ MapType.prototype.hooks = function (hooks) {
4039
+ var hookInitializers = this.hookInitializers.length > 0 ? this.hookInitializers.concat(hooks) : [hooks];
4040
+ return new MapType(this.name, this._subType, hookInitializers);
4041
+ };
3946
4042
  MapType.prototype.instantiate = function (parent, subpath, environment, initialValue) {
3947
4043
  this._determineIdentifierMode();
3948
4044
  return createObjectNode(this, parent, subpath, environment, initialValue);
@@ -3985,6 +4081,15 @@
3985
4081
  };
3986
4082
  MapType.prototype.finalizeNewInstance = function (node, instance) {
3987
4083
  mobx._interceptReads(instance, node.unbox);
4084
+ var type = node.type;
4085
+ type.hookInitializers.forEach(function (initializer) {
4086
+ var hooks = initializer(instance);
4087
+ Object.keys(hooks).forEach(function (name) {
4088
+ var hook = hooks[name];
4089
+ var actionInvoker = createActionInvoker(instance, name, hook);
4090
+ ( addHiddenWritableProp)(instance, name, actionInvoker);
4091
+ });
4092
+ });
3988
4093
  mobx.intercept(instance, this.willChange);
3989
4094
  mobx.observe(instance, this.didChange);
3990
4095
  };
@@ -4179,12 +4284,19 @@
4179
4284
  */
4180
4285
  var ArrayType = /** @class */ (function (_super) {
4181
4286
  __extends(ArrayType, _super);
4182
- function ArrayType(name, _subType) {
4287
+ function ArrayType(name, _subType, hookInitializers) {
4288
+ if (hookInitializers === void 0) { hookInitializers = []; }
4183
4289
  var _this = _super.call(this, name) || this;
4184
4290
  _this._subType = _subType;
4185
4291
  _this.flags = TypeFlags.Array;
4292
+ _this.hookInitializers = [];
4293
+ _this.hookInitializers = hookInitializers;
4186
4294
  return _this;
4187
4295
  }
4296
+ ArrayType.prototype.hooks = function (hooks) {
4297
+ var hookInitializers = this.hookInitializers.length > 0 ? this.hookInitializers.concat(hooks) : [hooks];
4298
+ return new ArrayType(this.name, this._subType, hookInitializers);
4299
+ };
4188
4300
  ArrayType.prototype.instantiate = function (parent, subpath, environment, initialValue) {
4189
4301
  return createObjectNode(this, parent, subpath, environment, initialValue);
4190
4302
  };
@@ -4203,6 +4315,15 @@
4203
4315
  };
4204
4316
  ArrayType.prototype.finalizeNewInstance = function (node, instance) {
4205
4317
  mobx._getAdministration(instance).dehancer = node.unbox;
4318
+ var type = node.type;
4319
+ type.hookInitializers.forEach(function (initializer) {
4320
+ var hooks = initializer(instance);
4321
+ Object.keys(hooks).forEach(function (name) {
4322
+ var hook = hooks[name];
4323
+ var actionInvoker = createActionInvoker(instance, name, hook);
4324
+ ( addHiddenWritableProp)(instance, name, actionInvoker);
4325
+ });
4326
+ });
4206
4327
  mobx.intercept(instance, this.willChange);
4207
4328
  mobx.observe(instance, this.didChange);
4208
4329
  };
@@ -4536,11 +4657,11 @@
4536
4657
  return props;
4537
4658
  // its a function, maybe the user wanted a view?
4538
4659
  }
4539
- else if (devMode() && typeof value === "function") {
4660
+ else if ( typeof value === "function") {
4540
4661
  throw fail$1("Invalid type definition for property '" + key + "', it looks like you passed a function. Did you forget to invoke it, or did you intend to declare a view / action?");
4541
4662
  // no other complex values
4542
4663
  }
4543
- else if (devMode() && typeof value === "object") {
4664
+ else if ( typeof value === "object") {
4544
4665
  throw fail$1("Invalid type definition for property '" + key + "', it looks like you passed an object. Try passing another model type or a types.frozen.");
4545
4666
  // WTF did you pass in mate?
4546
4667
  }
@@ -4582,10 +4703,6 @@
4582
4703
  postProcessor: function (snapshot) { return postProcessor(currentPostprocessor(snapshot)); }
4583
4704
  });
4584
4705
  };
4585
- var name = opts.name || defaultObjectOptions.name;
4586
- // TODO: this test still needed?
4587
- if (!/^\w[\w\d_]*$/.test(name))
4588
- throw fail$1("Typename should be a valid identifier: " + name);
4589
4706
  Object.assign(_this, defaultObjectOptions, opts);
4590
4707
  // ensures that any default value gets converted to its related type
4591
4708
  _this.properties = toPropertiesObject(_this.properties);
@@ -4651,11 +4768,14 @@
4651
4768
  boundAction.$mst_middleware = middlewares;
4652
4769
  var actionInvoker = createActionInvoker(self, name, boundAction);
4653
4770
  actions[name] = actionInvoker;
4654
- (!devMode() ? addHiddenFinalProp : addHiddenWritableProp)(self, name, actionInvoker);
4771
+ ( addHiddenWritableProp)(self, name, actionInvoker);
4655
4772
  });
4656
4773
  };
4657
4774
  ModelType.prototype.volatile = function (fn) {
4658
4775
  var _this = this;
4776
+ if (typeof fn !== "function") {
4777
+ throw fail$1("You passed an " + typeof fn + " to volatile state as an argument, when function is expected");
4778
+ }
4659
4779
  var stateInitializer = function (self) {
4660
4780
  _this.instantiateVolatileState(self, fn(self));
4661
4781
  return self;
@@ -4714,7 +4834,7 @@
4714
4834
  }
4715
4835
  }
4716
4836
  else if (typeof descriptor.value === "function") {
4717
- (!devMode() ? addHiddenFinalProp : addHiddenWritableProp)(self, key, descriptor.value);
4837
+ ( addHiddenWritableProp)(self, key, descriptor.value);
4718
4838
  }
4719
4839
  else {
4720
4840
  throw fail$1("A view member should either be a function or getter based property");
@@ -4862,7 +4982,9 @@
4862
4982
  var _this = this;
4863
4983
  // optimization: cache
4864
4984
  return ("{ " +
4865
- this.propertyNames.map(function (key) { return key + ": " + _this.properties[key].describe(); }).join("; ") +
4985
+ this.propertyNames
4986
+ .map(function (key) { return key + ": " + _this.properties[key].describe(); })
4987
+ .join("; ") +
4866
4988
  " }");
4867
4989
  };
4868
4990
  ModelType.prototype.getDefaultSnapshot = function () {
@@ -4879,7 +5001,7 @@
4879
5001
  /**
4880
5002
  * `types.model` - Creates a new model type by providing a name, properties, volatile state and actions.
4881
5003
  *
4882
- * See the [model type](https://github.com/mobxjs/mobx-state-tree#creating-models) description or the [getting started](https://github.com/mobxjs/mobx-state-tree/blob/master/docs/getting-started.md#getting-started-1) tutorial.
5004
+ * See the [model type](/concepts/trees#creating-models) description or the [getting started](intro/getting-started.md#getting-started-1) tutorial.
4883
5005
  */
4884
5006
  function model() {
4885
5007
  var args = [];
@@ -4909,7 +5031,7 @@
4909
5031
  args.shift();
4910
5032
  }
4911
5033
  // check all parameters
4912
- if (devMode()) {
5034
+ {
4913
5035
  args.forEach(function (type, i) {
4914
5036
  assertArg(type, isModelType, "mobx-state-tree model type", hasTypename ? i + 2 : i + 1);
4915
5037
  });
@@ -5160,7 +5282,7 @@
5160
5282
  get: function () {
5161
5283
  return this._subtype.flags | TypeFlags.Refinement;
5162
5284
  },
5163
- enumerable: true,
5285
+ enumerable: false,
5164
5286
  configurable: true
5165
5287
  });
5166
5288
  Refinement.prototype.describe = function () {
@@ -5245,7 +5367,7 @@
5245
5367
  function enumeration(name, options) {
5246
5368
  var realOptions = typeof name === "string" ? options : name;
5247
5369
  // check all options
5248
- if (devMode()) {
5370
+ {
5249
5371
  realOptions.forEach(function (option, i) {
5250
5372
  assertIsString(option, i + 1);
5251
5373
  });
@@ -5280,7 +5402,7 @@
5280
5402
  });
5281
5403
  return result;
5282
5404
  },
5283
- enumerable: true,
5405
+ enumerable: false,
5284
5406
  configurable: true
5285
5407
  });
5286
5408
  Union.prototype.isAssignableFrom = function (type) {
@@ -5312,7 +5434,9 @@
5312
5434
  if (reconcileCurrentType.is(value)) {
5313
5435
  return reconcileCurrentType;
5314
5436
  }
5315
- return this._types.filter(function (t) { return t !== reconcileCurrentType; }).find(function (type) { return type.is(value); });
5437
+ return this._types
5438
+ .filter(function (t) { return t !== reconcileCurrentType; })
5439
+ .find(function (type) { return type.is(value); });
5316
5440
  }
5317
5441
  else {
5318
5442
  return this._types.find(function (type) { return type.is(value); });
@@ -5362,7 +5486,7 @@
5362
5486
  var types = isType(optionsOrType) ? __spread([optionsOrType], otherTypes) : otherTypes;
5363
5487
  var name = "(" + types.map(function (type) { return type.name; }).join(" | ") + ")";
5364
5488
  // check all options
5365
- if (devMode()) {
5489
+ {
5366
5490
  if (options) {
5367
5491
  assertArg(options, function (o) { return isPlainObject(o); }, "object { eager?: boolean, dispatcher?: Function }", 1);
5368
5492
  }
@@ -5399,7 +5523,7 @@
5399
5523
  get: function () {
5400
5524
  return this._subtype.flags | TypeFlags.Optional;
5401
5525
  },
5402
- enumerable: true,
5526
+ enumerable: false,
5403
5527
  configurable: true
5404
5528
  });
5405
5529
  OptionalValue.prototype.describe = function () {
@@ -5450,7 +5574,7 @@
5450
5574
  throw fail$1("default value cannot be an instance, pass a snapshot or a function that creates an instance/snapshot instead");
5451
5575
  }
5452
5576
  assertIsType(type, 1);
5453
- if (devMode()) {
5577
+ {
5454
5578
  // we only check default values if they are passed directly
5455
5579
  // if they are generator functions they will be checked once they are generated
5456
5580
  // we don't check generator function results here to avoid generating a node just for type-checking purposes
@@ -5554,7 +5678,7 @@
5554
5678
  get: function () {
5555
5679
  return (this._subType ? this._subType.flags : 0) | TypeFlags.Late;
5556
5680
  },
5557
- enumerable: true,
5681
+ enumerable: false,
5558
5682
  configurable: true
5559
5683
  });
5560
5684
  Late.prototype.getSubType = function (mustSucceed) {
@@ -5573,7 +5697,7 @@
5573
5697
  if (mustSucceed && t === undefined)
5574
5698
  throw fail$1("Late type seems to be used too early, the definition (still) returns undefined");
5575
5699
  if (t) {
5576
- if (devMode() && !isType(t))
5700
+ if ( !isType(t))
5577
5701
  throw fail$1("Failed to determine subtype, make sure types.late returns a type definition.");
5578
5702
  this._subType = t;
5579
5703
  }
@@ -5628,7 +5752,7 @@
5628
5752
  var name = typeof nameOrType === "string" ? nameOrType : "late(" + nameOrType.toString() + ")";
5629
5753
  var type = typeof nameOrType === "string" ? maybeType : nameOrType;
5630
5754
  // checks that the type is actually a late type
5631
- if (devMode()) {
5755
+ {
5632
5756
  if (!(typeof type === "function" && type.length === 0))
5633
5757
  throw fail$1("Invalid late type, expected a function with zero arguments that returns a type, got: " +
5634
5758
  type);
@@ -5786,7 +5910,7 @@
5786
5910
  this.updateResolvedReference(this.node);
5787
5911
  return this.resolvedReference.node.value;
5788
5912
  },
5789
- enumerable: true,
5913
+ enumerable: false,
5790
5914
  configurable: true
5791
5915
  });
5792
5916
  return StoredReference;
@@ -6048,7 +6172,7 @@
6048
6172
  */
6049
6173
  function reference(subType, options) {
6050
6174
  assertIsType(subType, 1);
6051
- if (devMode()) {
6175
+ {
6052
6176
  if (arguments.length === 2 && typeof arguments[1] === "string") {
6053
6177
  // istanbul ignore next
6054
6178
  throw fail$1("References with base path are no longer supported. Please remove the base path.");
@@ -6059,7 +6183,7 @@
6059
6183
  ? options.onInvalidated
6060
6184
  : undefined;
6061
6185
  if (getSetOptions && (getSetOptions.get || getSetOptions.set)) {
6062
- if (devMode()) {
6186
+ {
6063
6187
  if (!getSetOptions.get || !getSetOptions.set) {
6064
6188
  throw fail$1("reference options must either contain both a 'get' and a 'set' method or none of them");
6065
6189
  }
@@ -6100,7 +6224,7 @@
6100
6224
  * @returns
6101
6225
  */
6102
6226
  function safeReference(subType, options) {
6103
- var refType = reference(subType, __assign({}, options, { onInvalidated: function (ev) {
6227
+ var refType = reference(subType, __assign(__assign({}, options), { onInvalidated: function (ev) {
6104
6228
  ev.removeRef();
6105
6229
  } }));
6106
6230
  if (options && options.acceptsUndefined === false) {
@@ -6243,8 +6367,8 @@
6243
6367
  * export interface CustomTypeOptions<S, T> {
6244
6368
  * // Friendly name
6245
6369
  * name: string
6246
- * // given a serialized value, how to turn it into the target type
6247
- * fromSnapshot(snapshot: S): T
6370
+ * // given a serialized value and environment, how to turn it into the target type
6371
+ * fromSnapshot(snapshot: S, env: any): T
6248
6372
  * // return the serialization of the current value
6249
6373
  * toSnapshot(value: T): S
6250
6374
  * // if true, this is a converted value, if false, it's a snapshot
@@ -6314,7 +6438,7 @@
6314
6438
  CustomType.prototype.instantiate = function (parent, subpath, environment, initialValue) {
6315
6439
  var valueToStore = this.options.isTargetType(initialValue)
6316
6440
  ? initialValue
6317
- : this.options.fromSnapshot(initialValue);
6441
+ : this.options.fromSnapshot(initialValue, parent && parent.root.environment);
6318
6442
  return createScalarNode(this, parent, subpath, environment, valueToStore);
6319
6443
  };
6320
6444
  CustomType.prototype.reconcile = function (current, value, parent, subpath) {
@@ -6328,7 +6452,9 @@
6328
6452
  return current;
6329
6453
  }
6330
6454
  }
6331
- var valueToStore = isSnapshot ? this.options.fromSnapshot(value) : value;
6455
+ var valueToStore = isSnapshot
6456
+ ? this.options.fromSnapshot(value, parent.root.environment)
6457
+ : value;
6332
6458
  var newNode = this.instantiate(parent, subpath, undefined, valueToStore);
6333
6459
  current.die(); // noop if detaching
6334
6460
  return newNode;
@@ -6366,13 +6492,6 @@
6366
6492
  snapshotProcessor: snapshotProcessor
6367
6493
  };
6368
6494
 
6369
- /*
6370
- * All imports / exports should be proxied through this file.
6371
- * Why? It gives us full control over the module load order, preventing circular dependency isses
6372
- */
6373
-
6374
- /* all code is initially loaded through internal, to avoid circular dep issues */
6375
-
6376
6495
  exports.addDisposer = addDisposer;
6377
6496
  exports.addMiddleware = addMiddleware;
6378
6497
  exports.applyAction = applyAction;
@@ -6432,7 +6551,7 @@
6432
6551
  exports.onAction = onAction;
6433
6552
  exports.onPatch = onPatch;
6434
6553
  exports.onSnapshot = onSnapshot;
6435
- exports.process = process$1;
6554
+ exports.process = process;
6436
6555
  exports.protect = protect;
6437
6556
  exports.recordActions = recordActions;
6438
6557
  exports.recordPatches = recordPatches;
@@ -6441,6 +6560,8 @@
6441
6560
  exports.setLivelinessChecking = setLivelinessChecking;
6442
6561
  exports.setLivelynessChecking = setLivelynessChecking;
6443
6562
  exports.splitJsonPath = splitJsonPath;
6563
+ exports.toGenerator = toGenerator;
6564
+ exports.toGeneratorFunction = toGeneratorFunction;
6444
6565
  exports.tryReference = tryReference;
6445
6566
  exports.tryResolve = tryResolve;
6446
6567
  exports.typecheck = typecheck;
@@ -6451,4 +6572,4 @@
6451
6572
 
6452
6573
  Object.defineProperty(exports, '__esModule', { value: true });
6453
6574
 
6454
- }));
6575
+ })));