UNPKG

189 kBJavaScriptView Raw
1var niceErrors = {
2 0: "Invalid value for configuration 'enforceActions', expected 'never', 'always' or 'observed'",
3 1: function _(annotationType, key) {
4 return "Cannot apply '" + annotationType + "' to '" + key.toString() + "': Field not found.";
5 },
6 /*
7 2(prop) {
8 return `invalid decorator for '${prop.toString()}'`
9 },
10 3(prop) {
11 return `Cannot decorate '${prop.toString()}': action can only be used on properties with a function value.`
12 },
13 4(prop) {
14 return `Cannot decorate '${prop.toString()}': computed can only be used on getter properties.`
15 },
16 */
17 5: "'keys()' can only be used on observable objects, arrays, sets and maps",
18 6: "'values()' can only be used on observable objects, arrays, sets and maps",
19 7: "'entries()' can only be used on observable objects, arrays and maps",
20 8: "'set()' can only be used on observable objects, arrays and maps",
21 9: "'remove()' can only be used on observable objects, arrays and maps",
22 10: "'has()' can only be used on observable objects, arrays and maps",
23 11: "'get()' can only be used on observable objects, arrays and maps",
24 12: "Invalid annotation",
25 13: "Dynamic observable objects cannot be frozen. If you're passing observables to 3rd party component/function that calls Object.freeze, pass copy instead: toJS(observable)",
26 14: "Intercept handlers should return nothing or a change object",
27 15: "Observable arrays cannot be frozen. If you're passing observables to 3rd party component/function that calls Object.freeze, pass copy instead: toJS(observable)",
28 16: "Modification exception: the internal structure of an observable array was changed.",
29 17: function _(index, length) {
30 return "[mobx.array] Index out of bounds, " + index + " is larger than " + length;
31 },
32 18: "mobx.map requires Map polyfill for the current browser. Check babel-polyfill or core-js/es6/map.js",
33 19: function _(other) {
34 return "Cannot initialize from classes that inherit from Map: " + other.constructor.name;
35 },
36 20: function _(other) {
37 return "Cannot initialize map from " + other;
38 },
39 21: function _(dataStructure) {
40 return "Cannot convert to map from '" + dataStructure + "'";
41 },
42 22: "mobx.set requires Set polyfill for the current browser. Check babel-polyfill or core-js/es6/set.js",
43 23: "It is not possible to get index atoms from arrays",
44 24: function _(thing) {
45 return "Cannot obtain administration from " + thing;
46 },
47 25: function _(property, name) {
48 return "the entry '" + property + "' does not exist in the observable map '" + name + "'";
49 },
50 26: "please specify a property",
51 27: function _(property, name) {
52 return "no observable property '" + property.toString() + "' found on the observable object '" + name + "'";
53 },
54 28: function _(thing) {
55 return "Cannot obtain atom from " + thing;
56 },
57 29: "Expecting some object",
58 30: "invalid action stack. did you forget to finish an action?",
59 31: "missing option for computed: get",
60 32: function _(name, derivation) {
61 return "Cycle detected in computation " + name + ": " + derivation;
62 },
63 33: function _(name) {
64 return "The setter of computed value '" + name + "' is trying to update itself. Did you intend to update an _observable_ value, instead of the computed property?";
65 },
66 34: function _(name) {
67 return "[ComputedValue '" + name + "'] It is not possible to assign a new value to a computed value.";
68 },
69 35: "There are multiple, different versions of MobX active. Make sure MobX is loaded only once or use `configure({ isolateGlobalState: true })`",
70 36: "isolateGlobalState should be called before MobX is running any reactions",
71 37: function _(method) {
72 return "[mobx] `observableArray." + method + "()` mutates the array in-place, which is not allowed inside a derivation. Use `array.slice()." + method + "()` instead";
73 },
74 38: "'ownKeys()' can only be used on observable objects",
75 39: "'defineProperty()' can only be used on observable objects"
76};
77var errors = niceErrors ;
78function die(error) {
79 for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
80 args[_key - 1] = arguments[_key];
81 }
82 {
83 var e = typeof error === "string" ? error : errors[error];
84 if (typeof e === "function") e = e.apply(null, args);
85 throw new Error("[MobX] " + e);
86 }
87}
88
89var mockGlobal = {};
90function getGlobal() {
91 if (typeof globalThis !== "undefined") {
92 return globalThis;
93 }
94 if (typeof window !== "undefined") {
95 return window;
96 }
97 if (typeof global !== "undefined") {
98 return global;
99 }
100 if (typeof self !== "undefined") {
101 return self;
102 }
103 return mockGlobal;
104}
105
106// We shorten anything used > 5 times
107var assign = Object.assign;
108var getDescriptor = Object.getOwnPropertyDescriptor;
109var defineProperty = Object.defineProperty;
110var objectPrototype = Object.prototype;
111var EMPTY_ARRAY = [];
112Object.freeze(EMPTY_ARRAY);
113var EMPTY_OBJECT = {};
114Object.freeze(EMPTY_OBJECT);
115var hasProxy = typeof Proxy !== "undefined";
116var plainObjectString = /*#__PURE__*/Object.toString();
117function assertProxies() {
118 if (!hasProxy) {
119 die( "`Proxy` objects are not available in the current environment. Please configure MobX to enable a fallback implementation.`" );
120 }
121}
122function warnAboutProxyRequirement(msg) {
123 if ( globalState.verifyProxies) {
124 die("MobX is currently configured to be able to run in ES5 mode, but in ES5 MobX won't be able to " + msg);
125 }
126}
127function getNextId() {
128 return ++globalState.mobxGuid;
129}
130/**
131 * Makes sure that the provided function is invoked at most once.
132 */
133function once(func) {
134 var invoked = false;
135 return function () {
136 if (invoked) {
137 return;
138 }
139 invoked = true;
140 return func.apply(this, arguments);
141 };
142}
143var noop = function noop() {};
144function isFunction(fn) {
145 return typeof fn === "function";
146}
147function isStringish(value) {
148 var t = typeof value;
149 switch (t) {
150 case "string":
151 case "symbol":
152 case "number":
153 return true;
154 }
155 return false;
156}
157function isObject(value) {
158 return value !== null && typeof value === "object";
159}
160function isPlainObject(value) {
161 if (!isObject(value)) {
162 return false;
163 }
164 var proto = Object.getPrototypeOf(value);
165 if (proto == null) {
166 return true;
167 }
168 var protoConstructor = Object.hasOwnProperty.call(proto, "constructor") && proto.constructor;
169 return typeof protoConstructor === "function" && protoConstructor.toString() === plainObjectString;
170}
171// https://stackoverflow.com/a/37865170
172function isGenerator(obj) {
173 var constructor = obj == null ? void 0 : obj.constructor;
174 if (!constructor) {
175 return false;
176 }
177 if ("GeneratorFunction" === constructor.name || "GeneratorFunction" === constructor.displayName) {
178 return true;
179 }
180 return false;
181}
182function addHiddenProp(object, propName, value) {
183 defineProperty(object, propName, {
184 enumerable: false,
185 writable: true,
186 configurable: true,
187 value: value
188 });
189}
190function addHiddenFinalProp(object, propName, value) {
191 defineProperty(object, propName, {
192 enumerable: false,
193 writable: false,
194 configurable: true,
195 value: value
196 });
197}
198function createInstanceofPredicate(name, theClass) {
199 var propName = "isMobX" + name;
200 theClass.prototype[propName] = true;
201 return function (x) {
202 return isObject(x) && x[propName] === true;
203 };
204}
205function isES6Map(thing) {
206 return thing instanceof Map;
207}
208function isES6Set(thing) {
209 return thing instanceof Set;
210}
211var hasGetOwnPropertySymbols = typeof Object.getOwnPropertySymbols !== "undefined";
212/**
213 * Returns the following: own enumerable keys and symbols.
214 */
215function getPlainObjectKeys(object) {
216 var keys = Object.keys(object);
217 // Not supported in IE, so there are not going to be symbol props anyway...
218 if (!hasGetOwnPropertySymbols) {
219 return keys;
220 }
221 var symbols = Object.getOwnPropertySymbols(object);
222 if (!symbols.length) {
223 return keys;
224 }
225 return [].concat(keys, symbols.filter(function (s) {
226 return objectPrototype.propertyIsEnumerable.call(object, s);
227 }));
228}
229// From Immer utils
230// Returns all own keys, including non-enumerable and symbolic
231var ownKeys = typeof Reflect !== "undefined" && Reflect.ownKeys ? Reflect.ownKeys : hasGetOwnPropertySymbols ? function (obj) {
232 return Object.getOwnPropertyNames(obj).concat(Object.getOwnPropertySymbols(obj));
233} : /* istanbul ignore next */Object.getOwnPropertyNames;
234function stringifyKey(key) {
235 if (typeof key === "string") {
236 return key;
237 }
238 if (typeof key === "symbol") {
239 return key.toString();
240 }
241 return new String(key).toString();
242}
243function toPrimitive(value) {
244 return value === null ? null : typeof value === "object" ? "" + value : value;
245}
246function hasProp(target, prop) {
247 return objectPrototype.hasOwnProperty.call(target, prop);
248}
249// From Immer utils
250var getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors || function getOwnPropertyDescriptors(target) {
251 // Polyfill needed for Hermes and IE, see https://github.com/facebook/hermes/issues/274
252 var res = {};
253 // Note: without polyfill for ownKeys, symbols won't be picked up
254 ownKeys(target).forEach(function (key) {
255 res[key] = getDescriptor(target, key);
256 });
257 return res;
258};
259
260function _defineProperties(target, props) {
261 for (var i = 0; i < props.length; i++) {
262 var descriptor = props[i];
263 descriptor.enumerable = descriptor.enumerable || false;
264 descriptor.configurable = true;
265 if ("value" in descriptor) descriptor.writable = true;
266 Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor);
267 }
268}
269function _createClass(Constructor, protoProps, staticProps) {
270 if (protoProps) _defineProperties(Constructor.prototype, protoProps);
271 if (staticProps) _defineProperties(Constructor, staticProps);
272 Object.defineProperty(Constructor, "prototype", {
273 writable: false
274 });
275 return Constructor;
276}
277function _extends() {
278 _extends = Object.assign ? Object.assign.bind() : function (target) {
279 for (var i = 1; i < arguments.length; i++) {
280 var source = arguments[i];
281 for (var key in source) {
282 if (Object.prototype.hasOwnProperty.call(source, key)) {
283 target[key] = source[key];
284 }
285 }
286 }
287 return target;
288 };
289 return _extends.apply(this, arguments);
290}
291function _inheritsLoose(subClass, superClass) {
292 subClass.prototype = Object.create(superClass.prototype);
293 subClass.prototype.constructor = subClass;
294 _setPrototypeOf(subClass, superClass);
295}
296function _setPrototypeOf(o, p) {
297 _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
298 o.__proto__ = p;
299 return o;
300 };
301 return _setPrototypeOf(o, p);
302}
303function _assertThisInitialized(self) {
304 if (self === void 0) {
305 throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
306 }
307 return self;
308}
309function _unsupportedIterableToArray(o, minLen) {
310 if (!o) return;
311 if (typeof o === "string") return _arrayLikeToArray(o, minLen);
312 var n = Object.prototype.toString.call(o).slice(8, -1);
313 if (n === "Object" && o.constructor) n = o.constructor.name;
314 if (n === "Map" || n === "Set") return Array.from(o);
315 if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
316}
317function _arrayLikeToArray(arr, len) {
318 if (len == null || len > arr.length) len = arr.length;
319 for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
320 return arr2;
321}
322function _createForOfIteratorHelperLoose(o, allowArrayLike) {
323 var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
324 if (it) return (it = it.call(o)).next.bind(it);
325 if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
326 if (it) o = it;
327 var i = 0;
328 return function () {
329 if (i >= o.length) return {
330 done: true
331 };
332 return {
333 done: false,
334 value: o[i++]
335 };
336 };
337 }
338 throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
339}
340function _toPrimitive(input, hint) {
341 if (typeof input !== "object" || input === null) return input;
342 var prim = input[Symbol.toPrimitive];
343 if (prim !== undefined) {
344 var res = prim.call(input, hint || "default");
345 if (typeof res !== "object") return res;
346 throw new TypeError("@@toPrimitive must return a primitive value.");
347 }
348 return (hint === "string" ? String : Number)(input);
349}
350function _toPropertyKey(arg) {
351 var key = _toPrimitive(arg, "string");
352 return typeof key === "symbol" ? key : String(key);
353}
354
355var storedAnnotationsSymbol = /*#__PURE__*/Symbol("mobx-stored-annotations");
356/**
357 * Creates a function that acts as
358 * - decorator
359 * - annotation object
360 */
361function createDecoratorAnnotation(annotation) {
362 function decorator(target, property) {
363 storeAnnotation(target, property, annotation);
364 }
365 return Object.assign(decorator, annotation);
366}
367/**
368 * Stores annotation to prototype,
369 * so it can be inspected later by `makeObservable` called from constructor
370 */
371function storeAnnotation(prototype, key, annotation) {
372 if (!hasProp(prototype, storedAnnotationsSymbol)) {
373 addHiddenProp(prototype, storedAnnotationsSymbol, _extends({}, prototype[storedAnnotationsSymbol]));
374 }
375 // @override must override something
376 if ( isOverride(annotation) && !hasProp(prototype[storedAnnotationsSymbol], key)) {
377 var fieldName = prototype.constructor.name + ".prototype." + key.toString();
378 die("'" + fieldName + "' is decorated with 'override', " + "but no such decorated member was found on prototype.");
379 }
380 // Cannot re-decorate
381 assertNotDecorated(prototype, annotation, key);
382 // Ignore override
383 if (!isOverride(annotation)) {
384 prototype[storedAnnotationsSymbol][key] = annotation;
385 }
386}
387function assertNotDecorated(prototype, annotation, key) {
388 if ( !isOverride(annotation) && hasProp(prototype[storedAnnotationsSymbol], key)) {
389 var fieldName = prototype.constructor.name + ".prototype." + key.toString();
390 var currentAnnotationType = prototype[storedAnnotationsSymbol][key].annotationType_;
391 var requestedAnnotationType = annotation.annotationType_;
392 die("Cannot apply '@" + requestedAnnotationType + "' to '" + fieldName + "':" + ("\nThe field is already decorated with '@" + currentAnnotationType + "'.") + "\nRe-decorating fields is not allowed." + "\nUse '@override' decorator for methods overridden by subclass.");
393 }
394}
395/**
396 * Collects annotations from prototypes and stores them on target (instance)
397 */
398function collectStoredAnnotations(target) {
399 if (!hasProp(target, storedAnnotationsSymbol)) {
400 if ( !target[storedAnnotationsSymbol]) {
401 die("No annotations were passed to makeObservable, but no decorated members have been found either");
402 }
403 // We need a copy as we will remove annotation from the list once it's applied.
404 addHiddenProp(target, storedAnnotationsSymbol, _extends({}, target[storedAnnotationsSymbol]));
405 }
406 return target[storedAnnotationsSymbol];
407}
408
409var $mobx = /*#__PURE__*/Symbol("mobx administration");
410var Atom = /*#__PURE__*/function () {
411 // for effective unobserving. BaseAtom has true, for extra optimization, so its onBecomeUnobserved never gets called, because it's not needed
412
413 /**
414 * Create a new atom. For debugging purposes it is recommended to give it a name.
415 * The onBecomeObserved and onBecomeUnobserved callbacks can be used for resource management.
416 */
417 function Atom(name_) {
418 if (name_ === void 0) {
419 name_ = "Atom@" + getNextId() ;
420 }
421 this.name_ = void 0;
422 this.isPendingUnobservation_ = false;
423 this.isBeingObserved_ = false;
424 this.observers_ = new Set();
425 this.diffValue_ = 0;
426 this.lastAccessedBy_ = 0;
427 this.lowestObserverState_ = IDerivationState_.NOT_TRACKING_;
428 this.onBOL = void 0;
429 this.onBUOL = void 0;
430 this.name_ = name_;
431 }
432 // onBecomeObservedListeners
433 var _proto = Atom.prototype;
434 _proto.onBO = function onBO() {
435 if (this.onBOL) {
436 this.onBOL.forEach(function (listener) {
437 return listener();
438 });
439 }
440 };
441 _proto.onBUO = function onBUO() {
442 if (this.onBUOL) {
443 this.onBUOL.forEach(function (listener) {
444 return listener();
445 });
446 }
447 }
448 /**
449 * Invoke this method to notify mobx that your atom has been used somehow.
450 * Returns true if there is currently a reactive context.
451 */;
452 _proto.reportObserved = function reportObserved$1() {
453 return reportObserved(this);
454 }
455 /**
456 * Invoke this method _after_ this method has changed to signal mobx that all its observers should invalidate.
457 */;
458 _proto.reportChanged = function reportChanged() {
459 startBatch();
460 propagateChanged(this);
461 // We could update state version only at the end of batch,
462 // but we would still have to switch some global flag here to signal a change.
463 globalState.stateVersion = globalState.stateVersion < Number.MAX_SAFE_INTEGER ? globalState.stateVersion + 1 : Number.MIN_SAFE_INTEGER;
464 endBatch();
465 };
466 _proto.toString = function toString() {
467 return this.name_;
468 };
469 return Atom;
470}();
471var isAtom = /*#__PURE__*/createInstanceofPredicate("Atom", Atom);
472function createAtom(name, onBecomeObservedHandler, onBecomeUnobservedHandler) {
473 if (onBecomeObservedHandler === void 0) {
474 onBecomeObservedHandler = noop;
475 }
476 if (onBecomeUnobservedHandler === void 0) {
477 onBecomeUnobservedHandler = noop;
478 }
479 var atom = new Atom(name);
480 // default `noop` listener will not initialize the hook Set
481 if (onBecomeObservedHandler !== noop) {
482 onBecomeObserved(atom, onBecomeObservedHandler);
483 }
484 if (onBecomeUnobservedHandler !== noop) {
485 onBecomeUnobserved(atom, onBecomeUnobservedHandler);
486 }
487 return atom;
488}
489
490function identityComparer(a, b) {
491 return a === b;
492}
493function structuralComparer(a, b) {
494 return deepEqual(a, b);
495}
496function shallowComparer(a, b) {
497 return deepEqual(a, b, 1);
498}
499function defaultComparer(a, b) {
500 if (Object.is) {
501 return Object.is(a, b);
502 }
503 return a === b ? a !== 0 || 1 / a === 1 / b : a !== a && b !== b;
504}
505var comparer = {
506 identity: identityComparer,
507 structural: structuralComparer,
508 "default": defaultComparer,
509 shallow: shallowComparer
510};
511
512function deepEnhancer(v, _, name) {
513 // it is an observable already, done
514 if (isObservable(v)) {
515 return v;
516 }
517 // something that can be converted and mutated?
518 if (Array.isArray(v)) {
519 return observable.array(v, {
520 name: name
521 });
522 }
523 if (isPlainObject(v)) {
524 return observable.object(v, undefined, {
525 name: name
526 });
527 }
528 if (isES6Map(v)) {
529 return observable.map(v, {
530 name: name
531 });
532 }
533 if (isES6Set(v)) {
534 return observable.set(v, {
535 name: name
536 });
537 }
538 if (typeof v === "function" && !isAction(v) && !isFlow(v)) {
539 if (isGenerator(v)) {
540 return flow(v);
541 } else {
542 return autoAction(name, v);
543 }
544 }
545 return v;
546}
547function shallowEnhancer(v, _, name) {
548 if (v === undefined || v === null) {
549 return v;
550 }
551 if (isObservableObject(v) || isObservableArray(v) || isObservableMap(v) || isObservableSet(v)) {
552 return v;
553 }
554 if (Array.isArray(v)) {
555 return observable.array(v, {
556 name: name,
557 deep: false
558 });
559 }
560 if (isPlainObject(v)) {
561 return observable.object(v, undefined, {
562 name: name,
563 deep: false
564 });
565 }
566 if (isES6Map(v)) {
567 return observable.map(v, {
568 name: name,
569 deep: false
570 });
571 }
572 if (isES6Set(v)) {
573 return observable.set(v, {
574 name: name,
575 deep: false
576 });
577 }
578 {
579 die("The shallow modifier / decorator can only used in combination with arrays, objects, maps and sets");
580 }
581}
582function referenceEnhancer(newValue) {
583 // never turn into an observable
584 return newValue;
585}
586function refStructEnhancer(v, oldValue) {
587 if ( isObservable(v)) {
588 die("observable.struct should not be used with observable values");
589 }
590 if (deepEqual(v, oldValue)) {
591 return oldValue;
592 }
593 return v;
594}
595
596var OVERRIDE = "override";
597var override = /*#__PURE__*/createDecoratorAnnotation({
598 annotationType_: OVERRIDE,
599 make_: make_,
600 extend_: extend_
601});
602function isOverride(annotation) {
603 return annotation.annotationType_ === OVERRIDE;
604}
605function make_(adm, key) {
606 // Must not be plain object
607 if ( adm.isPlainObject_) {
608 die("Cannot apply '" + this.annotationType_ + "' to '" + adm.name_ + "." + key.toString() + "':" + ("\n'" + this.annotationType_ + "' cannot be used on plain objects."));
609 }
610 // Must override something
611 if ( !hasProp(adm.appliedAnnotations_, key)) {
612 die("'" + adm.name_ + "." + key.toString() + "' is annotated with '" + this.annotationType_ + "', " + "but no such annotated member was found on prototype.");
613 }
614 return 0 /* Cancel */;
615}
616
617function extend_(adm, key, descriptor, proxyTrap) {
618 die("'" + this.annotationType_ + "' can only be used with 'makeObservable'");
619}
620
621function createActionAnnotation(name, options) {
622 return {
623 annotationType_: name,
624 options_: options,
625 make_: make_$1,
626 extend_: extend_$1
627 };
628}
629function make_$1(adm, key, descriptor, source) {
630 var _this$options_;
631 // bound
632 if ((_this$options_ = this.options_) != null && _this$options_.bound) {
633 return this.extend_(adm, key, descriptor, false) === null ? 0 /* Cancel */ : 1 /* Break */;
634 }
635 // own
636 if (source === adm.target_) {
637 return this.extend_(adm, key, descriptor, false) === null ? 0 /* Cancel */ : 2 /* Continue */;
638 }
639 // prototype
640 if (isAction(descriptor.value)) {
641 // A prototype could have been annotated already by other constructor,
642 // rest of the proto chain must be annotated already
643 return 1 /* Break */;
644 }
645
646 var actionDescriptor = createActionDescriptor(adm, this, key, descriptor, false);
647 defineProperty(source, key, actionDescriptor);
648 return 2 /* Continue */;
649}
650
651function extend_$1(adm, key, descriptor, proxyTrap) {
652 var actionDescriptor = createActionDescriptor(adm, this, key, descriptor);
653 return adm.defineProperty_(key, actionDescriptor, proxyTrap);
654}
655function assertActionDescriptor(adm, _ref, key, _ref2) {
656 var annotationType_ = _ref.annotationType_;
657 var value = _ref2.value;
658 if ( !isFunction(value)) {
659 die("Cannot apply '" + annotationType_ + "' to '" + adm.name_ + "." + key.toString() + "':" + ("\n'" + annotationType_ + "' can only be used on properties with a function value."));
660 }
661}
662function createActionDescriptor(adm, annotation, key, descriptor,
663// provides ability to disable safeDescriptors for prototypes
664safeDescriptors) {
665 var _annotation$options_, _annotation$options_$, _annotation$options_2, _annotation$options_$2, _annotation$options_3, _annotation$options_4, _adm$proxy_2;
666 if (safeDescriptors === void 0) {
667 safeDescriptors = globalState.safeDescriptors;
668 }
669 assertActionDescriptor(adm, annotation, key, descriptor);
670 var value = descriptor.value;
671 if ((_annotation$options_ = annotation.options_) != null && _annotation$options_.bound) {
672 var _adm$proxy_;
673 value = value.bind((_adm$proxy_ = adm.proxy_) != null ? _adm$proxy_ : adm.target_);
674 }
675 return {
676 value: createAction((_annotation$options_$ = (_annotation$options_2 = annotation.options_) == null ? void 0 : _annotation$options_2.name) != null ? _annotation$options_$ : key.toString(), value, (_annotation$options_$2 = (_annotation$options_3 = annotation.options_) == null ? void 0 : _annotation$options_3.autoAction) != null ? _annotation$options_$2 : false,
677 // https://github.com/mobxjs/mobx/discussions/3140
678 (_annotation$options_4 = annotation.options_) != null && _annotation$options_4.bound ? (_adm$proxy_2 = adm.proxy_) != null ? _adm$proxy_2 : adm.target_ : undefined),
679 // Non-configurable for classes
680 // prevents accidental field redefinition in subclass
681 configurable: safeDescriptors ? adm.isPlainObject_ : true,
682 // https://github.com/mobxjs/mobx/pull/2641#issuecomment-737292058
683 enumerable: false,
684 // Non-obsevable, therefore non-writable
685 // Also prevents rewriting in subclass constructor
686 writable: safeDescriptors ? false : true
687 };
688}
689
690function createFlowAnnotation(name, options) {
691 return {
692 annotationType_: name,
693 options_: options,
694 make_: make_$2,
695 extend_: extend_$2
696 };
697}
698function make_$2(adm, key, descriptor, source) {
699 var _this$options_;
700 // own
701 if (source === adm.target_) {
702 return this.extend_(adm, key, descriptor, false) === null ? 0 /* Cancel */ : 2 /* Continue */;
703 }
704 // prototype
705 // bound - must annotate protos to support super.flow()
706 if ((_this$options_ = this.options_) != null && _this$options_.bound && (!hasProp(adm.target_, key) || !isFlow(adm.target_[key]))) {
707 if (this.extend_(adm, key, descriptor, false) === null) {
708 return 0 /* Cancel */;
709 }
710 }
711
712 if (isFlow(descriptor.value)) {
713 // A prototype could have been annotated already by other constructor,
714 // rest of the proto chain must be annotated already
715 return 1 /* Break */;
716 }
717
718 var flowDescriptor = createFlowDescriptor(adm, this, key, descriptor, false, false);
719 defineProperty(source, key, flowDescriptor);
720 return 2 /* Continue */;
721}
722
723function extend_$2(adm, key, descriptor, proxyTrap) {
724 var _this$options_2;
725 var flowDescriptor = createFlowDescriptor(adm, this, key, descriptor, (_this$options_2 = this.options_) == null ? void 0 : _this$options_2.bound);
726 return adm.defineProperty_(key, flowDescriptor, proxyTrap);
727}
728function assertFlowDescriptor(adm, _ref, key, _ref2) {
729 var annotationType_ = _ref.annotationType_;
730 var value = _ref2.value;
731 if ( !isFunction(value)) {
732 die("Cannot apply '" + annotationType_ + "' to '" + adm.name_ + "." + key.toString() + "':" + ("\n'" + annotationType_ + "' can only be used on properties with a generator function value."));
733 }
734}
735function createFlowDescriptor(adm, annotation, key, descriptor, bound,
736// provides ability to disable safeDescriptors for prototypes
737safeDescriptors) {
738 if (safeDescriptors === void 0) {
739 safeDescriptors = globalState.safeDescriptors;
740 }
741 assertFlowDescriptor(adm, annotation, key, descriptor);
742 var value = descriptor.value;
743 // In case of flow.bound, the descriptor can be from already annotated prototype
744 if (!isFlow(value)) {
745 value = flow(value);
746 }
747 if (bound) {
748 var _adm$proxy_;
749 // We do not keep original function around, so we bind the existing flow
750 value = value.bind((_adm$proxy_ = adm.proxy_) != null ? _adm$proxy_ : adm.target_);
751 // This is normally set by `flow`, but `bind` returns new function...
752 value.isMobXFlow = true;
753 }
754 return {
755 value: value,
756 // Non-configurable for classes
757 // prevents accidental field redefinition in subclass
758 configurable: safeDescriptors ? adm.isPlainObject_ : true,
759 // https://github.com/mobxjs/mobx/pull/2641#issuecomment-737292058
760 enumerable: false,
761 // Non-obsevable, therefore non-writable
762 // Also prevents rewriting in subclass constructor
763 writable: safeDescriptors ? false : true
764 };
765}
766
767function createComputedAnnotation(name, options) {
768 return {
769 annotationType_: name,
770 options_: options,
771 make_: make_$3,
772 extend_: extend_$3
773 };
774}
775function make_$3(adm, key, descriptor) {
776 return this.extend_(adm, key, descriptor, false) === null ? 0 /* Cancel */ : 1 /* Break */;
777}
778
779function extend_$3(adm, key, descriptor, proxyTrap) {
780 assertComputedDescriptor(adm, this, key, descriptor);
781 return adm.defineComputedProperty_(key, _extends({}, this.options_, {
782 get: descriptor.get,
783 set: descriptor.set
784 }), proxyTrap);
785}
786function assertComputedDescriptor(adm, _ref, key, _ref2) {
787 var annotationType_ = _ref.annotationType_;
788 var get = _ref2.get;
789 if ( !get) {
790 die("Cannot apply '" + annotationType_ + "' to '" + adm.name_ + "." + key.toString() + "':" + ("\n'" + annotationType_ + "' can only be used on getter(+setter) properties."));
791 }
792}
793
794function createObservableAnnotation(name, options) {
795 return {
796 annotationType_: name,
797 options_: options,
798 make_: make_$4,
799 extend_: extend_$4
800 };
801}
802function make_$4(adm, key, descriptor) {
803 return this.extend_(adm, key, descriptor, false) === null ? 0 /* Cancel */ : 1 /* Break */;
804}
805
806function extend_$4(adm, key, descriptor, proxyTrap) {
807 var _this$options_$enhanc, _this$options_;
808 assertObservableDescriptor(adm, this, key, descriptor);
809 return adm.defineObservableProperty_(key, descriptor.value, (_this$options_$enhanc = (_this$options_ = this.options_) == null ? void 0 : _this$options_.enhancer) != null ? _this$options_$enhanc : deepEnhancer, proxyTrap);
810}
811function assertObservableDescriptor(adm, _ref, key, descriptor) {
812 var annotationType_ = _ref.annotationType_;
813 if ( !("value" in descriptor)) {
814 die("Cannot apply '" + annotationType_ + "' to '" + adm.name_ + "." + key.toString() + "':" + ("\n'" + annotationType_ + "' cannot be used on getter/setter properties"));
815 }
816}
817
818var AUTO = "true";
819var autoAnnotation = /*#__PURE__*/createAutoAnnotation();
820function createAutoAnnotation(options) {
821 return {
822 annotationType_: AUTO,
823 options_: options,
824 make_: make_$5,
825 extend_: extend_$5
826 };
827}
828function make_$5(adm, key, descriptor, source) {
829 var _this$options_3, _this$options_4;
830 // getter -> computed
831 if (descriptor.get) {
832 return computed.make_(adm, key, descriptor, source);
833 }
834 // lone setter -> action setter
835 if (descriptor.set) {
836 // TODO make action applicable to setter and delegate to action.make_
837 var set = createAction(key.toString(), descriptor.set);
838 // own
839 if (source === adm.target_) {
840 return adm.defineProperty_(key, {
841 configurable: globalState.safeDescriptors ? adm.isPlainObject_ : true,
842 set: set
843 }) === null ? 0 /* Cancel */ : 2 /* Continue */;
844 }
845 // proto
846 defineProperty(source, key, {
847 configurable: true,
848 set: set
849 });
850 return 2 /* Continue */;
851 }
852 // function on proto -> autoAction/flow
853 if (source !== adm.target_ && typeof descriptor.value === "function") {
854 var _this$options_2;
855 if (isGenerator(descriptor.value)) {
856 var _this$options_;
857 var flowAnnotation = (_this$options_ = this.options_) != null && _this$options_.autoBind ? flow.bound : flow;
858 return flowAnnotation.make_(adm, key, descriptor, source);
859 }
860 var actionAnnotation = (_this$options_2 = this.options_) != null && _this$options_2.autoBind ? autoAction.bound : autoAction;
861 return actionAnnotation.make_(adm, key, descriptor, source);
862 }
863 // other -> observable
864 // Copy props from proto as well, see test:
865 // "decorate should work with Object.create"
866 var observableAnnotation = ((_this$options_3 = this.options_) == null ? void 0 : _this$options_3.deep) === false ? observable.ref : observable;
867 // if function respect autoBind option
868 if (typeof descriptor.value === "function" && (_this$options_4 = this.options_) != null && _this$options_4.autoBind) {
869 var _adm$proxy_;
870 descriptor.value = descriptor.value.bind((_adm$proxy_ = adm.proxy_) != null ? _adm$proxy_ : adm.target_);
871 }
872 return observableAnnotation.make_(adm, key, descriptor, source);
873}
874function extend_$5(adm, key, descriptor, proxyTrap) {
875 var _this$options_5, _this$options_6;
876 // getter -> computed
877 if (descriptor.get) {
878 return computed.extend_(adm, key, descriptor, proxyTrap);
879 }
880 // lone setter -> action setter
881 if (descriptor.set) {
882 // TODO make action applicable to setter and delegate to action.extend_
883 return adm.defineProperty_(key, {
884 configurable: globalState.safeDescriptors ? adm.isPlainObject_ : true,
885 set: createAction(key.toString(), descriptor.set)
886 }, proxyTrap);
887 }
888 // other -> observable
889 // if function respect autoBind option
890 if (typeof descriptor.value === "function" && (_this$options_5 = this.options_) != null && _this$options_5.autoBind) {
891 var _adm$proxy_2;
892 descriptor.value = descriptor.value.bind((_adm$proxy_2 = adm.proxy_) != null ? _adm$proxy_2 : adm.target_);
893 }
894 var observableAnnotation = ((_this$options_6 = this.options_) == null ? void 0 : _this$options_6.deep) === false ? observable.ref : observable;
895 return observableAnnotation.extend_(adm, key, descriptor, proxyTrap);
896}
897
898var OBSERVABLE = "observable";
899var OBSERVABLE_REF = "observable.ref";
900var OBSERVABLE_SHALLOW = "observable.shallow";
901var OBSERVABLE_STRUCT = "observable.struct";
902// Predefined bags of create observable options, to avoid allocating temporarily option objects
903// in the majority of cases
904var defaultCreateObservableOptions = {
905 deep: true,
906 name: undefined,
907 defaultDecorator: undefined,
908 proxy: true
909};
910Object.freeze(defaultCreateObservableOptions);
911function asCreateObservableOptions(thing) {
912 return thing || defaultCreateObservableOptions;
913}
914var observableAnnotation = /*#__PURE__*/createObservableAnnotation(OBSERVABLE);
915var observableRefAnnotation = /*#__PURE__*/createObservableAnnotation(OBSERVABLE_REF, {
916 enhancer: referenceEnhancer
917});
918var observableShallowAnnotation = /*#__PURE__*/createObservableAnnotation(OBSERVABLE_SHALLOW, {
919 enhancer: shallowEnhancer
920});
921var observableStructAnnotation = /*#__PURE__*/createObservableAnnotation(OBSERVABLE_STRUCT, {
922 enhancer: refStructEnhancer
923});
924var observableDecoratorAnnotation = /*#__PURE__*/createDecoratorAnnotation(observableAnnotation);
925function getEnhancerFromOptions(options) {
926 return options.deep === true ? deepEnhancer : options.deep === false ? referenceEnhancer : getEnhancerFromAnnotation(options.defaultDecorator);
927}
928function getAnnotationFromOptions(options) {
929 var _options$defaultDecor;
930 return options ? (_options$defaultDecor = options.defaultDecorator) != null ? _options$defaultDecor : createAutoAnnotation(options) : undefined;
931}
932function getEnhancerFromAnnotation(annotation) {
933 var _annotation$options_$, _annotation$options_;
934 return !annotation ? deepEnhancer : (_annotation$options_$ = (_annotation$options_ = annotation.options_) == null ? void 0 : _annotation$options_.enhancer) != null ? _annotation$options_$ : deepEnhancer;
935}
936/**
937 * Turns an object, array or function into a reactive structure.
938 * @param v the value which should become observable.
939 */
940function createObservable(v, arg2, arg3) {
941 // @observable someProp;
942 if (isStringish(arg2)) {
943 storeAnnotation(v, arg2, observableAnnotation);
944 return;
945 }
946 // already observable - ignore
947 if (isObservable(v)) {
948 return v;
949 }
950 // plain object
951 if (isPlainObject(v)) {
952 return observable.object(v, arg2, arg3);
953 }
954 // Array
955 if (Array.isArray(v)) {
956 return observable.array(v, arg2);
957 }
958 // Map
959 if (isES6Map(v)) {
960 return observable.map(v, arg2);
961 }
962 // Set
963 if (isES6Set(v)) {
964 return observable.set(v, arg2);
965 }
966 // other object - ignore
967 if (typeof v === "object" && v !== null) {
968 return v;
969 }
970 // anything else
971 return observable.box(v, arg2);
972}
973assign(createObservable, observableDecoratorAnnotation);
974var observableFactories = {
975 box: function box(value, options) {
976 var o = asCreateObservableOptions(options);
977 return new ObservableValue(value, getEnhancerFromOptions(o), o.name, true, o.equals);
978 },
979 array: function array(initialValues, options) {
980 var o = asCreateObservableOptions(options);
981 return (globalState.useProxies === false || o.proxy === false ? createLegacyArray : createObservableArray)(initialValues, getEnhancerFromOptions(o), o.name);
982 },
983 map: function map(initialValues, options) {
984 var o = asCreateObservableOptions(options);
985 return new ObservableMap(initialValues, getEnhancerFromOptions(o), o.name);
986 },
987 set: function set(initialValues, options) {
988 var o = asCreateObservableOptions(options);
989 return new ObservableSet(initialValues, getEnhancerFromOptions(o), o.name);
990 },
991 object: function object(props, decorators, options) {
992 return extendObservable(globalState.useProxies === false || (options == null ? void 0 : options.proxy) === false ? asObservableObject({}, options) : asDynamicObservableObject({}, options), props, decorators);
993 },
994 ref: /*#__PURE__*/createDecoratorAnnotation(observableRefAnnotation),
995 shallow: /*#__PURE__*/createDecoratorAnnotation(observableShallowAnnotation),
996 deep: observableDecoratorAnnotation,
997 struct: /*#__PURE__*/createDecoratorAnnotation(observableStructAnnotation)
998};
999// eslint-disable-next-line
1000var observable = /*#__PURE__*/assign(createObservable, observableFactories);
1001
1002var COMPUTED = "computed";
1003var COMPUTED_STRUCT = "computed.struct";
1004var computedAnnotation = /*#__PURE__*/createComputedAnnotation(COMPUTED);
1005var computedStructAnnotation = /*#__PURE__*/createComputedAnnotation(COMPUTED_STRUCT, {
1006 equals: comparer.structural
1007});
1008/**
1009 * Decorator for class properties: @computed get value() { return expr; }.
1010 * For legacy purposes also invokable as ES5 observable created: `computed(() => expr)`;
1011 */
1012var computed = function computed(arg1, arg2) {
1013 if (isStringish(arg2)) {
1014 // @computed
1015 return storeAnnotation(arg1, arg2, computedAnnotation);
1016 }
1017 if (isPlainObject(arg1)) {
1018 // @computed({ options })
1019 return createDecoratorAnnotation(createComputedAnnotation(COMPUTED, arg1));
1020 }
1021 // computed(expr, options?)
1022 {
1023 if (!isFunction(arg1)) {
1024 die("First argument to `computed` should be an expression.");
1025 }
1026 if (isFunction(arg2)) {
1027 die("A setter as second argument is no longer supported, use `{ set: fn }` option instead");
1028 }
1029 }
1030 var opts = isPlainObject(arg2) ? arg2 : {};
1031 opts.get = arg1;
1032 opts.name || (opts.name = arg1.name || ""); /* for generated name */
1033 return new ComputedValue(opts);
1034};
1035Object.assign(computed, computedAnnotation);
1036computed.struct = /*#__PURE__*/createDecoratorAnnotation(computedStructAnnotation);
1037
1038var _getDescriptor$config, _getDescriptor;
1039// we don't use globalState for these in order to avoid possible issues with multiple
1040// mobx versions
1041var currentActionId = 0;
1042var nextActionId = 1;
1043var isFunctionNameConfigurable = (_getDescriptor$config = (_getDescriptor = /*#__PURE__*/getDescriptor(function () {}, "name")) == null ? void 0 : _getDescriptor.configurable) != null ? _getDescriptor$config : false;
1044// we can safely recycle this object
1045var tmpNameDescriptor = {
1046 value: "action",
1047 configurable: true,
1048 writable: false,
1049 enumerable: false
1050};
1051function createAction(actionName, fn, autoAction, ref) {
1052 if (autoAction === void 0) {
1053 autoAction = false;
1054 }
1055 {
1056 if (!isFunction(fn)) {
1057 die("`action` can only be invoked on functions");
1058 }
1059 if (typeof actionName !== "string" || !actionName) {
1060 die("actions should have valid names, got: '" + actionName + "'");
1061 }
1062 }
1063 function res() {
1064 return executeAction(actionName, autoAction, fn, ref || this, arguments);
1065 }
1066 res.isMobxAction = true;
1067 if (isFunctionNameConfigurable) {
1068 tmpNameDescriptor.value = actionName;
1069 defineProperty(res, "name", tmpNameDescriptor);
1070 }
1071 return res;
1072}
1073function executeAction(actionName, canRunAsDerivation, fn, scope, args) {
1074 var runInfo = _startAction(actionName, canRunAsDerivation, scope, args);
1075 try {
1076 return fn.apply(scope, args);
1077 } catch (err) {
1078 runInfo.error_ = err;
1079 throw err;
1080 } finally {
1081 _endAction(runInfo);
1082 }
1083}
1084function _startAction(actionName, canRunAsDerivation,
1085// true for autoAction
1086scope, args) {
1087 var notifySpy_ = isSpyEnabled() && !!actionName;
1088 var startTime_ = 0;
1089 if ( notifySpy_) {
1090 startTime_ = Date.now();
1091 var flattenedArgs = args ? Array.from(args) : EMPTY_ARRAY;
1092 spyReportStart({
1093 type: ACTION,
1094 name: actionName,
1095 object: scope,
1096 arguments: flattenedArgs
1097 });
1098 }
1099 var prevDerivation_ = globalState.trackingDerivation;
1100 var runAsAction = !canRunAsDerivation || !prevDerivation_;
1101 startBatch();
1102 var prevAllowStateChanges_ = globalState.allowStateChanges; // by default preserve previous allow
1103 if (runAsAction) {
1104 untrackedStart();
1105 prevAllowStateChanges_ = allowStateChangesStart(true);
1106 }
1107 var prevAllowStateReads_ = allowStateReadsStart(true);
1108 var runInfo = {
1109 runAsAction_: runAsAction,
1110 prevDerivation_: prevDerivation_,
1111 prevAllowStateChanges_: prevAllowStateChanges_,
1112 prevAllowStateReads_: prevAllowStateReads_,
1113 notifySpy_: notifySpy_,
1114 startTime_: startTime_,
1115 actionId_: nextActionId++,
1116 parentActionId_: currentActionId
1117 };
1118 currentActionId = runInfo.actionId_;
1119 return runInfo;
1120}
1121function _endAction(runInfo) {
1122 if (currentActionId !== runInfo.actionId_) {
1123 die(30);
1124 }
1125 currentActionId = runInfo.parentActionId_;
1126 if (runInfo.error_ !== undefined) {
1127 globalState.suppressReactionErrors = true;
1128 }
1129 allowStateChangesEnd(runInfo.prevAllowStateChanges_);
1130 allowStateReadsEnd(runInfo.prevAllowStateReads_);
1131 endBatch();
1132 if (runInfo.runAsAction_) {
1133 untrackedEnd(runInfo.prevDerivation_);
1134 }
1135 if ( runInfo.notifySpy_) {
1136 spyReportEnd({
1137 time: Date.now() - runInfo.startTime_
1138 });
1139 }
1140 globalState.suppressReactionErrors = false;
1141}
1142function allowStateChanges(allowStateChanges, func) {
1143 var prev = allowStateChangesStart(allowStateChanges);
1144 try {
1145 return func();
1146 } finally {
1147 allowStateChangesEnd(prev);
1148 }
1149}
1150function allowStateChangesStart(allowStateChanges) {
1151 var prev = globalState.allowStateChanges;
1152 globalState.allowStateChanges = allowStateChanges;
1153 return prev;
1154}
1155function allowStateChangesEnd(prev) {
1156 globalState.allowStateChanges = prev;
1157}
1158
1159var _Symbol$toPrimitive;
1160var CREATE = "create";
1161_Symbol$toPrimitive = Symbol.toPrimitive;
1162var ObservableValue = /*#__PURE__*/function (_Atom) {
1163 _inheritsLoose(ObservableValue, _Atom);
1164 function ObservableValue(value, enhancer, name_, notifySpy, equals) {
1165 var _this;
1166 if (name_ === void 0) {
1167 name_ = "ObservableValue@" + getNextId() ;
1168 }
1169 if (notifySpy === void 0) {
1170 notifySpy = true;
1171 }
1172 if (equals === void 0) {
1173 equals = comparer["default"];
1174 }
1175 _this = _Atom.call(this, name_) || this;
1176 _this.enhancer = void 0;
1177 _this.name_ = void 0;
1178 _this.equals = void 0;
1179 _this.hasUnreportedChange_ = false;
1180 _this.interceptors_ = void 0;
1181 _this.changeListeners_ = void 0;
1182 _this.value_ = void 0;
1183 _this.dehancer = void 0;
1184 _this.enhancer = enhancer;
1185 _this.name_ = name_;
1186 _this.equals = equals;
1187 _this.value_ = enhancer(value, undefined, name_);
1188 if ( notifySpy && isSpyEnabled()) {
1189 // only notify spy if this is a stand-alone observable
1190 spyReport({
1191 type: CREATE,
1192 object: _assertThisInitialized(_this),
1193 observableKind: "value",
1194 debugObjectName: _this.name_,
1195 newValue: "" + _this.value_
1196 });
1197 }
1198 return _this;
1199 }
1200 var _proto = ObservableValue.prototype;
1201 _proto.dehanceValue = function dehanceValue(value) {
1202 if (this.dehancer !== undefined) {
1203 return this.dehancer(value);
1204 }
1205 return value;
1206 };
1207 _proto.set = function set(newValue) {
1208 var oldValue = this.value_;
1209 newValue = this.prepareNewValue_(newValue);
1210 if (newValue !== globalState.UNCHANGED) {
1211 var notifySpy = isSpyEnabled();
1212 if ( notifySpy) {
1213 spyReportStart({
1214 type: UPDATE,
1215 object: this,
1216 observableKind: "value",
1217 debugObjectName: this.name_,
1218 newValue: newValue,
1219 oldValue: oldValue
1220 });
1221 }
1222 this.setNewValue_(newValue);
1223 if ( notifySpy) {
1224 spyReportEnd();
1225 }
1226 }
1227 };
1228 _proto.prepareNewValue_ = function prepareNewValue_(newValue) {
1229 checkIfStateModificationsAreAllowed(this);
1230 if (hasInterceptors(this)) {
1231 var change = interceptChange(this, {
1232 object: this,
1233 type: UPDATE,
1234 newValue: newValue
1235 });
1236 if (!change) {
1237 return globalState.UNCHANGED;
1238 }
1239 newValue = change.newValue;
1240 }
1241 // apply modifier
1242 newValue = this.enhancer(newValue, this.value_, this.name_);
1243 return this.equals(this.value_, newValue) ? globalState.UNCHANGED : newValue;
1244 };
1245 _proto.setNewValue_ = function setNewValue_(newValue) {
1246 var oldValue = this.value_;
1247 this.value_ = newValue;
1248 this.reportChanged();
1249 if (hasListeners(this)) {
1250 notifyListeners(this, {
1251 type: UPDATE,
1252 object: this,
1253 newValue: newValue,
1254 oldValue: oldValue
1255 });
1256 }
1257 };
1258 _proto.get = function get() {
1259 this.reportObserved();
1260 return this.dehanceValue(this.value_);
1261 };
1262 _proto.intercept_ = function intercept_(handler) {
1263 return registerInterceptor(this, handler);
1264 };
1265 _proto.observe_ = function observe_(listener, fireImmediately) {
1266 if (fireImmediately) {
1267 listener({
1268 observableKind: "value",
1269 debugObjectName: this.name_,
1270 object: this,
1271 type: UPDATE,
1272 newValue: this.value_,
1273 oldValue: undefined
1274 });
1275 }
1276 return registerListener(this, listener);
1277 };
1278 _proto.raw = function raw() {
1279 // used by MST ot get undehanced value
1280 return this.value_;
1281 };
1282 _proto.toJSON = function toJSON() {
1283 return this.get();
1284 };
1285 _proto.toString = function toString() {
1286 return this.name_ + "[" + this.value_ + "]";
1287 };
1288 _proto.valueOf = function valueOf() {
1289 return toPrimitive(this.get());
1290 };
1291 _proto[_Symbol$toPrimitive] = function () {
1292 return this.valueOf();
1293 };
1294 return ObservableValue;
1295}(Atom);
1296var isObservableValue = /*#__PURE__*/createInstanceofPredicate("ObservableValue", ObservableValue);
1297
1298var _Symbol$toPrimitive$1;
1299/**
1300 * A node in the state dependency root that observes other nodes, and can be observed itself.
1301 *
1302 * ComputedValue will remember the result of the computation for the duration of the batch, or
1303 * while being observed.
1304 *
1305 * During this time it will recompute only when one of its direct dependencies changed,
1306 * but only when it is being accessed with `ComputedValue.get()`.
1307 *
1308 * Implementation description:
1309 * 1. First time it's being accessed it will compute and remember result
1310 * give back remembered result until 2. happens
1311 * 2. First time any deep dependency change, propagate POSSIBLY_STALE to all observers, wait for 3.
1312 * 3. When it's being accessed, recompute if any shallow dependency changed.
1313 * if result changed: propagate STALE to all observers, that were POSSIBLY_STALE from the last step.
1314 * go to step 2. either way
1315 *
1316 * If at any point it's outside batch and it isn't observed: reset everything and go to 1.
1317 */
1318_Symbol$toPrimitive$1 = Symbol.toPrimitive;
1319var ComputedValue = /*#__PURE__*/function () {
1320 // nodes we are looking at. Our value depends on these nodes
1321 // during tracking it's an array with new observed observers
1322
1323 // to check for cycles
1324
1325 // N.B: unminified as it is used by MST
1326
1327 /**
1328 * Create a new computed value based on a function expression.
1329 *
1330 * The `name` property is for debug purposes only.
1331 *
1332 * The `equals` property specifies the comparer function to use to determine if a newly produced
1333 * value differs from the previous value. Two comparers are provided in the library; `defaultComparer`
1334 * compares based on identity comparison (===), and `structuralComparer` deeply compares the structure.
1335 * Structural comparison can be convenient if you always produce a new aggregated object and
1336 * don't want to notify observers if it is structurally the same.
1337 * This is useful for working with vectors, mouse coordinates etc.
1338 */
1339 function ComputedValue(options) {
1340 this.dependenciesState_ = IDerivationState_.NOT_TRACKING_;
1341 this.observing_ = [];
1342 this.newObserving_ = null;
1343 this.isBeingObserved_ = false;
1344 this.isPendingUnobservation_ = false;
1345 this.observers_ = new Set();
1346 this.diffValue_ = 0;
1347 this.runId_ = 0;
1348 this.lastAccessedBy_ = 0;
1349 this.lowestObserverState_ = IDerivationState_.UP_TO_DATE_;
1350 this.unboundDepsCount_ = 0;
1351 this.value_ = new CaughtException(null);
1352 this.name_ = void 0;
1353 this.triggeredBy_ = void 0;
1354 this.isComputing_ = false;
1355 this.isRunningSetter_ = false;
1356 this.derivation = void 0;
1357 this.setter_ = void 0;
1358 this.isTracing_ = TraceMode.NONE;
1359 this.scope_ = void 0;
1360 this.equals_ = void 0;
1361 this.requiresReaction_ = void 0;
1362 this.keepAlive_ = void 0;
1363 this.onBOL = void 0;
1364 this.onBUOL = void 0;
1365 if (!options.get) {
1366 die(31);
1367 }
1368 this.derivation = options.get;
1369 this.name_ = options.name || ( "ComputedValue@" + getNextId() );
1370 if (options.set) {
1371 this.setter_ = createAction( this.name_ + "-setter" , options.set);
1372 }
1373 this.equals_ = options.equals || (options.compareStructural || options.struct ? comparer.structural : comparer["default"]);
1374 this.scope_ = options.context;
1375 this.requiresReaction_ = options.requiresReaction;
1376 this.keepAlive_ = !!options.keepAlive;
1377 }
1378 var _proto = ComputedValue.prototype;
1379 _proto.onBecomeStale_ = function onBecomeStale_() {
1380 propagateMaybeChanged(this);
1381 };
1382 _proto.onBO = function onBO() {
1383 if (this.onBOL) {
1384 this.onBOL.forEach(function (listener) {
1385 return listener();
1386 });
1387 }
1388 };
1389 _proto.onBUO = function onBUO() {
1390 if (this.onBUOL) {
1391 this.onBUOL.forEach(function (listener) {
1392 return listener();
1393 });
1394 }
1395 }
1396 /**
1397 * Returns the current value of this computed value.
1398 * Will evaluate its computation first if needed.
1399 */;
1400 _proto.get = function get() {
1401 if (this.isComputing_) {
1402 die(32, this.name_, this.derivation);
1403 }
1404 if (globalState.inBatch === 0 &&
1405 // !globalState.trackingDerivatpion &&
1406 this.observers_.size === 0 && !this.keepAlive_) {
1407 if (shouldCompute(this)) {
1408 this.warnAboutUntrackedRead_();
1409 startBatch(); // See perf test 'computed memoization'
1410 this.value_ = this.computeValue_(false);
1411 endBatch();
1412 }
1413 } else {
1414 reportObserved(this);
1415 if (shouldCompute(this)) {
1416 var prevTrackingContext = globalState.trackingContext;
1417 if (this.keepAlive_ && !prevTrackingContext) {
1418 globalState.trackingContext = this;
1419 }
1420 if (this.trackAndCompute()) {
1421 propagateChangeConfirmed(this);
1422 }
1423 globalState.trackingContext = prevTrackingContext;
1424 }
1425 }
1426 var result = this.value_;
1427 if (isCaughtException(result)) {
1428 throw result.cause;
1429 }
1430 return result;
1431 };
1432 _proto.set = function set(value) {
1433 if (this.setter_) {
1434 if (this.isRunningSetter_) {
1435 die(33, this.name_);
1436 }
1437 this.isRunningSetter_ = true;
1438 try {
1439 this.setter_.call(this.scope_, value);
1440 } finally {
1441 this.isRunningSetter_ = false;
1442 }
1443 } else {
1444 die(34, this.name_);
1445 }
1446 };
1447 _proto.trackAndCompute = function trackAndCompute() {
1448 // N.B: unminified as it is used by MST
1449 var oldValue = this.value_;
1450 var wasSuspended = /* see #1208 */this.dependenciesState_ === IDerivationState_.NOT_TRACKING_;
1451 var newValue = this.computeValue_(true);
1452 var changed = wasSuspended || isCaughtException(oldValue) || isCaughtException(newValue) || !this.equals_(oldValue, newValue);
1453 if (changed) {
1454 this.value_ = newValue;
1455 if ( isSpyEnabled()) {
1456 spyReport({
1457 observableKind: "computed",
1458 debugObjectName: this.name_,
1459 object: this.scope_,
1460 type: "update",
1461 oldValue: oldValue,
1462 newValue: newValue
1463 });
1464 }
1465 }
1466 return changed;
1467 };
1468 _proto.computeValue_ = function computeValue_(track) {
1469 this.isComputing_ = true;
1470 // don't allow state changes during computation
1471 var prev = allowStateChangesStart(false);
1472 var res;
1473 if (track) {
1474 res = trackDerivedFunction(this, this.derivation, this.scope_);
1475 } else {
1476 if (globalState.disableErrorBoundaries === true) {
1477 res = this.derivation.call(this.scope_);
1478 } else {
1479 try {
1480 res = this.derivation.call(this.scope_);
1481 } catch (e) {
1482 res = new CaughtException(e);
1483 }
1484 }
1485 }
1486 allowStateChangesEnd(prev);
1487 this.isComputing_ = false;
1488 return res;
1489 };
1490 _proto.suspend_ = function suspend_() {
1491 if (!this.keepAlive_) {
1492 clearObserving(this);
1493 this.value_ = undefined; // don't hold on to computed value!
1494 if ( this.isTracing_ !== TraceMode.NONE) {
1495 console.log("[mobx.trace] Computed value '" + this.name_ + "' was suspended and it will recompute on the next access.");
1496 }
1497 }
1498 };
1499 _proto.observe_ = function observe_(listener, fireImmediately) {
1500 var _this = this;
1501 var firstTime = true;
1502 var prevValue = undefined;
1503 return autorun(function () {
1504 // TODO: why is this in a different place than the spyReport() function? in all other observables it's called in the same place
1505 var newValue = _this.get();
1506 if (!firstTime || fireImmediately) {
1507 var prevU = untrackedStart();
1508 listener({
1509 observableKind: "computed",
1510 debugObjectName: _this.name_,
1511 type: UPDATE,
1512 object: _this,
1513 newValue: newValue,
1514 oldValue: prevValue
1515 });
1516 untrackedEnd(prevU);
1517 }
1518 firstTime = false;
1519 prevValue = newValue;
1520 });
1521 };
1522 _proto.warnAboutUntrackedRead_ = function warnAboutUntrackedRead_() {
1523 if (this.isTracing_ !== TraceMode.NONE) {
1524 console.log("[mobx.trace] Computed value '" + this.name_ + "' is being read outside a reactive context. Doing a full recompute.");
1525 }
1526 if (typeof this.requiresReaction_ === "boolean" ? this.requiresReaction_ : globalState.computedRequiresReaction) {
1527 console.warn("[mobx] Computed value '" + this.name_ + "' is being read outside a reactive context. Doing a full recompute.");
1528 }
1529 };
1530 _proto.toString = function toString() {
1531 return this.name_ + "[" + this.derivation.toString() + "]";
1532 };
1533 _proto.valueOf = function valueOf() {
1534 return toPrimitive(this.get());
1535 };
1536 _proto[_Symbol$toPrimitive$1] = function () {
1537 return this.valueOf();
1538 };
1539 return ComputedValue;
1540}();
1541var isComputedValue = /*#__PURE__*/createInstanceofPredicate("ComputedValue", ComputedValue);
1542
1543var IDerivationState_;
1544(function (IDerivationState_) {
1545 // before being run or (outside batch and not being observed)
1546 // at this point derivation is not holding any data about dependency tree
1547 IDerivationState_[IDerivationState_["NOT_TRACKING_"] = -1] = "NOT_TRACKING_";
1548 // no shallow dependency changed since last computation
1549 // won't recalculate derivation
1550 // this is what makes mobx fast
1551 IDerivationState_[IDerivationState_["UP_TO_DATE_"] = 0] = "UP_TO_DATE_";
1552 // some deep dependency changed, but don't know if shallow dependency changed
1553 // will require to check first if UP_TO_DATE or POSSIBLY_STALE
1554 // currently only ComputedValue will propagate POSSIBLY_STALE
1555 //
1556 // having this state is second big optimization:
1557 // don't have to recompute on every dependency change, but only when it's needed
1558 IDerivationState_[IDerivationState_["POSSIBLY_STALE_"] = 1] = "POSSIBLY_STALE_";
1559 // A shallow dependency has changed since last computation and the derivation
1560 // will need to recompute when it's needed next.
1561 IDerivationState_[IDerivationState_["STALE_"] = 2] = "STALE_";
1562})(IDerivationState_ || (IDerivationState_ = {}));
1563var TraceMode;
1564(function (TraceMode) {
1565 TraceMode[TraceMode["NONE"] = 0] = "NONE";
1566 TraceMode[TraceMode["LOG"] = 1] = "LOG";
1567 TraceMode[TraceMode["BREAK"] = 2] = "BREAK";
1568})(TraceMode || (TraceMode = {}));
1569var CaughtException = function CaughtException(cause) {
1570 this.cause = void 0;
1571 this.cause = cause;
1572 // Empty
1573};
1574
1575function isCaughtException(e) {
1576 return e instanceof CaughtException;
1577}
1578/**
1579 * Finds out whether any dependency of the derivation has actually changed.
1580 * If dependenciesState is 1 then it will recalculate dependencies,
1581 * if any dependency changed it will propagate it by changing dependenciesState to 2.
1582 *
1583 * By iterating over the dependencies in the same order that they were reported and
1584 * stopping on the first change, all the recalculations are only called for ComputedValues
1585 * that will be tracked by derivation. That is because we assume that if the first x
1586 * dependencies of the derivation doesn't change then the derivation should run the same way
1587 * up until accessing x-th dependency.
1588 */
1589function shouldCompute(derivation) {
1590 switch (derivation.dependenciesState_) {
1591 case IDerivationState_.UP_TO_DATE_:
1592 return false;
1593 case IDerivationState_.NOT_TRACKING_:
1594 case IDerivationState_.STALE_:
1595 return true;
1596 case IDerivationState_.POSSIBLY_STALE_:
1597 {
1598 // state propagation can occur outside of action/reactive context #2195
1599 var prevAllowStateReads = allowStateReadsStart(true);
1600 var prevUntracked = untrackedStart(); // no need for those computeds to be reported, they will be picked up in trackDerivedFunction.
1601 var obs = derivation.observing_,
1602 l = obs.length;
1603 for (var i = 0; i < l; i++) {
1604 var obj = obs[i];
1605 if (isComputedValue(obj)) {
1606 if (globalState.disableErrorBoundaries) {
1607 obj.get();
1608 } else {
1609 try {
1610 obj.get();
1611 } catch (e) {
1612 // we are not interested in the value *or* exception at this moment, but if there is one, notify all
1613 untrackedEnd(prevUntracked);
1614 allowStateReadsEnd(prevAllowStateReads);
1615 return true;
1616 }
1617 }
1618 // if ComputedValue `obj` actually changed it will be computed and propagated to its observers.
1619 // and `derivation` is an observer of `obj`
1620 // invariantShouldCompute(derivation)
1621 if (derivation.dependenciesState_ === IDerivationState_.STALE_) {
1622 untrackedEnd(prevUntracked);
1623 allowStateReadsEnd(prevAllowStateReads);
1624 return true;
1625 }
1626 }
1627 }
1628 changeDependenciesStateTo0(derivation);
1629 untrackedEnd(prevUntracked);
1630 allowStateReadsEnd(prevAllowStateReads);
1631 return false;
1632 }
1633 }
1634}
1635function isComputingDerivation() {
1636 return globalState.trackingDerivation !== null; // filter out actions inside computations
1637}
1638
1639function checkIfStateModificationsAreAllowed(atom) {
1640 var hasObservers = atom.observers_.size > 0;
1641 // Should not be possible to change observed state outside strict mode, except during initialization, see #563
1642 if (!globalState.allowStateChanges && (hasObservers || globalState.enforceActions === "always")) {
1643 console.warn("[MobX] " + (globalState.enforceActions ? "Since strict-mode is enabled, changing (observed) observable values without using an action is not allowed. Tried to modify: " : "Side effects like changing state are not allowed at this point. Are you trying to modify state from, for example, a computed value or the render function of a React component? You can wrap side effects in 'runInAction' (or decorate functions with 'action') if needed. Tried to modify: ") + atom.name_);
1644 }
1645}
1646function checkIfStateReadsAreAllowed(observable) {
1647 if ( !globalState.allowStateReads && globalState.observableRequiresReaction) {
1648 console.warn("[mobx] Observable '" + observable.name_ + "' being read outside a reactive context.");
1649 }
1650}
1651/**
1652 * Executes the provided function `f` and tracks which observables are being accessed.
1653 * The tracking information is stored on the `derivation` object and the derivation is registered
1654 * as observer of any of the accessed observables.
1655 */
1656function trackDerivedFunction(derivation, f, context) {
1657 var prevAllowStateReads = allowStateReadsStart(true);
1658 // pre allocate array allocation + room for variation in deps
1659 // array will be trimmed by bindDependencies
1660 changeDependenciesStateTo0(derivation);
1661 derivation.newObserving_ = new Array(derivation.observing_.length + 100);
1662 derivation.unboundDepsCount_ = 0;
1663 derivation.runId_ = ++globalState.runId;
1664 var prevTracking = globalState.trackingDerivation;
1665 globalState.trackingDerivation = derivation;
1666 globalState.inBatch++;
1667 var result;
1668 if (globalState.disableErrorBoundaries === true) {
1669 result = f.call(context);
1670 } else {
1671 try {
1672 result = f.call(context);
1673 } catch (e) {
1674 result = new CaughtException(e);
1675 }
1676 }
1677 globalState.inBatch--;
1678 globalState.trackingDerivation = prevTracking;
1679 bindDependencies(derivation);
1680 warnAboutDerivationWithoutDependencies(derivation);
1681 allowStateReadsEnd(prevAllowStateReads);
1682 return result;
1683}
1684function warnAboutDerivationWithoutDependencies(derivation) {
1685 if (derivation.observing_.length !== 0) {
1686 return;
1687 }
1688 if (typeof derivation.requiresObservable_ === "boolean" ? derivation.requiresObservable_ : globalState.reactionRequiresObservable) {
1689 console.warn("[mobx] Derivation '" + derivation.name_ + "' is created/updated without reading any observable value.");
1690 }
1691}
1692/**
1693 * diffs newObserving with observing.
1694 * update observing to be newObserving with unique observables
1695 * notify observers that become observed/unobserved
1696 */
1697function bindDependencies(derivation) {
1698 // invariant(derivation.dependenciesState !== IDerivationState.NOT_TRACKING, "INTERNAL ERROR bindDependencies expects derivation.dependenciesState !== -1");
1699 var prevObserving = derivation.observing_;
1700 var observing = derivation.observing_ = derivation.newObserving_;
1701 var lowestNewObservingDerivationState = IDerivationState_.UP_TO_DATE_;
1702 // Go through all new observables and check diffValue: (this list can contain duplicates):
1703 // 0: first occurrence, change to 1 and keep it
1704 // 1: extra occurrence, drop it
1705 var i0 = 0,
1706 l = derivation.unboundDepsCount_;
1707 for (var i = 0; i < l; i++) {
1708 var dep = observing[i];
1709 if (dep.diffValue_ === 0) {
1710 dep.diffValue_ = 1;
1711 if (i0 !== i) {
1712 observing[i0] = dep;
1713 }
1714 i0++;
1715 }
1716 // Upcast is 'safe' here, because if dep is IObservable, `dependenciesState` will be undefined,
1717 // not hitting the condition
1718 if (dep.dependenciesState_ > lowestNewObservingDerivationState) {
1719 lowestNewObservingDerivationState = dep.dependenciesState_;
1720 }
1721 }
1722 observing.length = i0;
1723 derivation.newObserving_ = null; // newObserving shouldn't be needed outside tracking (statement moved down to work around FF bug, see #614)
1724 // Go through all old observables and check diffValue: (it is unique after last bindDependencies)
1725 // 0: it's not in new observables, unobserve it
1726 // 1: it keeps being observed, don't want to notify it. change to 0
1727 l = prevObserving.length;
1728 while (l--) {
1729 var _dep = prevObserving[l];
1730 if (_dep.diffValue_ === 0) {
1731 removeObserver(_dep, derivation);
1732 }
1733 _dep.diffValue_ = 0;
1734 }
1735 // Go through all new observables and check diffValue: (now it should be unique)
1736 // 0: it was set to 0 in last loop. don't need to do anything.
1737 // 1: it wasn't observed, let's observe it. set back to 0
1738 while (i0--) {
1739 var _dep2 = observing[i0];
1740 if (_dep2.diffValue_ === 1) {
1741 _dep2.diffValue_ = 0;
1742 addObserver(_dep2, derivation);
1743 }
1744 }
1745 // Some new observed derivations may become stale during this derivation computation
1746 // so they have had no chance to propagate staleness (#916)
1747 if (lowestNewObservingDerivationState !== IDerivationState_.UP_TO_DATE_) {
1748 derivation.dependenciesState_ = lowestNewObservingDerivationState;
1749 derivation.onBecomeStale_();
1750 }
1751}
1752function clearObserving(derivation) {
1753 // invariant(globalState.inBatch > 0, "INTERNAL ERROR clearObserving should be called only inside batch");
1754 var obs = derivation.observing_;
1755 derivation.observing_ = [];
1756 var i = obs.length;
1757 while (i--) {
1758 removeObserver(obs[i], derivation);
1759 }
1760 derivation.dependenciesState_ = IDerivationState_.NOT_TRACKING_;
1761}
1762function untracked(action) {
1763 var prev = untrackedStart();
1764 try {
1765 return action();
1766 } finally {
1767 untrackedEnd(prev);
1768 }
1769}
1770function untrackedStart() {
1771 var prev = globalState.trackingDerivation;
1772 globalState.trackingDerivation = null;
1773 return prev;
1774}
1775function untrackedEnd(prev) {
1776 globalState.trackingDerivation = prev;
1777}
1778function allowStateReadsStart(allowStateReads) {
1779 var prev = globalState.allowStateReads;
1780 globalState.allowStateReads = allowStateReads;
1781 return prev;
1782}
1783function allowStateReadsEnd(prev) {
1784 globalState.allowStateReads = prev;
1785}
1786/**
1787 * needed to keep `lowestObserverState` correct. when changing from (2 or 1) to 0
1788 *
1789 */
1790function changeDependenciesStateTo0(derivation) {
1791 if (derivation.dependenciesState_ === IDerivationState_.UP_TO_DATE_) {
1792 return;
1793 }
1794 derivation.dependenciesState_ = IDerivationState_.UP_TO_DATE_;
1795 var obs = derivation.observing_;
1796 var i = obs.length;
1797 while (i--) {
1798 obs[i].lowestObserverState_ = IDerivationState_.UP_TO_DATE_;
1799 }
1800}
1801
1802/**
1803 * These values will persist if global state is reset
1804 */
1805var persistentKeys = ["mobxGuid", "spyListeners", "enforceActions", "computedRequiresReaction", "reactionRequiresObservable", "observableRequiresReaction", "allowStateReads", "disableErrorBoundaries", "runId", "UNCHANGED", "useProxies"];
1806var MobXGlobals = function MobXGlobals() {
1807 this.version = 6;
1808 this.UNCHANGED = {};
1809 this.trackingDerivation = null;
1810 this.trackingContext = null;
1811 this.runId = 0;
1812 this.mobxGuid = 0;
1813 this.inBatch = 0;
1814 this.pendingUnobservations = [];
1815 this.pendingReactions = [];
1816 this.isRunningReactions = false;
1817 this.allowStateChanges = false;
1818 this.allowStateReads = true;
1819 this.enforceActions = true;
1820 this.spyListeners = [];
1821 this.globalReactionErrorHandlers = [];
1822 this.computedRequiresReaction = false;
1823 this.reactionRequiresObservable = false;
1824 this.observableRequiresReaction = false;
1825 this.disableErrorBoundaries = false;
1826 this.suppressReactionErrors = false;
1827 this.useProxies = true;
1828 this.verifyProxies = false;
1829 this.safeDescriptors = true;
1830 this.stateVersion = Number.MIN_SAFE_INTEGER;
1831};
1832var canMergeGlobalState = true;
1833var isolateCalled = false;
1834var globalState = /*#__PURE__*/function () {
1835 var global = /*#__PURE__*/getGlobal();
1836 if (global.__mobxInstanceCount > 0 && !global.__mobxGlobals) {
1837 canMergeGlobalState = false;
1838 }
1839 if (global.__mobxGlobals && global.__mobxGlobals.version !== new MobXGlobals().version) {
1840 canMergeGlobalState = false;
1841 }
1842 if (!canMergeGlobalState) {
1843 // Because this is a IIFE we need to let isolateCalled a chance to change
1844 // so we run it after the event loop completed at least 1 iteration
1845 setTimeout(function () {
1846 if (!isolateCalled) {
1847 die(35);
1848 }
1849 }, 1);
1850 return new MobXGlobals();
1851 } else if (global.__mobxGlobals) {
1852 global.__mobxInstanceCount += 1;
1853 if (!global.__mobxGlobals.UNCHANGED) {
1854 global.__mobxGlobals.UNCHANGED = {};
1855 } // make merge backward compatible
1856 return global.__mobxGlobals;
1857 } else {
1858 global.__mobxInstanceCount = 1;
1859 return global.__mobxGlobals = /*#__PURE__*/new MobXGlobals();
1860 }
1861}();
1862function isolateGlobalState() {
1863 if (globalState.pendingReactions.length || globalState.inBatch || globalState.isRunningReactions) {
1864 die(36);
1865 }
1866 isolateCalled = true;
1867 if (canMergeGlobalState) {
1868 var global = getGlobal();
1869 if (--global.__mobxInstanceCount === 0) {
1870 global.__mobxGlobals = undefined;
1871 }
1872 globalState = new MobXGlobals();
1873 }
1874}
1875function getGlobalState() {
1876 return globalState;
1877}
1878/**
1879 * For testing purposes only; this will break the internal state of existing observables,
1880 * but can be used to get back at a stable state after throwing errors
1881 */
1882function resetGlobalState() {
1883 var defaultGlobals = new MobXGlobals();
1884 for (var key in defaultGlobals) {
1885 if (persistentKeys.indexOf(key) === -1) {
1886 globalState[key] = defaultGlobals[key];
1887 }
1888 }
1889 globalState.allowStateChanges = !globalState.enforceActions;
1890}
1891
1892function hasObservers(observable) {
1893 return observable.observers_ && observable.observers_.size > 0;
1894}
1895function getObservers(observable) {
1896 return observable.observers_;
1897}
1898// function invariantObservers(observable: IObservable) {
1899// const list = observable.observers
1900// const map = observable.observersIndexes
1901// const l = list.length
1902// for (let i = 0; i < l; i++) {
1903// const id = list[i].__mapid
1904// if (i) {
1905// invariant(map[id] === i, "INTERNAL ERROR maps derivation.__mapid to index in list") // for performance
1906// } else {
1907// invariant(!(id in map), "INTERNAL ERROR observer on index 0 shouldn't be held in map.") // for performance
1908// }
1909// }
1910// invariant(
1911// list.length === 0 || Object.keys(map).length === list.length - 1,
1912// "INTERNAL ERROR there is no junk in map"
1913// )
1914// }
1915function addObserver(observable, node) {
1916 // invariant(node.dependenciesState !== -1, "INTERNAL ERROR, can add only dependenciesState !== -1");
1917 // invariant(observable._observers.indexOf(node) === -1, "INTERNAL ERROR add already added node");
1918 // invariantObservers(observable);
1919 observable.observers_.add(node);
1920 if (observable.lowestObserverState_ > node.dependenciesState_) {
1921 observable.lowestObserverState_ = node.dependenciesState_;
1922 }
1923 // invariantObservers(observable);
1924 // invariant(observable._observers.indexOf(node) !== -1, "INTERNAL ERROR didn't add node");
1925}
1926
1927function removeObserver(observable, node) {
1928 // invariant(globalState.inBatch > 0, "INTERNAL ERROR, remove should be called only inside batch");
1929 // invariant(observable._observers.indexOf(node) !== -1, "INTERNAL ERROR remove already removed node");
1930 // invariantObservers(observable);
1931 observable.observers_["delete"](node);
1932 if (observable.observers_.size === 0) {
1933 // deleting last observer
1934 queueForUnobservation(observable);
1935 }
1936 // invariantObservers(observable);
1937 // invariant(observable._observers.indexOf(node) === -1, "INTERNAL ERROR remove already removed node2");
1938}
1939
1940function queueForUnobservation(observable) {
1941 if (observable.isPendingUnobservation_ === false) {
1942 // invariant(observable._observers.length === 0, "INTERNAL ERROR, should only queue for unobservation unobserved observables");
1943 observable.isPendingUnobservation_ = true;
1944 globalState.pendingUnobservations.push(observable);
1945 }
1946}
1947/**
1948 * Batch starts a transaction, at least for purposes of memoizing ComputedValues when nothing else does.
1949 * During a batch `onBecomeUnobserved` will be called at most once per observable.
1950 * Avoids unnecessary recalculations.
1951 */
1952function startBatch() {
1953 globalState.inBatch++;
1954}
1955function endBatch() {
1956 if (--globalState.inBatch === 0) {
1957 runReactions();
1958 // the batch is actually about to finish, all unobserving should happen here.
1959 var list = globalState.pendingUnobservations;
1960 for (var i = 0; i < list.length; i++) {
1961 var observable = list[i];
1962 observable.isPendingUnobservation_ = false;
1963 if (observable.observers_.size === 0) {
1964 if (observable.isBeingObserved_) {
1965 // if this observable had reactive observers, trigger the hooks
1966 observable.isBeingObserved_ = false;
1967 observable.onBUO();
1968 }
1969 if (observable instanceof ComputedValue) {
1970 // computed values are automatically teared down when the last observer leaves
1971 // this process happens recursively, this computed might be the last observabe of another, etc..
1972 observable.suspend_();
1973 }
1974 }
1975 }
1976 globalState.pendingUnobservations = [];
1977 }
1978}
1979function reportObserved(observable) {
1980 checkIfStateReadsAreAllowed(observable);
1981 var derivation = globalState.trackingDerivation;
1982 if (derivation !== null) {
1983 /**
1984 * Simple optimization, give each derivation run an unique id (runId)
1985 * Check if last time this observable was accessed the same runId is used
1986 * if this is the case, the relation is already known
1987 */
1988 if (derivation.runId_ !== observable.lastAccessedBy_) {
1989 observable.lastAccessedBy_ = derivation.runId_;
1990 // Tried storing newObserving, or observing, or both as Set, but performance didn't come close...
1991 derivation.newObserving_[derivation.unboundDepsCount_++] = observable;
1992 if (!observable.isBeingObserved_ && globalState.trackingContext) {
1993 observable.isBeingObserved_ = true;
1994 observable.onBO();
1995 }
1996 }
1997 return observable.isBeingObserved_;
1998 } else if (observable.observers_.size === 0 && globalState.inBatch > 0) {
1999 queueForUnobservation(observable);
2000 }
2001 return false;
2002}
2003// function invariantLOS(observable: IObservable, msg: string) {
2004// // it's expensive so better not run it in produciton. but temporarily helpful for testing
2005// const min = getObservers(observable).reduce((a, b) => Math.min(a, b.dependenciesState), 2)
2006// if (min >= observable.lowestObserverState) return // <- the only assumption about `lowestObserverState`
2007// throw new Error(
2008// "lowestObserverState is wrong for " +
2009// msg +
2010// " because " +
2011// min +
2012// " < " +
2013// observable.lowestObserverState
2014// )
2015// }
2016/**
2017 * NOTE: current propagation mechanism will in case of self reruning autoruns behave unexpectedly
2018 * It will propagate changes to observers from previous run
2019 * It's hard or maybe impossible (with reasonable perf) to get it right with current approach
2020 * Hopefully self reruning autoruns aren't a feature people should depend on
2021 * Also most basic use cases should be ok
2022 */
2023// Called by Atom when its value changes
2024function propagateChanged(observable) {
2025 // invariantLOS(observable, "changed start");
2026 if (observable.lowestObserverState_ === IDerivationState_.STALE_) {
2027 return;
2028 }
2029 observable.lowestObserverState_ = IDerivationState_.STALE_;
2030 // Ideally we use for..of here, but the downcompiled version is really slow...
2031 observable.observers_.forEach(function (d) {
2032 if (d.dependenciesState_ === IDerivationState_.UP_TO_DATE_) {
2033 if ( d.isTracing_ !== TraceMode.NONE) {
2034 logTraceInfo(d, observable);
2035 }
2036 d.onBecomeStale_();
2037 }
2038 d.dependenciesState_ = IDerivationState_.STALE_;
2039 });
2040 // invariantLOS(observable, "changed end");
2041}
2042// Called by ComputedValue when it recalculate and its value changed
2043function propagateChangeConfirmed(observable) {
2044 // invariantLOS(observable, "confirmed start");
2045 if (observable.lowestObserverState_ === IDerivationState_.STALE_) {
2046 return;
2047 }
2048 observable.lowestObserverState_ = IDerivationState_.STALE_;
2049 observable.observers_.forEach(function (d) {
2050 if (d.dependenciesState_ === IDerivationState_.POSSIBLY_STALE_) {
2051 d.dependenciesState_ = IDerivationState_.STALE_;
2052 if ( d.isTracing_ !== TraceMode.NONE) {
2053 logTraceInfo(d, observable);
2054 }
2055 } else if (d.dependenciesState_ === IDerivationState_.UP_TO_DATE_ // this happens during computing of `d`, just keep lowestObserverState up to date.
2056 ) {
2057 observable.lowestObserverState_ = IDerivationState_.UP_TO_DATE_;
2058 }
2059 });
2060 // invariantLOS(observable, "confirmed end");
2061}
2062// Used by computed when its dependency changed, but we don't wan't to immediately recompute.
2063function propagateMaybeChanged(observable) {
2064 // invariantLOS(observable, "maybe start");
2065 if (observable.lowestObserverState_ !== IDerivationState_.UP_TO_DATE_) {
2066 return;
2067 }
2068 observable.lowestObserverState_ = IDerivationState_.POSSIBLY_STALE_;
2069 observable.observers_.forEach(function (d) {
2070 if (d.dependenciesState_ === IDerivationState_.UP_TO_DATE_) {
2071 d.dependenciesState_ = IDerivationState_.POSSIBLY_STALE_;
2072 d.onBecomeStale_();
2073 }
2074 });
2075 // invariantLOS(observable, "maybe end");
2076}
2077
2078function logTraceInfo(derivation, observable) {
2079 console.log("[mobx.trace] '" + derivation.name_ + "' is invalidated due to a change in: '" + observable.name_ + "'");
2080 if (derivation.isTracing_ === TraceMode.BREAK) {
2081 var lines = [];
2082 printDepTree(getDependencyTree(derivation), lines, 1);
2083 // prettier-ignore
2084 new Function("debugger;\n/*\nTracing '" + derivation.name_ + "'\n\nYou are entering this break point because derivation '" + derivation.name_ + "' is being traced and '" + observable.name_ + "' is now forcing it to update.\nJust follow the stacktrace you should now see in the devtools to see precisely what piece of your code is causing this update\nThe stackframe you are looking for is at least ~6-8 stack-frames up.\n\n" + (derivation instanceof ComputedValue ? derivation.derivation.toString().replace(/[*]\//g, "/") : "") + "\n\nThe dependencies for this derivation are:\n\n" + lines.join("\n") + "\n*/\n ")();
2085 }
2086}
2087function printDepTree(tree, lines, depth) {
2088 if (lines.length >= 1000) {
2089 lines.push("(and many more)");
2090 return;
2091 }
2092 lines.push("" + "\t".repeat(depth - 1) + tree.name);
2093 if (tree.dependencies) {
2094 tree.dependencies.forEach(function (child) {
2095 return printDepTree(child, lines, depth + 1);
2096 });
2097 }
2098}
2099
2100var Reaction = /*#__PURE__*/function () {
2101 // nodes we are looking at. Our value depends on these nodes
2102
2103 function Reaction(name_, onInvalidate_, errorHandler_, requiresObservable_) {
2104 if (name_ === void 0) {
2105 name_ = "Reaction@" + getNextId() ;
2106 }
2107 this.name_ = void 0;
2108 this.onInvalidate_ = void 0;
2109 this.errorHandler_ = void 0;
2110 this.requiresObservable_ = void 0;
2111 this.observing_ = [];
2112 this.newObserving_ = [];
2113 this.dependenciesState_ = IDerivationState_.NOT_TRACKING_;
2114 this.diffValue_ = 0;
2115 this.runId_ = 0;
2116 this.unboundDepsCount_ = 0;
2117 this.isDisposed_ = false;
2118 this.isScheduled_ = false;
2119 this.isTrackPending_ = false;
2120 this.isRunning_ = false;
2121 this.isTracing_ = TraceMode.NONE;
2122 this.name_ = name_;
2123 this.onInvalidate_ = onInvalidate_;
2124 this.errorHandler_ = errorHandler_;
2125 this.requiresObservable_ = requiresObservable_;
2126 }
2127 var _proto = Reaction.prototype;
2128 _proto.onBecomeStale_ = function onBecomeStale_() {
2129 this.schedule_();
2130 };
2131 _proto.schedule_ = function schedule_() {
2132 if (!this.isScheduled_) {
2133 this.isScheduled_ = true;
2134 globalState.pendingReactions.push(this);
2135 runReactions();
2136 }
2137 };
2138 _proto.isScheduled = function isScheduled() {
2139 return this.isScheduled_;
2140 }
2141 /**
2142 * internal, use schedule() if you intend to kick off a reaction
2143 */;
2144 _proto.runReaction_ = function runReaction_() {
2145 if (!this.isDisposed_) {
2146 startBatch();
2147 this.isScheduled_ = false;
2148 var prev = globalState.trackingContext;
2149 globalState.trackingContext = this;
2150 if (shouldCompute(this)) {
2151 this.isTrackPending_ = true;
2152 try {
2153 this.onInvalidate_();
2154 if ("development" !== "production" && this.isTrackPending_ && isSpyEnabled()) {
2155 // onInvalidate didn't trigger track right away..
2156 spyReport({
2157 name: this.name_,
2158 type: "scheduled-reaction"
2159 });
2160 }
2161 } catch (e) {
2162 this.reportExceptionInDerivation_(e);
2163 }
2164 }
2165 globalState.trackingContext = prev;
2166 endBatch();
2167 }
2168 };
2169 _proto.track = function track(fn) {
2170 if (this.isDisposed_) {
2171 return;
2172 // console.warn("Reaction already disposed") // Note: Not a warning / error in mobx 4 either
2173 }
2174
2175 startBatch();
2176 var notify = isSpyEnabled();
2177 var startTime;
2178 if ( notify) {
2179 startTime = Date.now();
2180 spyReportStart({
2181 name: this.name_,
2182 type: "reaction"
2183 });
2184 }
2185 this.isRunning_ = true;
2186 var prevReaction = globalState.trackingContext; // reactions could create reactions...
2187 globalState.trackingContext = this;
2188 var result = trackDerivedFunction(this, fn, undefined);
2189 globalState.trackingContext = prevReaction;
2190 this.isRunning_ = false;
2191 this.isTrackPending_ = false;
2192 if (this.isDisposed_) {
2193 // disposed during last run. Clean up everything that was bound after the dispose call.
2194 clearObserving(this);
2195 }
2196 if (isCaughtException(result)) {
2197 this.reportExceptionInDerivation_(result.cause);
2198 }
2199 if ( notify) {
2200 spyReportEnd({
2201 time: Date.now() - startTime
2202 });
2203 }
2204 endBatch();
2205 };
2206 _proto.reportExceptionInDerivation_ = function reportExceptionInDerivation_(error) {
2207 var _this = this;
2208 if (this.errorHandler_) {
2209 this.errorHandler_(error, this);
2210 return;
2211 }
2212 if (globalState.disableErrorBoundaries) {
2213 throw error;
2214 }
2215 var message = "[mobx] Encountered an uncaught exception that was thrown by a reaction or observer component, in: '" + this + "'" ;
2216 if (!globalState.suppressReactionErrors) {
2217 console.error(message, error);
2218 /** If debugging brought you here, please, read the above message :-). Tnx! */
2219 } else {
2220 console.warn("[mobx] (error in reaction '" + this.name_ + "' suppressed, fix error of causing action below)");
2221 } // prettier-ignore
2222 if ( isSpyEnabled()) {
2223 spyReport({
2224 type: "error",
2225 name: this.name_,
2226 message: message,
2227 error: "" + error
2228 });
2229 }
2230 globalState.globalReactionErrorHandlers.forEach(function (f) {
2231 return f(error, _this);
2232 });
2233 };
2234 _proto.dispose = function dispose() {
2235 if (!this.isDisposed_) {
2236 this.isDisposed_ = true;
2237 if (!this.isRunning_) {
2238 // if disposed while running, clean up later. Maybe not optimal, but rare case
2239 startBatch();
2240 clearObserving(this);
2241 endBatch();
2242 }
2243 }
2244 };
2245 _proto.getDisposer_ = function getDisposer_(abortSignal) {
2246 var _this2 = this;
2247 var dispose = function dispose() {
2248 _this2.dispose();
2249 abortSignal == null ? void 0 : abortSignal.removeEventListener == null ? void 0 : abortSignal.removeEventListener("abort", dispose);
2250 };
2251 abortSignal == null ? void 0 : abortSignal.addEventListener == null ? void 0 : abortSignal.addEventListener("abort", dispose);
2252 dispose[$mobx] = this;
2253 return dispose;
2254 };
2255 _proto.toString = function toString() {
2256 return "Reaction[" + this.name_ + "]";
2257 };
2258 _proto.trace = function trace$1(enterBreakPoint) {
2259 if (enterBreakPoint === void 0) {
2260 enterBreakPoint = false;
2261 }
2262 trace(this, enterBreakPoint);
2263 };
2264 return Reaction;
2265}();
2266function onReactionError(handler) {
2267 globalState.globalReactionErrorHandlers.push(handler);
2268 return function () {
2269 var idx = globalState.globalReactionErrorHandlers.indexOf(handler);
2270 if (idx >= 0) {
2271 globalState.globalReactionErrorHandlers.splice(idx, 1);
2272 }
2273 };
2274}
2275/**
2276 * Magic number alert!
2277 * Defines within how many times a reaction is allowed to re-trigger itself
2278 * until it is assumed that this is gonna be a never ending loop...
2279 */
2280var MAX_REACTION_ITERATIONS = 100;
2281var reactionScheduler = function reactionScheduler(f) {
2282 return f();
2283};
2284function runReactions() {
2285 // Trampolining, if runReactions are already running, new reactions will be picked up
2286 if (globalState.inBatch > 0 || globalState.isRunningReactions) {
2287 return;
2288 }
2289 reactionScheduler(runReactionsHelper);
2290}
2291function runReactionsHelper() {
2292 globalState.isRunningReactions = true;
2293 var allReactions = globalState.pendingReactions;
2294 var iterations = 0;
2295 // While running reactions, new reactions might be triggered.
2296 // Hence we work with two variables and check whether
2297 // we converge to no remaining reactions after a while.
2298 while (allReactions.length > 0) {
2299 if (++iterations === MAX_REACTION_ITERATIONS) {
2300 console.error( "Reaction doesn't converge to a stable state after " + MAX_REACTION_ITERATIONS + " iterations." + (" Probably there is a cycle in the reactive function: " + allReactions[0]) );
2301 allReactions.splice(0); // clear reactions
2302 }
2303
2304 var remainingReactions = allReactions.splice(0);
2305 for (var i = 0, l = remainingReactions.length; i < l; i++) {
2306 remainingReactions[i].runReaction_();
2307 }
2308 }
2309 globalState.isRunningReactions = false;
2310}
2311var isReaction = /*#__PURE__*/createInstanceofPredicate("Reaction", Reaction);
2312function setReactionScheduler(fn) {
2313 var baseScheduler = reactionScheduler;
2314 reactionScheduler = function reactionScheduler(f) {
2315 return fn(function () {
2316 return baseScheduler(f);
2317 });
2318 };
2319}
2320
2321function isSpyEnabled() {
2322 return !!globalState.spyListeners.length;
2323}
2324function spyReport(event) {
2325 if (!globalState.spyListeners.length) {
2326 return;
2327 }
2328 var listeners = globalState.spyListeners;
2329 for (var i = 0, l = listeners.length; i < l; i++) {
2330 listeners[i](event);
2331 }
2332}
2333function spyReportStart(event) {
2334 var change = _extends({}, event, {
2335 spyReportStart: true
2336 });
2337 spyReport(change);
2338}
2339var END_EVENT = {
2340 type: "report-end",
2341 spyReportEnd: true
2342};
2343function spyReportEnd(change) {
2344 if (change) {
2345 spyReport(_extends({}, change, {
2346 type: "report-end",
2347 spyReportEnd: true
2348 }));
2349 } else {
2350 spyReport(END_EVENT);
2351 }
2352}
2353function spy(listener) {
2354 {
2355 globalState.spyListeners.push(listener);
2356 return once(function () {
2357 globalState.spyListeners = globalState.spyListeners.filter(function (l) {
2358 return l !== listener;
2359 });
2360 });
2361 }
2362}
2363
2364var ACTION = "action";
2365var ACTION_BOUND = "action.bound";
2366var AUTOACTION = "autoAction";
2367var AUTOACTION_BOUND = "autoAction.bound";
2368var DEFAULT_ACTION_NAME = "<unnamed action>";
2369var actionAnnotation = /*#__PURE__*/createActionAnnotation(ACTION);
2370var actionBoundAnnotation = /*#__PURE__*/createActionAnnotation(ACTION_BOUND, {
2371 bound: true
2372});
2373var autoActionAnnotation = /*#__PURE__*/createActionAnnotation(AUTOACTION, {
2374 autoAction: true
2375});
2376var autoActionBoundAnnotation = /*#__PURE__*/createActionAnnotation(AUTOACTION_BOUND, {
2377 autoAction: true,
2378 bound: true
2379});
2380function createActionFactory(autoAction) {
2381 var res = function action(arg1, arg2) {
2382 // action(fn() {})
2383 if (isFunction(arg1)) {
2384 return createAction(arg1.name || DEFAULT_ACTION_NAME, arg1, autoAction);
2385 }
2386 // action("name", fn() {})
2387 if (isFunction(arg2)) {
2388 return createAction(arg1, arg2, autoAction);
2389 }
2390 // @action
2391 if (isStringish(arg2)) {
2392 return storeAnnotation(arg1, arg2, autoAction ? autoActionAnnotation : actionAnnotation);
2393 }
2394 // action("name") & @action("name")
2395 if (isStringish(arg1)) {
2396 return createDecoratorAnnotation(createActionAnnotation(autoAction ? AUTOACTION : ACTION, {
2397 name: arg1,
2398 autoAction: autoAction
2399 }));
2400 }
2401 {
2402 die("Invalid arguments for `action`");
2403 }
2404 };
2405 return res;
2406}
2407var action = /*#__PURE__*/createActionFactory(false);
2408Object.assign(action, actionAnnotation);
2409var autoAction = /*#__PURE__*/createActionFactory(true);
2410Object.assign(autoAction, autoActionAnnotation);
2411action.bound = /*#__PURE__*/createDecoratorAnnotation(actionBoundAnnotation);
2412autoAction.bound = /*#__PURE__*/createDecoratorAnnotation(autoActionBoundAnnotation);
2413function runInAction(fn) {
2414 return executeAction(fn.name || DEFAULT_ACTION_NAME, false, fn, this, undefined);
2415}
2416function isAction(thing) {
2417 return isFunction(thing) && thing.isMobxAction === true;
2418}
2419
2420/**
2421 * Creates a named reactive view and keeps it alive, so that the view is always
2422 * updated if one of the dependencies changes, even when the view is not further used by something else.
2423 * @param view The reactive view
2424 * @returns disposer function, which can be used to stop the view from being updated in the future.
2425 */
2426function autorun(view, opts) {
2427 var _opts$name, _opts, _opts2, _opts2$signal, _opts3;
2428 if (opts === void 0) {
2429 opts = EMPTY_OBJECT;
2430 }
2431 {
2432 if (!isFunction(view)) {
2433 die("Autorun expects a function as first argument");
2434 }
2435 if (isAction(view)) {
2436 die("Autorun does not accept actions since actions are untrackable");
2437 }
2438 }
2439 var name = (_opts$name = (_opts = opts) == null ? void 0 : _opts.name) != null ? _opts$name : view.name || "Autorun@" + getNextId() ;
2440 var runSync = !opts.scheduler && !opts.delay;
2441 var reaction;
2442 if (runSync) {
2443 // normal autorun
2444 reaction = new Reaction(name, function () {
2445 this.track(reactionRunner);
2446 }, opts.onError, opts.requiresObservable);
2447 } else {
2448 var scheduler = createSchedulerFromOptions(opts);
2449 // debounced autorun
2450 var isScheduled = false;
2451 reaction = new Reaction(name, function () {
2452 if (!isScheduled) {
2453 isScheduled = true;
2454 scheduler(function () {
2455 isScheduled = false;
2456 if (!reaction.isDisposed_) {
2457 reaction.track(reactionRunner);
2458 }
2459 });
2460 }
2461 }, opts.onError, opts.requiresObservable);
2462 }
2463 function reactionRunner() {
2464 view(reaction);
2465 }
2466 if (!((_opts2 = opts) != null && (_opts2$signal = _opts2.signal) != null && _opts2$signal.aborted)) {
2467 reaction.schedule_();
2468 }
2469 return reaction.getDisposer_((_opts3 = opts) == null ? void 0 : _opts3.signal);
2470}
2471var run = function run(f) {
2472 return f();
2473};
2474function createSchedulerFromOptions(opts) {
2475 return opts.scheduler ? opts.scheduler : opts.delay ? function (f) {
2476 return setTimeout(f, opts.delay);
2477 } : run;
2478}
2479function reaction(expression, effect, opts) {
2480 var _opts$name2, _opts4, _opts4$signal, _opts5;
2481 if (opts === void 0) {
2482 opts = EMPTY_OBJECT;
2483 }
2484 {
2485 if (!isFunction(expression) || !isFunction(effect)) {
2486 die("First and second argument to reaction should be functions");
2487 }
2488 if (!isPlainObject(opts)) {
2489 die("Third argument of reactions should be an object");
2490 }
2491 }
2492 var name = (_opts$name2 = opts.name) != null ? _opts$name2 : "Reaction@" + getNextId() ;
2493 var effectAction = action(name, opts.onError ? wrapErrorHandler(opts.onError, effect) : effect);
2494 var runSync = !opts.scheduler && !opts.delay;
2495 var scheduler = createSchedulerFromOptions(opts);
2496 var firstTime = true;
2497 var isScheduled = false;
2498 var value;
2499 var oldValue;
2500 var equals = opts.compareStructural ? comparer.structural : opts.equals || comparer["default"];
2501 var r = new Reaction(name, function () {
2502 if (firstTime || runSync) {
2503 reactionRunner();
2504 } else if (!isScheduled) {
2505 isScheduled = true;
2506 scheduler(reactionRunner);
2507 }
2508 }, opts.onError, opts.requiresObservable);
2509 function reactionRunner() {
2510 isScheduled = false;
2511 if (r.isDisposed_) {
2512 return;
2513 }
2514 var changed = false;
2515 r.track(function () {
2516 var nextValue = allowStateChanges(false, function () {
2517 return expression(r);
2518 });
2519 changed = firstTime || !equals(value, nextValue);
2520 oldValue = value;
2521 value = nextValue;
2522 });
2523 if (firstTime && opts.fireImmediately) {
2524 effectAction(value, oldValue, r);
2525 } else if (!firstTime && changed) {
2526 effectAction(value, oldValue, r);
2527 }
2528 firstTime = false;
2529 }
2530 if (!((_opts4 = opts) != null && (_opts4$signal = _opts4.signal) != null && _opts4$signal.aborted)) {
2531 r.schedule_();
2532 }
2533 return r.getDisposer_((_opts5 = opts) == null ? void 0 : _opts5.signal);
2534}
2535function wrapErrorHandler(errorHandler, baseFn) {
2536 return function () {
2537 try {
2538 return baseFn.apply(this, arguments);
2539 } catch (e) {
2540 errorHandler.call(this, e);
2541 }
2542 };
2543}
2544
2545var ON_BECOME_OBSERVED = "onBO";
2546var ON_BECOME_UNOBSERVED = "onBUO";
2547function onBecomeObserved(thing, arg2, arg3) {
2548 return interceptHook(ON_BECOME_OBSERVED, thing, arg2, arg3);
2549}
2550function onBecomeUnobserved(thing, arg2, arg3) {
2551 return interceptHook(ON_BECOME_UNOBSERVED, thing, arg2, arg3);
2552}
2553function interceptHook(hook, thing, arg2, arg3) {
2554 var atom = typeof arg3 === "function" ? getAtom(thing, arg2) : getAtom(thing);
2555 var cb = isFunction(arg3) ? arg3 : arg2;
2556 var listenersKey = hook + "L";
2557 if (atom[listenersKey]) {
2558 atom[listenersKey].add(cb);
2559 } else {
2560 atom[listenersKey] = new Set([cb]);
2561 }
2562 return function () {
2563 var hookListeners = atom[listenersKey];
2564 if (hookListeners) {
2565 hookListeners["delete"](cb);
2566 if (hookListeners.size === 0) {
2567 delete atom[listenersKey];
2568 }
2569 }
2570 };
2571}
2572
2573var NEVER = "never";
2574var ALWAYS = "always";
2575var OBSERVED = "observed";
2576// const IF_AVAILABLE = "ifavailable"
2577function configure(options) {
2578 if (options.isolateGlobalState === true) {
2579 isolateGlobalState();
2580 }
2581 var useProxies = options.useProxies,
2582 enforceActions = options.enforceActions;
2583 if (useProxies !== undefined) {
2584 globalState.useProxies = useProxies === ALWAYS ? true : useProxies === NEVER ? false : typeof Proxy !== "undefined";
2585 }
2586 if (useProxies === "ifavailable") {
2587 globalState.verifyProxies = true;
2588 }
2589 if (enforceActions !== undefined) {
2590 var ea = enforceActions === ALWAYS ? ALWAYS : enforceActions === OBSERVED;
2591 globalState.enforceActions = ea;
2592 globalState.allowStateChanges = ea === true || ea === ALWAYS ? false : true;
2593 }
2594 ["computedRequiresReaction", "reactionRequiresObservable", "observableRequiresReaction", "disableErrorBoundaries", "safeDescriptors"].forEach(function (key) {
2595 if (key in options) {
2596 globalState[key] = !!options[key];
2597 }
2598 });
2599 globalState.allowStateReads = !globalState.observableRequiresReaction;
2600 if ( globalState.disableErrorBoundaries === true) {
2601 console.warn("WARNING: Debug feature only. MobX will NOT recover from errors when `disableErrorBoundaries` is enabled.");
2602 }
2603 if (options.reactionScheduler) {
2604 setReactionScheduler(options.reactionScheduler);
2605 }
2606}
2607
2608function extendObservable(target, properties, annotations, options) {
2609 {
2610 if (arguments.length > 4) {
2611 die("'extendObservable' expected 2-4 arguments");
2612 }
2613 if (typeof target !== "object") {
2614 die("'extendObservable' expects an object as first argument");
2615 }
2616 if (isObservableMap(target)) {
2617 die("'extendObservable' should not be used on maps, use map.merge instead");
2618 }
2619 if (!isPlainObject(properties)) {
2620 die("'extendObservable' only accepts plain objects as second argument");
2621 }
2622 if (isObservable(properties) || isObservable(annotations)) {
2623 die("Extending an object with another observable (object) is not supported");
2624 }
2625 }
2626 // Pull descriptors first, so we don't have to deal with props added by administration ($mobx)
2627 var descriptors = getOwnPropertyDescriptors(properties);
2628 var adm = asObservableObject(target, options)[$mobx];
2629 startBatch();
2630 try {
2631 ownKeys(descriptors).forEach(function (key) {
2632 adm.extend_(key, descriptors[key],
2633 // must pass "undefined" for { key: undefined }
2634 !annotations ? true : key in annotations ? annotations[key] : true);
2635 });
2636 } finally {
2637 endBatch();
2638 }
2639 return target;
2640}
2641
2642function getDependencyTree(thing, property) {
2643 return nodeToDependencyTree(getAtom(thing, property));
2644}
2645function nodeToDependencyTree(node) {
2646 var result = {
2647 name: node.name_
2648 };
2649 if (node.observing_ && node.observing_.length > 0) {
2650 result.dependencies = unique(node.observing_).map(nodeToDependencyTree);
2651 }
2652 return result;
2653}
2654function getObserverTree(thing, property) {
2655 return nodeToObserverTree(getAtom(thing, property));
2656}
2657function nodeToObserverTree(node) {
2658 var result = {
2659 name: node.name_
2660 };
2661 if (hasObservers(node)) {
2662 result.observers = Array.from(getObservers(node)).map(nodeToObserverTree);
2663 }
2664 return result;
2665}
2666function unique(list) {
2667 return Array.from(new Set(list));
2668}
2669
2670var generatorId = 0;
2671function FlowCancellationError() {
2672 this.message = "FLOW_CANCELLED";
2673}
2674FlowCancellationError.prototype = /*#__PURE__*/Object.create(Error.prototype);
2675function isFlowCancellationError(error) {
2676 return error instanceof FlowCancellationError;
2677}
2678var flowAnnotation = /*#__PURE__*/createFlowAnnotation("flow");
2679var flowBoundAnnotation = /*#__PURE__*/createFlowAnnotation("flow.bound", {
2680 bound: true
2681});
2682var flow = /*#__PURE__*/Object.assign(function flow(arg1, arg2) {
2683 // @flow
2684 if (isStringish(arg2)) {
2685 return storeAnnotation(arg1, arg2, flowAnnotation);
2686 }
2687 // flow(fn)
2688 if ( arguments.length !== 1) {
2689 die("Flow expects single argument with generator function");
2690 }
2691 var generator = arg1;
2692 var name = generator.name || "<unnamed flow>";
2693 // Implementation based on https://github.com/tj/co/blob/master/index.js
2694 var res = function res() {
2695 var ctx = this;
2696 var args = arguments;
2697 var runId = ++generatorId;
2698 var gen = action(name + " - runid: " + runId + " - init", generator).apply(ctx, args);
2699 var rejector;
2700 var pendingPromise = undefined;
2701 var promise = new Promise(function (resolve, reject) {
2702 var stepId = 0;
2703 rejector = reject;
2704 function onFulfilled(res) {
2705 pendingPromise = undefined;
2706 var ret;
2707 try {
2708 ret = action(name + " - runid: " + runId + " - yield " + stepId++, gen.next).call(gen, res);
2709 } catch (e) {
2710 return reject(e);
2711 }
2712 next(ret);
2713 }
2714 function onRejected(err) {
2715 pendingPromise = undefined;
2716 var ret;
2717 try {
2718 ret = action(name + " - runid: " + runId + " - yield " + stepId++, gen["throw"]).call(gen, err);
2719 } catch (e) {
2720 return reject(e);
2721 }
2722 next(ret);
2723 }
2724 function next(ret) {
2725 if (isFunction(ret == null ? void 0 : ret.then)) {
2726 // an async iterator
2727 ret.then(next, reject);
2728 return;
2729 }
2730 if (ret.done) {
2731 return resolve(ret.value);
2732 }
2733 pendingPromise = Promise.resolve(ret.value);
2734 return pendingPromise.then(onFulfilled, onRejected);
2735 }
2736 onFulfilled(undefined); // kick off the process
2737 });
2738
2739 promise.cancel = action(name + " - runid: " + runId + " - cancel", function () {
2740 try {
2741 if (pendingPromise) {
2742 cancelPromise(pendingPromise);
2743 }
2744 // Finally block can return (or yield) stuff..
2745 var _res = gen["return"](undefined);
2746 // eat anything that promise would do, it's cancelled!
2747 var yieldedPromise = Promise.resolve(_res.value);
2748 yieldedPromise.then(noop, noop);
2749 cancelPromise(yieldedPromise); // maybe it can be cancelled :)
2750 // reject our original promise
2751 rejector(new FlowCancellationError());
2752 } catch (e) {
2753 rejector(e); // there could be a throwing finally block
2754 }
2755 });
2756
2757 return promise;
2758 };
2759 res.isMobXFlow = true;
2760 return res;
2761}, flowAnnotation);
2762flow.bound = /*#__PURE__*/createDecoratorAnnotation(flowBoundAnnotation);
2763function cancelPromise(promise) {
2764 if (isFunction(promise.cancel)) {
2765 promise.cancel();
2766 }
2767}
2768function flowResult(result) {
2769 return result; // just tricking TypeScript :)
2770}
2771
2772function isFlow(fn) {
2773 return (fn == null ? void 0 : fn.isMobXFlow) === true;
2774}
2775
2776function interceptReads(thing, propOrHandler, handler) {
2777 var target;
2778 if (isObservableMap(thing) || isObservableArray(thing) || isObservableValue(thing)) {
2779 target = getAdministration(thing);
2780 } else if (isObservableObject(thing)) {
2781 if ( !isStringish(propOrHandler)) {
2782 return die("InterceptReads can only be used with a specific property, not with an object in general");
2783 }
2784 target = getAdministration(thing, propOrHandler);
2785 } else {
2786 return die("Expected observable map, object or array as first array");
2787 }
2788 if ( target.dehancer !== undefined) {
2789 return die("An intercept reader was already established");
2790 }
2791 target.dehancer = typeof propOrHandler === "function" ? propOrHandler : handler;
2792 return function () {
2793 target.dehancer = undefined;
2794 };
2795}
2796
2797function intercept(thing, propOrHandler, handler) {
2798 if (isFunction(handler)) {
2799 return interceptProperty(thing, propOrHandler, handler);
2800 } else {
2801 return interceptInterceptable(thing, propOrHandler);
2802 }
2803}
2804function interceptInterceptable(thing, handler) {
2805 return getAdministration(thing).intercept_(handler);
2806}
2807function interceptProperty(thing, property, handler) {
2808 return getAdministration(thing, property).intercept_(handler);
2809}
2810
2811function _isComputed(value, property) {
2812 if (property === undefined) {
2813 return isComputedValue(value);
2814 }
2815 if (isObservableObject(value) === false) {
2816 return false;
2817 }
2818 if (!value[$mobx].values_.has(property)) {
2819 return false;
2820 }
2821 var atom = getAtom(value, property);
2822 return isComputedValue(atom);
2823}
2824function isComputed(value) {
2825 if ( arguments.length > 1) {
2826 return die("isComputed expects only 1 argument. Use isComputedProp to inspect the observability of a property");
2827 }
2828 return _isComputed(value);
2829}
2830function isComputedProp(value, propName) {
2831 if ( !isStringish(propName)) {
2832 return die("isComputed expected a property name as second argument");
2833 }
2834 return _isComputed(value, propName);
2835}
2836
2837function _isObservable(value, property) {
2838 if (!value) {
2839 return false;
2840 }
2841 if (property !== undefined) {
2842 if ( (isObservableMap(value) || isObservableArray(value))) {
2843 return die("isObservable(object, propertyName) is not supported for arrays and maps. Use map.has or array.length instead.");
2844 }
2845 if (isObservableObject(value)) {
2846 return value[$mobx].values_.has(property);
2847 }
2848 return false;
2849 }
2850 // For first check, see #701
2851 return isObservableObject(value) || !!value[$mobx] || isAtom(value) || isReaction(value) || isComputedValue(value);
2852}
2853function isObservable(value) {
2854 if ( arguments.length !== 1) {
2855 die("isObservable expects only 1 argument. Use isObservableProp to inspect the observability of a property");
2856 }
2857 return _isObservable(value);
2858}
2859function isObservableProp(value, propName) {
2860 if ( !isStringish(propName)) {
2861 return die("expected a property name as second argument");
2862 }
2863 return _isObservable(value, propName);
2864}
2865
2866function keys(obj) {
2867 if (isObservableObject(obj)) {
2868 return obj[$mobx].keys_();
2869 }
2870 if (isObservableMap(obj) || isObservableSet(obj)) {
2871 return Array.from(obj.keys());
2872 }
2873 if (isObservableArray(obj)) {
2874 return obj.map(function (_, index) {
2875 return index;
2876 });
2877 }
2878 die(5);
2879}
2880function values(obj) {
2881 if (isObservableObject(obj)) {
2882 return keys(obj).map(function (key) {
2883 return obj[key];
2884 });
2885 }
2886 if (isObservableMap(obj)) {
2887 return keys(obj).map(function (key) {
2888 return obj.get(key);
2889 });
2890 }
2891 if (isObservableSet(obj)) {
2892 return Array.from(obj.values());
2893 }
2894 if (isObservableArray(obj)) {
2895 return obj.slice();
2896 }
2897 die(6);
2898}
2899function entries(obj) {
2900 if (isObservableObject(obj)) {
2901 return keys(obj).map(function (key) {
2902 return [key, obj[key]];
2903 });
2904 }
2905 if (isObservableMap(obj)) {
2906 return keys(obj).map(function (key) {
2907 return [key, obj.get(key)];
2908 });
2909 }
2910 if (isObservableSet(obj)) {
2911 return Array.from(obj.entries());
2912 }
2913 if (isObservableArray(obj)) {
2914 return obj.map(function (key, index) {
2915 return [index, key];
2916 });
2917 }
2918 die(7);
2919}
2920function set(obj, key, value) {
2921 if (arguments.length === 2 && !isObservableSet(obj)) {
2922 startBatch();
2923 var _values = key;
2924 try {
2925 for (var _key in _values) {
2926 set(obj, _key, _values[_key]);
2927 }
2928 } finally {
2929 endBatch();
2930 }
2931 return;
2932 }
2933 if (isObservableObject(obj)) {
2934 obj[$mobx].set_(key, value);
2935 } else if (isObservableMap(obj)) {
2936 obj.set(key, value);
2937 } else if (isObservableSet(obj)) {
2938 obj.add(key);
2939 } else if (isObservableArray(obj)) {
2940 if (typeof key !== "number") {
2941 key = parseInt(key, 10);
2942 }
2943 if (key < 0) {
2944 die("Invalid index: '" + key + "'");
2945 }
2946 startBatch();
2947 if (key >= obj.length) {
2948 obj.length = key + 1;
2949 }
2950 obj[key] = value;
2951 endBatch();
2952 } else {
2953 die(8);
2954 }
2955}
2956function remove(obj, key) {
2957 if (isObservableObject(obj)) {
2958 obj[$mobx].delete_(key);
2959 } else if (isObservableMap(obj)) {
2960 obj["delete"](key);
2961 } else if (isObservableSet(obj)) {
2962 obj["delete"](key);
2963 } else if (isObservableArray(obj)) {
2964 if (typeof key !== "number") {
2965 key = parseInt(key, 10);
2966 }
2967 obj.splice(key, 1);
2968 } else {
2969 die(9);
2970 }
2971}
2972function has(obj, key) {
2973 if (isObservableObject(obj)) {
2974 return obj[$mobx].has_(key);
2975 } else if (isObservableMap(obj)) {
2976 return obj.has(key);
2977 } else if (isObservableSet(obj)) {
2978 return obj.has(key);
2979 } else if (isObservableArray(obj)) {
2980 return key >= 0 && key < obj.length;
2981 }
2982 die(10);
2983}
2984function get(obj, key) {
2985 if (!has(obj, key)) {
2986 return undefined;
2987 }
2988 if (isObservableObject(obj)) {
2989 return obj[$mobx].get_(key);
2990 } else if (isObservableMap(obj)) {
2991 return obj.get(key);
2992 } else if (isObservableArray(obj)) {
2993 return obj[key];
2994 }
2995 die(11);
2996}
2997function apiDefineProperty(obj, key, descriptor) {
2998 if (isObservableObject(obj)) {
2999 return obj[$mobx].defineProperty_(key, descriptor);
3000 }
3001 die(39);
3002}
3003function apiOwnKeys(obj) {
3004 if (isObservableObject(obj)) {
3005 return obj[$mobx].ownKeys_();
3006 }
3007 die(38);
3008}
3009
3010function observe(thing, propOrCb, cbOrFire, fireImmediately) {
3011 if (isFunction(cbOrFire)) {
3012 return observeObservableProperty(thing, propOrCb, cbOrFire, fireImmediately);
3013 } else {
3014 return observeObservable(thing, propOrCb, cbOrFire);
3015 }
3016}
3017function observeObservable(thing, listener, fireImmediately) {
3018 return getAdministration(thing).observe_(listener, fireImmediately);
3019}
3020function observeObservableProperty(thing, property, listener, fireImmediately) {
3021 return getAdministration(thing, property).observe_(listener, fireImmediately);
3022}
3023
3024function cache(map, key, value) {
3025 map.set(key, value);
3026 return value;
3027}
3028function toJSHelper(source, __alreadySeen) {
3029 if (source == null || typeof source !== "object" || source instanceof Date || !isObservable(source)) {
3030 return source;
3031 }
3032 if (isObservableValue(source) || isComputedValue(source)) {
3033 return toJSHelper(source.get(), __alreadySeen);
3034 }
3035 if (__alreadySeen.has(source)) {
3036 return __alreadySeen.get(source);
3037 }
3038 if (isObservableArray(source)) {
3039 var res = cache(__alreadySeen, source, new Array(source.length));
3040 source.forEach(function (value, idx) {
3041 res[idx] = toJSHelper(value, __alreadySeen);
3042 });
3043 return res;
3044 }
3045 if (isObservableSet(source)) {
3046 var _res = cache(__alreadySeen, source, new Set());
3047 source.forEach(function (value) {
3048 _res.add(toJSHelper(value, __alreadySeen));
3049 });
3050 return _res;
3051 }
3052 if (isObservableMap(source)) {
3053 var _res2 = cache(__alreadySeen, source, new Map());
3054 source.forEach(function (value, key) {
3055 _res2.set(key, toJSHelper(value, __alreadySeen));
3056 });
3057 return _res2;
3058 } else {
3059 // must be observable object
3060 var _res3 = cache(__alreadySeen, source, {});
3061 apiOwnKeys(source).forEach(function (key) {
3062 if (objectPrototype.propertyIsEnumerable.call(source, key)) {
3063 _res3[key] = toJSHelper(source[key], __alreadySeen);
3064 }
3065 });
3066 return _res3;
3067 }
3068}
3069/**
3070 * Recursively converts an observable to it's non-observable native counterpart.
3071 * It does NOT recurse into non-observables, these are left as they are, even if they contain observables.
3072 * Computed and other non-enumerable properties are completely ignored.
3073 * Complex scenarios require custom solution, eg implementing `toJSON` or using `serializr` lib.
3074 */
3075function toJS(source, options) {
3076 if ( options) {
3077 die("toJS no longer supports options");
3078 }
3079 return toJSHelper(source, new Map());
3080}
3081
3082function trace() {
3083 var enterBreakPoint = false;
3084 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
3085 args[_key] = arguments[_key];
3086 }
3087 if (typeof args[args.length - 1] === "boolean") {
3088 enterBreakPoint = args.pop();
3089 }
3090 var derivation = getAtomFromArgs(args);
3091 if (!derivation) {
3092 return die("'trace(break?)' can only be used inside a tracked computed value or a Reaction. Consider passing in the computed value or reaction explicitly");
3093 }
3094 if (derivation.isTracing_ === TraceMode.NONE) {
3095 console.log("[mobx.trace] '" + derivation.name_ + "' tracing enabled");
3096 }
3097 derivation.isTracing_ = enterBreakPoint ? TraceMode.BREAK : TraceMode.LOG;
3098}
3099function getAtomFromArgs(args) {
3100 switch (args.length) {
3101 case 0:
3102 return globalState.trackingDerivation;
3103 case 1:
3104 return getAtom(args[0]);
3105 case 2:
3106 return getAtom(args[0], args[1]);
3107 }
3108}
3109
3110/**
3111 * During a transaction no views are updated until the end of the transaction.
3112 * The transaction will be run synchronously nonetheless.
3113 *
3114 * @param action a function that updates some reactive state
3115 * @returns any value that was returned by the 'action' parameter.
3116 */
3117function transaction(action, thisArg) {
3118 if (thisArg === void 0) {
3119 thisArg = undefined;
3120 }
3121 startBatch();
3122 try {
3123 return action.apply(thisArg);
3124 } finally {
3125 endBatch();
3126 }
3127}
3128
3129function when(predicate, arg1, arg2) {
3130 if (arguments.length === 1 || arg1 && typeof arg1 === "object") {
3131 return whenPromise(predicate, arg1);
3132 }
3133 return _when(predicate, arg1, arg2 || {});
3134}
3135function _when(predicate, effect, opts) {
3136 var timeoutHandle;
3137 if (typeof opts.timeout === "number") {
3138 var error = new Error("WHEN_TIMEOUT");
3139 timeoutHandle = setTimeout(function () {
3140 if (!disposer[$mobx].isDisposed_) {
3141 disposer();
3142 if (opts.onError) {
3143 opts.onError(error);
3144 } else {
3145 throw error;
3146 }
3147 }
3148 }, opts.timeout);
3149 }
3150 opts.name = opts.name || "When@" + getNextId() ;
3151 var effectAction = createAction( opts.name + "-effect" , effect);
3152 // eslint-disable-next-line
3153 var disposer = autorun(function (r) {
3154 // predicate should not change state
3155 var cond = allowStateChanges(false, predicate);
3156 if (cond) {
3157 r.dispose();
3158 if (timeoutHandle) {
3159 clearTimeout(timeoutHandle);
3160 }
3161 effectAction();
3162 }
3163 }, opts);
3164 return disposer;
3165}
3166function whenPromise(predicate, opts) {
3167 var _opts$signal;
3168 if ( opts && opts.onError) {
3169 return die("the options 'onError' and 'promise' cannot be combined");
3170 }
3171 if (opts != null && (_opts$signal = opts.signal) != null && _opts$signal.aborted) {
3172 return Object.assign(Promise.reject(new Error("WHEN_ABORTED")), {
3173 cancel: function cancel() {
3174 return null;
3175 }
3176 });
3177 }
3178 var cancel;
3179 var abort;
3180 var res = new Promise(function (resolve, reject) {
3181 var _opts$signal2;
3182 var disposer = _when(predicate, resolve, _extends({}, opts, {
3183 onError: reject
3184 }));
3185 cancel = function cancel() {
3186 disposer();
3187 reject(new Error("WHEN_CANCELLED"));
3188 };
3189 abort = function abort() {
3190 disposer();
3191 reject(new Error("WHEN_ABORTED"));
3192 };
3193 opts == null ? void 0 : (_opts$signal2 = opts.signal) == null ? void 0 : _opts$signal2.addEventListener == null ? void 0 : _opts$signal2.addEventListener("abort", abort);
3194 })["finally"](function () {
3195 var _opts$signal3;
3196 return opts == null ? void 0 : (_opts$signal3 = opts.signal) == null ? void 0 : _opts$signal3.removeEventListener == null ? void 0 : _opts$signal3.removeEventListener("abort", abort);
3197 });
3198 res.cancel = cancel;
3199 return res;
3200}
3201
3202function getAdm(target) {
3203 return target[$mobx];
3204}
3205// Optimization: we don't need the intermediate objects and could have a completely custom administration for DynamicObjects,
3206// and skip either the internal values map, or the base object with its property descriptors!
3207var objectProxyTraps = {
3208 has: function has(target, name) {
3209 if ( globalState.trackingDerivation) {
3210 warnAboutProxyRequirement("detect new properties using the 'in' operator. Use 'has' from 'mobx' instead.");
3211 }
3212 return getAdm(target).has_(name);
3213 },
3214 get: function get(target, name) {
3215 return getAdm(target).get_(name);
3216 },
3217 set: function set(target, name, value) {
3218 var _getAdm$set_;
3219 if (!isStringish(name)) {
3220 return false;
3221 }
3222 if ( !getAdm(target).values_.has(name)) {
3223 warnAboutProxyRequirement("add a new observable property through direct assignment. Use 'set' from 'mobx' instead.");
3224 }
3225 // null (intercepted) -> true (success)
3226 return (_getAdm$set_ = getAdm(target).set_(name, value, true)) != null ? _getAdm$set_ : true;
3227 },
3228 deleteProperty: function deleteProperty(target, name) {
3229 var _getAdm$delete_;
3230 {
3231 warnAboutProxyRequirement("delete properties from an observable object. Use 'remove' from 'mobx' instead.");
3232 }
3233 if (!isStringish(name)) {
3234 return false;
3235 }
3236 // null (intercepted) -> true (success)
3237 return (_getAdm$delete_ = getAdm(target).delete_(name, true)) != null ? _getAdm$delete_ : true;
3238 },
3239 defineProperty: function defineProperty(target, name, descriptor) {
3240 var _getAdm$definePropert;
3241 {
3242 warnAboutProxyRequirement("define property on an observable object. Use 'defineProperty' from 'mobx' instead.");
3243 }
3244 // null (intercepted) -> true (success)
3245 return (_getAdm$definePropert = getAdm(target).defineProperty_(name, descriptor)) != null ? _getAdm$definePropert : true;
3246 },
3247 ownKeys: function ownKeys(target) {
3248 if ( globalState.trackingDerivation) {
3249 warnAboutProxyRequirement("iterate keys to detect added / removed properties. Use 'keys' from 'mobx' instead.");
3250 }
3251 return getAdm(target).ownKeys_();
3252 },
3253 preventExtensions: function preventExtensions(target) {
3254 die(13);
3255 }
3256};
3257function asDynamicObservableObject(target, options) {
3258 var _target$$mobx, _target$$mobx$proxy_;
3259 assertProxies();
3260 target = asObservableObject(target, options);
3261 return (_target$$mobx$proxy_ = (_target$$mobx = target[$mobx]).proxy_) != null ? _target$$mobx$proxy_ : _target$$mobx.proxy_ = new Proxy(target, objectProxyTraps);
3262}
3263
3264function hasInterceptors(interceptable) {
3265 return interceptable.interceptors_ !== undefined && interceptable.interceptors_.length > 0;
3266}
3267function registerInterceptor(interceptable, handler) {
3268 var interceptors = interceptable.interceptors_ || (interceptable.interceptors_ = []);
3269 interceptors.push(handler);
3270 return once(function () {
3271 var idx = interceptors.indexOf(handler);
3272 if (idx !== -1) {
3273 interceptors.splice(idx, 1);
3274 }
3275 });
3276}
3277function interceptChange(interceptable, change) {
3278 var prevU = untrackedStart();
3279 try {
3280 // Interceptor can modify the array, copy it to avoid concurrent modification, see #1950
3281 var interceptors = [].concat(interceptable.interceptors_ || []);
3282 for (var i = 0, l = interceptors.length; i < l; i++) {
3283 change = interceptors[i](change);
3284 if (change && !change.type) {
3285 die(14);
3286 }
3287 if (!change) {
3288 break;
3289 }
3290 }
3291 return change;
3292 } finally {
3293 untrackedEnd(prevU);
3294 }
3295}
3296
3297function hasListeners(listenable) {
3298 return listenable.changeListeners_ !== undefined && listenable.changeListeners_.length > 0;
3299}
3300function registerListener(listenable, handler) {
3301 var listeners = listenable.changeListeners_ || (listenable.changeListeners_ = []);
3302 listeners.push(handler);
3303 return once(function () {
3304 var idx = listeners.indexOf(handler);
3305 if (idx !== -1) {
3306 listeners.splice(idx, 1);
3307 }
3308 });
3309}
3310function notifyListeners(listenable, change) {
3311 var prevU = untrackedStart();
3312 var listeners = listenable.changeListeners_;
3313 if (!listeners) {
3314 return;
3315 }
3316 listeners = listeners.slice();
3317 for (var i = 0, l = listeners.length; i < l; i++) {
3318 listeners[i](change);
3319 }
3320 untrackedEnd(prevU);
3321}
3322
3323function makeObservable(target, annotations, options) {
3324 var adm = asObservableObject(target, options)[$mobx];
3325 startBatch();
3326 try {
3327 var _annotations;
3328 if ("development" !== "production" && annotations && target[storedAnnotationsSymbol]) {
3329 die("makeObservable second arg must be nullish when using decorators. Mixing @decorator syntax with annotations is not supported.");
3330 }
3331 // Default to decorators
3332 (_annotations = annotations) != null ? _annotations : annotations = collectStoredAnnotations(target);
3333 // Annotate
3334 ownKeys(annotations).forEach(function (key) {
3335 return adm.make_(key, annotations[key]);
3336 });
3337 } finally {
3338 endBatch();
3339 }
3340 return target;
3341}
3342// proto[keysSymbol] = new Set<PropertyKey>()
3343var keysSymbol = /*#__PURE__*/Symbol("mobx-keys");
3344function makeAutoObservable(target, overrides, options) {
3345 {
3346 if (!isPlainObject(target) && !isPlainObject(Object.getPrototypeOf(target))) {
3347 die("'makeAutoObservable' can only be used for classes that don't have a superclass");
3348 }
3349 if (isObservableObject(target)) {
3350 die("makeAutoObservable can only be used on objects not already made observable");
3351 }
3352 }
3353 // Optimization: avoid visiting protos
3354 // Assumes that annotation.make_/.extend_ works the same for plain objects
3355 if (isPlainObject(target)) {
3356 return extendObservable(target, target, overrides, options);
3357 }
3358 var adm = asObservableObject(target, options)[$mobx];
3359 // Optimization: cache keys on proto
3360 // Assumes makeAutoObservable can be called only once per object and can't be used in subclass
3361 if (!target[keysSymbol]) {
3362 var proto = Object.getPrototypeOf(target);
3363 var keys = new Set([].concat(ownKeys(target), ownKeys(proto)));
3364 keys["delete"]("constructor");
3365 keys["delete"]($mobx);
3366 addHiddenProp(proto, keysSymbol, keys);
3367 }
3368 startBatch();
3369 try {
3370 target[keysSymbol].forEach(function (key) {
3371 return adm.make_(key,
3372 // must pass "undefined" for { key: undefined }
3373 !overrides ? true : key in overrides ? overrides[key] : true);
3374 });
3375 } finally {
3376 endBatch();
3377 }
3378 return target;
3379}
3380
3381var SPLICE = "splice";
3382var UPDATE = "update";
3383var MAX_SPLICE_SIZE = 10000; // See e.g. https://github.com/mobxjs/mobx/issues/859
3384var arrayTraps = {
3385 get: function get(target, name) {
3386 var adm = target[$mobx];
3387 if (name === $mobx) {
3388 return adm;
3389 }
3390 if (name === "length") {
3391 return adm.getArrayLength_();
3392 }
3393 if (typeof name === "string" && !isNaN(name)) {
3394 return adm.get_(parseInt(name));
3395 }
3396 if (hasProp(arrayExtensions, name)) {
3397 return arrayExtensions[name];
3398 }
3399 return target[name];
3400 },
3401 set: function set(target, name, value) {
3402 var adm = target[$mobx];
3403 if (name === "length") {
3404 adm.setArrayLength_(value);
3405 }
3406 if (typeof name === "symbol" || isNaN(name)) {
3407 target[name] = value;
3408 } else {
3409 // numeric string
3410 adm.set_(parseInt(name), value);
3411 }
3412 return true;
3413 },
3414 preventExtensions: function preventExtensions() {
3415 die(15);
3416 }
3417};
3418var ObservableArrayAdministration = /*#__PURE__*/function () {
3419 // this is the prop that gets proxied, so can't replace it!
3420
3421 function ObservableArrayAdministration(name, enhancer, owned_, legacyMode_) {
3422 if (name === void 0) {
3423 name = "ObservableArray@" + getNextId() ;
3424 }
3425 this.owned_ = void 0;
3426 this.legacyMode_ = void 0;
3427 this.atom_ = void 0;
3428 this.values_ = [];
3429 this.interceptors_ = void 0;
3430 this.changeListeners_ = void 0;
3431 this.enhancer_ = void 0;
3432 this.dehancer = void 0;
3433 this.proxy_ = void 0;
3434 this.lastKnownLength_ = 0;
3435 this.owned_ = owned_;
3436 this.legacyMode_ = legacyMode_;
3437 this.atom_ = new Atom(name);
3438 this.enhancer_ = function (newV, oldV) {
3439 return enhancer(newV, oldV, name + "[..]" );
3440 };
3441 }
3442 var _proto = ObservableArrayAdministration.prototype;
3443 _proto.dehanceValue_ = function dehanceValue_(value) {
3444 if (this.dehancer !== undefined) {
3445 return this.dehancer(value);
3446 }
3447 return value;
3448 };
3449 _proto.dehanceValues_ = function dehanceValues_(values) {
3450 if (this.dehancer !== undefined && values.length > 0) {
3451 return values.map(this.dehancer);
3452 }
3453 return values;
3454 };
3455 _proto.intercept_ = function intercept_(handler) {
3456 return registerInterceptor(this, handler);
3457 };
3458 _proto.observe_ = function observe_(listener, fireImmediately) {
3459 if (fireImmediately === void 0) {
3460 fireImmediately = false;
3461 }
3462 if (fireImmediately) {
3463 listener({
3464 observableKind: "array",
3465 object: this.proxy_,
3466 debugObjectName: this.atom_.name_,
3467 type: "splice",
3468 index: 0,
3469 added: this.values_.slice(),
3470 addedCount: this.values_.length,
3471 removed: [],
3472 removedCount: 0
3473 });
3474 }
3475 return registerListener(this, listener);
3476 };
3477 _proto.getArrayLength_ = function getArrayLength_() {
3478 this.atom_.reportObserved();
3479 return this.values_.length;
3480 };
3481 _proto.setArrayLength_ = function setArrayLength_(newLength) {
3482 if (typeof newLength !== "number" || isNaN(newLength) || newLength < 0) {
3483 die("Out of range: " + newLength);
3484 }
3485 var currentLength = this.values_.length;
3486 if (newLength === currentLength) {
3487 return;
3488 } else if (newLength > currentLength) {
3489 var newItems = new Array(newLength - currentLength);
3490 for (var i = 0; i < newLength - currentLength; i++) {
3491 newItems[i] = undefined;
3492 } // No Array.fill everywhere...
3493 this.spliceWithArray_(currentLength, 0, newItems);
3494 } else {
3495 this.spliceWithArray_(newLength, currentLength - newLength);
3496 }
3497 };
3498 _proto.updateArrayLength_ = function updateArrayLength_(oldLength, delta) {
3499 if (oldLength !== this.lastKnownLength_) {
3500 die(16);
3501 }
3502 this.lastKnownLength_ += delta;
3503 if (this.legacyMode_ && delta > 0) {
3504 reserveArrayBuffer(oldLength + delta + 1);
3505 }
3506 };
3507 _proto.spliceWithArray_ = function spliceWithArray_(index, deleteCount, newItems) {
3508 var _this = this;
3509 checkIfStateModificationsAreAllowed(this.atom_);
3510 var length = this.values_.length;
3511 if (index === undefined) {
3512 index = 0;
3513 } else if (index > length) {
3514 index = length;
3515 } else if (index < 0) {
3516 index = Math.max(0, length + index);
3517 }
3518 if (arguments.length === 1) {
3519 deleteCount = length - index;
3520 } else if (deleteCount === undefined || deleteCount === null) {
3521 deleteCount = 0;
3522 } else {
3523 deleteCount = Math.max(0, Math.min(deleteCount, length - index));
3524 }
3525 if (newItems === undefined) {
3526 newItems = EMPTY_ARRAY;
3527 }
3528 if (hasInterceptors(this)) {
3529 var change = interceptChange(this, {
3530 object: this.proxy_,
3531 type: SPLICE,
3532 index: index,
3533 removedCount: deleteCount,
3534 added: newItems
3535 });
3536 if (!change) {
3537 return EMPTY_ARRAY;
3538 }
3539 deleteCount = change.removedCount;
3540 newItems = change.added;
3541 }
3542 newItems = newItems.length === 0 ? newItems : newItems.map(function (v) {
3543 return _this.enhancer_(v, undefined);
3544 });
3545 if (this.legacyMode_ || "development" !== "production") {
3546 var lengthDelta = newItems.length - deleteCount;
3547 this.updateArrayLength_(length, lengthDelta); // checks if internal array wasn't modified
3548 }
3549
3550 var res = this.spliceItemsIntoValues_(index, deleteCount, newItems);
3551 if (deleteCount !== 0 || newItems.length !== 0) {
3552 this.notifyArraySplice_(index, newItems, res);
3553 }
3554 return this.dehanceValues_(res);
3555 };
3556 _proto.spliceItemsIntoValues_ = function spliceItemsIntoValues_(index, deleteCount, newItems) {
3557 if (newItems.length < MAX_SPLICE_SIZE) {
3558 var _this$values_;
3559 return (_this$values_ = this.values_).splice.apply(_this$values_, [index, deleteCount].concat(newItems));
3560 } else {
3561 // The items removed by the splice
3562 var res = this.values_.slice(index, index + deleteCount);
3563 // The items that that should remain at the end of the array
3564 var oldItems = this.values_.slice(index + deleteCount);
3565 // New length is the previous length + addition count - deletion count
3566 this.values_.length += newItems.length - deleteCount;
3567 for (var i = 0; i < newItems.length; i++) {
3568 this.values_[index + i] = newItems[i];
3569 }
3570 for (var _i = 0; _i < oldItems.length; _i++) {
3571 this.values_[index + newItems.length + _i] = oldItems[_i];
3572 }
3573 return res;
3574 }
3575 };
3576 _proto.notifyArrayChildUpdate_ = function notifyArrayChildUpdate_(index, newValue, oldValue) {
3577 var notifySpy = !this.owned_ && isSpyEnabled();
3578 var notify = hasListeners(this);
3579 var change = notify || notifySpy ? {
3580 observableKind: "array",
3581 object: this.proxy_,
3582 type: UPDATE,
3583 debugObjectName: this.atom_.name_,
3584 index: index,
3585 newValue: newValue,
3586 oldValue: oldValue
3587 } : null;
3588 // The reason why this is on right hand side here (and not above), is this way the uglifier will drop it, but it won't
3589 // cause any runtime overhead in development mode without NODE_ENV set, unless spying is enabled
3590 if ( notifySpy) {
3591 spyReportStart(change);
3592 }
3593 this.atom_.reportChanged();
3594 if (notify) {
3595 notifyListeners(this, change);
3596 }
3597 if ( notifySpy) {
3598 spyReportEnd();
3599 }
3600 };
3601 _proto.notifyArraySplice_ = function notifyArraySplice_(index, added, removed) {
3602 var notifySpy = !this.owned_ && isSpyEnabled();
3603 var notify = hasListeners(this);
3604 var change = notify || notifySpy ? {
3605 observableKind: "array",
3606 object: this.proxy_,
3607 debugObjectName: this.atom_.name_,
3608 type: SPLICE,
3609 index: index,
3610 removed: removed,
3611 added: added,
3612 removedCount: removed.length,
3613 addedCount: added.length
3614 } : null;
3615 if ( notifySpy) {
3616 spyReportStart(change);
3617 }
3618 this.atom_.reportChanged();
3619 // conform: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/observe
3620 if (notify) {
3621 notifyListeners(this, change);
3622 }
3623 if ( notifySpy) {
3624 spyReportEnd();
3625 }
3626 };
3627 _proto.get_ = function get_(index) {
3628 if (this.legacyMode_ && index >= this.values_.length) {
3629 console.warn( "[mobx.array] Attempt to read an array index (" + index + ") that is out of bounds (" + this.values_.length + "). Please check length first. Out of bound indices will not be tracked by MobX" );
3630 return undefined;
3631 }
3632 this.atom_.reportObserved();
3633 return this.dehanceValue_(this.values_[index]);
3634 };
3635 _proto.set_ = function set_(index, newValue) {
3636 var values = this.values_;
3637 if (this.legacyMode_ && index > values.length) {
3638 // out of bounds
3639 die(17, index, values.length);
3640 }
3641 if (index < values.length) {
3642 // update at index in range
3643 checkIfStateModificationsAreAllowed(this.atom_);
3644 var oldValue = values[index];
3645 if (hasInterceptors(this)) {
3646 var change = interceptChange(this, {
3647 type: UPDATE,
3648 object: this.proxy_,
3649 index: index,
3650 newValue: newValue
3651 });
3652 if (!change) {
3653 return;
3654 }
3655 newValue = change.newValue;
3656 }
3657 newValue = this.enhancer_(newValue, oldValue);
3658 var changed = newValue !== oldValue;
3659 if (changed) {
3660 values[index] = newValue;
3661 this.notifyArrayChildUpdate_(index, newValue, oldValue);
3662 }
3663 } else {
3664 // For out of bound index, we don't create an actual sparse array,
3665 // but rather fill the holes with undefined (same as setArrayLength_).
3666 // This could be considered a bug.
3667 var newItems = new Array(index + 1 - values.length);
3668 for (var i = 0; i < newItems.length - 1; i++) {
3669 newItems[i] = undefined;
3670 } // No Array.fill everywhere...
3671 newItems[newItems.length - 1] = newValue;
3672 this.spliceWithArray_(values.length, 0, newItems);
3673 }
3674 };
3675 return ObservableArrayAdministration;
3676}();
3677function createObservableArray(initialValues, enhancer, name, owned) {
3678 if (name === void 0) {
3679 name = "ObservableArray@" + getNextId() ;
3680 }
3681 if (owned === void 0) {
3682 owned = false;
3683 }
3684 assertProxies();
3685 var adm = new ObservableArrayAdministration(name, enhancer, owned, false);
3686 addHiddenFinalProp(adm.values_, $mobx, adm);
3687 var proxy = new Proxy(adm.values_, arrayTraps);
3688 adm.proxy_ = proxy;
3689 if (initialValues && initialValues.length) {
3690 var prev = allowStateChangesStart(true);
3691 adm.spliceWithArray_(0, 0, initialValues);
3692 allowStateChangesEnd(prev);
3693 }
3694 return proxy;
3695}
3696// eslint-disable-next-line
3697var arrayExtensions = {
3698 clear: function clear() {
3699 return this.splice(0);
3700 },
3701 replace: function replace(newItems) {
3702 var adm = this[$mobx];
3703 return adm.spliceWithArray_(0, adm.values_.length, newItems);
3704 },
3705 // Used by JSON.stringify
3706 toJSON: function toJSON() {
3707 return this.slice();
3708 },
3709 /*
3710 * functions that do alter the internal structure of the array, (based on lib.es6.d.ts)
3711 * since these functions alter the inner structure of the array, the have side effects.
3712 * Because the have side effects, they should not be used in computed function,
3713 * and for that reason the do not call dependencyState.notifyObserved
3714 */
3715 splice: function splice(index, deleteCount) {
3716 for (var _len = arguments.length, newItems = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
3717 newItems[_key - 2] = arguments[_key];
3718 }
3719 var adm = this[$mobx];
3720 switch (arguments.length) {
3721 case 0:
3722 return [];
3723 case 1:
3724 return adm.spliceWithArray_(index);
3725 case 2:
3726 return adm.spliceWithArray_(index, deleteCount);
3727 }
3728 return adm.spliceWithArray_(index, deleteCount, newItems);
3729 },
3730 spliceWithArray: function spliceWithArray(index, deleteCount, newItems) {
3731 return this[$mobx].spliceWithArray_(index, deleteCount, newItems);
3732 },
3733 push: function push() {
3734 var adm = this[$mobx];
3735 for (var _len2 = arguments.length, items = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
3736 items[_key2] = arguments[_key2];
3737 }
3738 adm.spliceWithArray_(adm.values_.length, 0, items);
3739 return adm.values_.length;
3740 },
3741 pop: function pop() {
3742 return this.splice(Math.max(this[$mobx].values_.length - 1, 0), 1)[0];
3743 },
3744 shift: function shift() {
3745 return this.splice(0, 1)[0];
3746 },
3747 unshift: function unshift() {
3748 var adm = this[$mobx];
3749 for (var _len3 = arguments.length, items = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
3750 items[_key3] = arguments[_key3];
3751 }
3752 adm.spliceWithArray_(0, 0, items);
3753 return adm.values_.length;
3754 },
3755 reverse: function reverse() {
3756 // reverse by default mutates in place before returning the result
3757 // which makes it both a 'derivation' and a 'mutation'.
3758 if (globalState.trackingDerivation) {
3759 die(37, "reverse");
3760 }
3761 this.replace(this.slice().reverse());
3762 return this;
3763 },
3764 sort: function sort() {
3765 // sort by default mutates in place before returning the result
3766 // which goes against all good practices. Let's not change the array in place!
3767 if (globalState.trackingDerivation) {
3768 die(37, "sort");
3769 }
3770 var copy = this.slice();
3771 copy.sort.apply(copy, arguments);
3772 this.replace(copy);
3773 return this;
3774 },
3775 remove: function remove(value) {
3776 var adm = this[$mobx];
3777 var idx = adm.dehanceValues_(adm.values_).indexOf(value);
3778 if (idx > -1) {
3779 this.splice(idx, 1);
3780 return true;
3781 }
3782 return false;
3783 }
3784};
3785/**
3786 * Wrap function from prototype
3787 * Without this, everything works as well, but this works
3788 * faster as everything works on unproxied values
3789 */
3790addArrayExtension("concat", simpleFunc);
3791addArrayExtension("flat", simpleFunc);
3792addArrayExtension("includes", simpleFunc);
3793addArrayExtension("indexOf", simpleFunc);
3794addArrayExtension("join", simpleFunc);
3795addArrayExtension("lastIndexOf", simpleFunc);
3796addArrayExtension("slice", simpleFunc);
3797addArrayExtension("toString", simpleFunc);
3798addArrayExtension("toLocaleString", simpleFunc);
3799// map
3800addArrayExtension("every", mapLikeFunc);
3801addArrayExtension("filter", mapLikeFunc);
3802addArrayExtension("find", mapLikeFunc);
3803addArrayExtension("findIndex", mapLikeFunc);
3804addArrayExtension("flatMap", mapLikeFunc);
3805addArrayExtension("forEach", mapLikeFunc);
3806addArrayExtension("map", mapLikeFunc);
3807addArrayExtension("some", mapLikeFunc);
3808// reduce
3809addArrayExtension("reduce", reduceLikeFunc);
3810addArrayExtension("reduceRight", reduceLikeFunc);
3811function addArrayExtension(funcName, funcFactory) {
3812 if (typeof Array.prototype[funcName] === "function") {
3813 arrayExtensions[funcName] = funcFactory(funcName);
3814 }
3815}
3816// Report and delegate to dehanced array
3817function simpleFunc(funcName) {
3818 return function () {
3819 var adm = this[$mobx];
3820 adm.atom_.reportObserved();
3821 var dehancedValues = adm.dehanceValues_(adm.values_);
3822 return dehancedValues[funcName].apply(dehancedValues, arguments);
3823 };
3824}
3825// Make sure callbacks recieve correct array arg #2326
3826function mapLikeFunc(funcName) {
3827 return function (callback, thisArg) {
3828 var _this2 = this;
3829 var adm = this[$mobx];
3830 adm.atom_.reportObserved();
3831 var dehancedValues = adm.dehanceValues_(adm.values_);
3832 return dehancedValues[funcName](function (element, index) {
3833 return callback.call(thisArg, element, index, _this2);
3834 });
3835 };
3836}
3837// Make sure callbacks recieve correct array arg #2326
3838function reduceLikeFunc(funcName) {
3839 return function () {
3840 var _this3 = this;
3841 var adm = this[$mobx];
3842 adm.atom_.reportObserved();
3843 var dehancedValues = adm.dehanceValues_(adm.values_);
3844 // #2432 - reduce behavior depends on arguments.length
3845 var callback = arguments[0];
3846 arguments[0] = function (accumulator, currentValue, index) {
3847 return callback(accumulator, currentValue, index, _this3);
3848 };
3849 return dehancedValues[funcName].apply(dehancedValues, arguments);
3850 };
3851}
3852var isObservableArrayAdministration = /*#__PURE__*/createInstanceofPredicate("ObservableArrayAdministration", ObservableArrayAdministration);
3853function isObservableArray(thing) {
3854 return isObject(thing) && isObservableArrayAdministration(thing[$mobx]);
3855}
3856
3857var _Symbol$iterator, _Symbol$toStringTag;
3858var ObservableMapMarker = {};
3859var ADD = "add";
3860var DELETE = "delete";
3861// just extend Map? See also https://gist.github.com/nestharus/13b4d74f2ef4a2f4357dbd3fc23c1e54
3862// But: https://github.com/mobxjs/mobx/issues/1556
3863_Symbol$iterator = Symbol.iterator;
3864_Symbol$toStringTag = Symbol.toStringTag;
3865var ObservableMap = /*#__PURE__*/function () {
3866 // hasMap, not hashMap >-).
3867
3868 function ObservableMap(initialData, enhancer_, name_) {
3869 var _this = this;
3870 if (enhancer_ === void 0) {
3871 enhancer_ = deepEnhancer;
3872 }
3873 if (name_ === void 0) {
3874 name_ = "ObservableMap@" + getNextId() ;
3875 }
3876 this.enhancer_ = void 0;
3877 this.name_ = void 0;
3878 this[$mobx] = ObservableMapMarker;
3879 this.data_ = void 0;
3880 this.hasMap_ = void 0;
3881 this.keysAtom_ = void 0;
3882 this.interceptors_ = void 0;
3883 this.changeListeners_ = void 0;
3884 this.dehancer = void 0;
3885 this.enhancer_ = enhancer_;
3886 this.name_ = name_;
3887 if (!isFunction(Map)) {
3888 die(18);
3889 }
3890 this.keysAtom_ = createAtom( this.name_ + ".keys()" );
3891 this.data_ = new Map();
3892 this.hasMap_ = new Map();
3893 allowStateChanges(true, function () {
3894 _this.merge(initialData);
3895 });
3896 }
3897 var _proto = ObservableMap.prototype;
3898 _proto.has_ = function has_(key) {
3899 return this.data_.has(key);
3900 };
3901 _proto.has = function has(key) {
3902 var _this2 = this;
3903 if (!globalState.trackingDerivation) {
3904 return this.has_(key);
3905 }
3906 var entry = this.hasMap_.get(key);
3907 if (!entry) {
3908 var newEntry = entry = new ObservableValue(this.has_(key), referenceEnhancer, this.name_ + "." + stringifyKey(key) + "?" , false);
3909 this.hasMap_.set(key, newEntry);
3910 onBecomeUnobserved(newEntry, function () {
3911 return _this2.hasMap_["delete"](key);
3912 });
3913 }
3914 return entry.get();
3915 };
3916 _proto.set = function set(key, value) {
3917 var hasKey = this.has_(key);
3918 if (hasInterceptors(this)) {
3919 var change = interceptChange(this, {
3920 type: hasKey ? UPDATE : ADD,
3921 object: this,
3922 newValue: value,
3923 name: key
3924 });
3925 if (!change) {
3926 return this;
3927 }
3928 value = change.newValue;
3929 }
3930 if (hasKey) {
3931 this.updateValue_(key, value);
3932 } else {
3933 this.addValue_(key, value);
3934 }
3935 return this;
3936 };
3937 _proto["delete"] = function _delete(key) {
3938 var _this3 = this;
3939 checkIfStateModificationsAreAllowed(this.keysAtom_);
3940 if (hasInterceptors(this)) {
3941 var change = interceptChange(this, {
3942 type: DELETE,
3943 object: this,
3944 name: key
3945 });
3946 if (!change) {
3947 return false;
3948 }
3949 }
3950 if (this.has_(key)) {
3951 var notifySpy = isSpyEnabled();
3952 var notify = hasListeners(this);
3953 var _change = notify || notifySpy ? {
3954 observableKind: "map",
3955 debugObjectName: this.name_,
3956 type: DELETE,
3957 object: this,
3958 oldValue: this.data_.get(key).value_,
3959 name: key
3960 } : null;
3961 if ( notifySpy) {
3962 spyReportStart(_change);
3963 } // TODO fix type
3964 transaction(function () {
3965 var _this3$hasMap_$get;
3966 _this3.keysAtom_.reportChanged();
3967 (_this3$hasMap_$get = _this3.hasMap_.get(key)) == null ? void 0 : _this3$hasMap_$get.setNewValue_(false);
3968 var observable = _this3.data_.get(key);
3969 observable.setNewValue_(undefined);
3970 _this3.data_["delete"](key);
3971 });
3972 if (notify) {
3973 notifyListeners(this, _change);
3974 }
3975 if ( notifySpy) {
3976 spyReportEnd();
3977 }
3978 return true;
3979 }
3980 return false;
3981 };
3982 _proto.updateValue_ = function updateValue_(key, newValue) {
3983 var observable = this.data_.get(key);
3984 newValue = observable.prepareNewValue_(newValue);
3985 if (newValue !== globalState.UNCHANGED) {
3986 var notifySpy = isSpyEnabled();
3987 var notify = hasListeners(this);
3988 var change = notify || notifySpy ? {
3989 observableKind: "map",
3990 debugObjectName: this.name_,
3991 type: UPDATE,
3992 object: this,
3993 oldValue: observable.value_,
3994 name: key,
3995 newValue: newValue
3996 } : null;
3997 if ( notifySpy) {
3998 spyReportStart(change);
3999 } // TODO fix type
4000 observable.setNewValue_(newValue);
4001 if (notify) {
4002 notifyListeners(this, change);
4003 }
4004 if ( notifySpy) {
4005 spyReportEnd();
4006 }
4007 }
4008 };
4009 _proto.addValue_ = function addValue_(key, newValue) {
4010 var _this4 = this;
4011 checkIfStateModificationsAreAllowed(this.keysAtom_);
4012 transaction(function () {
4013 var _this4$hasMap_$get;
4014 var observable = new ObservableValue(newValue, _this4.enhancer_, _this4.name_ + "." + stringifyKey(key) , false);
4015 _this4.data_.set(key, observable);
4016 newValue = observable.value_; // value might have been changed
4017 (_this4$hasMap_$get = _this4.hasMap_.get(key)) == null ? void 0 : _this4$hasMap_$get.setNewValue_(true);
4018 _this4.keysAtom_.reportChanged();
4019 });
4020 var notifySpy = isSpyEnabled();
4021 var notify = hasListeners(this);
4022 var change = notify || notifySpy ? {
4023 observableKind: "map",
4024 debugObjectName: this.name_,
4025 type: ADD,
4026 object: this,
4027 name: key,
4028 newValue: newValue
4029 } : null;
4030 if ( notifySpy) {
4031 spyReportStart(change);
4032 } // TODO fix type
4033 if (notify) {
4034 notifyListeners(this, change);
4035 }
4036 if ( notifySpy) {
4037 spyReportEnd();
4038 }
4039 };
4040 _proto.get = function get(key) {
4041 if (this.has(key)) {
4042 return this.dehanceValue_(this.data_.get(key).get());
4043 }
4044 return this.dehanceValue_(undefined);
4045 };
4046 _proto.dehanceValue_ = function dehanceValue_(value) {
4047 if (this.dehancer !== undefined) {
4048 return this.dehancer(value);
4049 }
4050 return value;
4051 };
4052 _proto.keys = function keys() {
4053 this.keysAtom_.reportObserved();
4054 return this.data_.keys();
4055 };
4056 _proto.values = function values() {
4057 var self = this;
4058 var keys = this.keys();
4059 return makeIterable({
4060 next: function next() {
4061 var _keys$next = keys.next(),
4062 done = _keys$next.done,
4063 value = _keys$next.value;
4064 return {
4065 done: done,
4066 value: done ? undefined : self.get(value)
4067 };
4068 }
4069 });
4070 };
4071 _proto.entries = function entries() {
4072 var self = this;
4073 var keys = this.keys();
4074 return makeIterable({
4075 next: function next() {
4076 var _keys$next2 = keys.next(),
4077 done = _keys$next2.done,
4078 value = _keys$next2.value;
4079 return {
4080 done: done,
4081 value: done ? undefined : [value, self.get(value)]
4082 };
4083 }
4084 });
4085 };
4086 _proto[_Symbol$iterator] = function () {
4087 return this.entries();
4088 };
4089 _proto.forEach = function forEach(callback, thisArg) {
4090 for (var _iterator = _createForOfIteratorHelperLoose(this), _step; !(_step = _iterator()).done;) {
4091 var _step$value = _step.value,
4092 key = _step$value[0],
4093 value = _step$value[1];
4094 callback.call(thisArg, value, key, this);
4095 }
4096 }
4097 /** Merge another object into this object, returns this. */;
4098 _proto.merge = function merge(other) {
4099 var _this5 = this;
4100 if (isObservableMap(other)) {
4101 other = new Map(other);
4102 }
4103 transaction(function () {
4104 if (isPlainObject(other)) {
4105 getPlainObjectKeys(other).forEach(function (key) {
4106 return _this5.set(key, other[key]);
4107 });
4108 } else if (Array.isArray(other)) {
4109 other.forEach(function (_ref) {
4110 var key = _ref[0],
4111 value = _ref[1];
4112 return _this5.set(key, value);
4113 });
4114 } else if (isES6Map(other)) {
4115 if (other.constructor !== Map) {
4116 die(19, other);
4117 }
4118 other.forEach(function (value, key) {
4119 return _this5.set(key, value);
4120 });
4121 } else if (other !== null && other !== undefined) {
4122 die(20, other);
4123 }
4124 });
4125 return this;
4126 };
4127 _proto.clear = function clear() {
4128 var _this6 = this;
4129 transaction(function () {
4130 untracked(function () {
4131 for (var _iterator2 = _createForOfIteratorHelperLoose(_this6.keys()), _step2; !(_step2 = _iterator2()).done;) {
4132 var key = _step2.value;
4133 _this6["delete"](key);
4134 }
4135 });
4136 });
4137 };
4138 _proto.replace = function replace(values) {
4139 var _this7 = this;
4140 // Implementation requirements:
4141 // - respect ordering of replacement map
4142 // - allow interceptors to run and potentially prevent individual operations
4143 // - don't recreate observables that already exist in original map (so we don't destroy existing subscriptions)
4144 // - don't _keysAtom.reportChanged if the keys of resulting map are indentical (order matters!)
4145 // - note that result map may differ from replacement map due to the interceptors
4146 transaction(function () {
4147 // Convert to map so we can do quick key lookups
4148 var replacementMap = convertToMap(values);
4149 var orderedData = new Map();
4150 // Used for optimization
4151 var keysReportChangedCalled = false;
4152 // Delete keys that don't exist in replacement map
4153 // if the key deletion is prevented by interceptor
4154 // add entry at the beginning of the result map
4155 for (var _iterator3 = _createForOfIteratorHelperLoose(_this7.data_.keys()), _step3; !(_step3 = _iterator3()).done;) {
4156 var key = _step3.value;
4157 // Concurrently iterating/deleting keys
4158 // iterator should handle this correctly
4159 if (!replacementMap.has(key)) {
4160 var deleted = _this7["delete"](key);
4161 // Was the key removed?
4162 if (deleted) {
4163 // _keysAtom.reportChanged() was already called
4164 keysReportChangedCalled = true;
4165 } else {
4166 // Delete prevented by interceptor
4167 var value = _this7.data_.get(key);
4168 orderedData.set(key, value);
4169 }
4170 }
4171 }
4172 // Merge entries
4173 for (var _iterator4 = _createForOfIteratorHelperLoose(replacementMap.entries()), _step4; !(_step4 = _iterator4()).done;) {
4174 var _step4$value = _step4.value,
4175 _key = _step4$value[0],
4176 _value = _step4$value[1];
4177 // We will want to know whether a new key is added
4178 var keyExisted = _this7.data_.has(_key);
4179 // Add or update value
4180 _this7.set(_key, _value);
4181 // The addition could have been prevent by interceptor
4182 if (_this7.data_.has(_key)) {
4183 // The update could have been prevented by interceptor
4184 // and also we want to preserve existing values
4185 // so use value from _data map (instead of replacement map)
4186 var _value2 = _this7.data_.get(_key);
4187 orderedData.set(_key, _value2);
4188 // Was a new key added?
4189 if (!keyExisted) {
4190 // _keysAtom.reportChanged() was already called
4191 keysReportChangedCalled = true;
4192 }
4193 }
4194 }
4195 // Check for possible key order change
4196 if (!keysReportChangedCalled) {
4197 if (_this7.data_.size !== orderedData.size) {
4198 // If size differs, keys are definitely modified
4199 _this7.keysAtom_.reportChanged();
4200 } else {
4201 var iter1 = _this7.data_.keys();
4202 var iter2 = orderedData.keys();
4203 var next1 = iter1.next();
4204 var next2 = iter2.next();
4205 while (!next1.done) {
4206 if (next1.value !== next2.value) {
4207 _this7.keysAtom_.reportChanged();
4208 break;
4209 }
4210 next1 = iter1.next();
4211 next2 = iter2.next();
4212 }
4213 }
4214 }
4215 // Use correctly ordered map
4216 _this7.data_ = orderedData;
4217 });
4218 return this;
4219 };
4220 _proto.toString = function toString() {
4221 return "[object ObservableMap]";
4222 };
4223 _proto.toJSON = function toJSON() {
4224 return Array.from(this);
4225 };
4226 /**
4227 * Observes this object. Triggers for the events 'add', 'update' and 'delete'.
4228 * See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/observe
4229 * for callback details
4230 */
4231 _proto.observe_ = function observe_(listener, fireImmediately) {
4232 if ( fireImmediately === true) {
4233 die("`observe` doesn't support fireImmediately=true in combination with maps.");
4234 }
4235 return registerListener(this, listener);
4236 };
4237 _proto.intercept_ = function intercept_(handler) {
4238 return registerInterceptor(this, handler);
4239 };
4240 _createClass(ObservableMap, [{
4241 key: "size",
4242 get: function get() {
4243 this.keysAtom_.reportObserved();
4244 return this.data_.size;
4245 }
4246 }, {
4247 key: _Symbol$toStringTag,
4248 get: function get() {
4249 return "Map";
4250 }
4251 }]);
4252 return ObservableMap;
4253}();
4254// eslint-disable-next-line
4255var isObservableMap = /*#__PURE__*/createInstanceofPredicate("ObservableMap", ObservableMap);
4256function convertToMap(dataStructure) {
4257 if (isES6Map(dataStructure) || isObservableMap(dataStructure)) {
4258 return dataStructure;
4259 } else if (Array.isArray(dataStructure)) {
4260 return new Map(dataStructure);
4261 } else if (isPlainObject(dataStructure)) {
4262 var map = new Map();
4263 for (var key in dataStructure) {
4264 map.set(key, dataStructure[key]);
4265 }
4266 return map;
4267 } else {
4268 return die(21, dataStructure);
4269 }
4270}
4271
4272var _Symbol$iterator$1, _Symbol$toStringTag$1;
4273var ObservableSetMarker = {};
4274_Symbol$iterator$1 = Symbol.iterator;
4275_Symbol$toStringTag$1 = Symbol.toStringTag;
4276var ObservableSet = /*#__PURE__*/function () {
4277 function ObservableSet(initialData, enhancer, name_) {
4278 if (enhancer === void 0) {
4279 enhancer = deepEnhancer;
4280 }
4281 if (name_ === void 0) {
4282 name_ = "ObservableSet@" + getNextId() ;
4283 }
4284 this.name_ = void 0;
4285 this[$mobx] = ObservableSetMarker;
4286 this.data_ = new Set();
4287 this.atom_ = void 0;
4288 this.changeListeners_ = void 0;
4289 this.interceptors_ = void 0;
4290 this.dehancer = void 0;
4291 this.enhancer_ = void 0;
4292 this.name_ = name_;
4293 if (!isFunction(Set)) {
4294 die(22);
4295 }
4296 this.atom_ = createAtom(this.name_);
4297 this.enhancer_ = function (newV, oldV) {
4298 return enhancer(newV, oldV, name_);
4299 };
4300 if (initialData) {
4301 this.replace(initialData);
4302 }
4303 }
4304 var _proto = ObservableSet.prototype;
4305 _proto.dehanceValue_ = function dehanceValue_(value) {
4306 if (this.dehancer !== undefined) {
4307 return this.dehancer(value);
4308 }
4309 return value;
4310 };
4311 _proto.clear = function clear() {
4312 var _this = this;
4313 transaction(function () {
4314 untracked(function () {
4315 for (var _iterator = _createForOfIteratorHelperLoose(_this.data_.values()), _step; !(_step = _iterator()).done;) {
4316 var value = _step.value;
4317 _this["delete"](value);
4318 }
4319 });
4320 });
4321 };
4322 _proto.forEach = function forEach(callbackFn, thisArg) {
4323 for (var _iterator2 = _createForOfIteratorHelperLoose(this), _step2; !(_step2 = _iterator2()).done;) {
4324 var value = _step2.value;
4325 callbackFn.call(thisArg, value, value, this);
4326 }
4327 };
4328 _proto.add = function add(value) {
4329 var _this2 = this;
4330 checkIfStateModificationsAreAllowed(this.atom_);
4331 if (hasInterceptors(this)) {
4332 var change = interceptChange(this, {
4333 type: ADD,
4334 object: this,
4335 newValue: value
4336 });
4337 if (!change) {
4338 return this;
4339 }
4340 // ideally, value = change.value would be done here, so that values can be
4341 // changed by interceptor. Same applies for other Set and Map api's.
4342 }
4343
4344 if (!this.has(value)) {
4345 transaction(function () {
4346 _this2.data_.add(_this2.enhancer_(value, undefined));
4347 _this2.atom_.reportChanged();
4348 });
4349 var notifySpy = isSpyEnabled();
4350 var notify = hasListeners(this);
4351 var _change = notify || notifySpy ? {
4352 observableKind: "set",
4353 debugObjectName: this.name_,
4354 type: ADD,
4355 object: this,
4356 newValue: value
4357 } : null;
4358 if (notifySpy && "development" !== "production") {
4359 spyReportStart(_change);
4360 }
4361 if (notify) {
4362 notifyListeners(this, _change);
4363 }
4364 if (notifySpy && "development" !== "production") {
4365 spyReportEnd();
4366 }
4367 }
4368 return this;
4369 };
4370 _proto["delete"] = function _delete(value) {
4371 var _this3 = this;
4372 if (hasInterceptors(this)) {
4373 var change = interceptChange(this, {
4374 type: DELETE,
4375 object: this,
4376 oldValue: value
4377 });
4378 if (!change) {
4379 return false;
4380 }
4381 }
4382 if (this.has(value)) {
4383 var notifySpy = isSpyEnabled();
4384 var notify = hasListeners(this);
4385 var _change2 = notify || notifySpy ? {
4386 observableKind: "set",
4387 debugObjectName: this.name_,
4388 type: DELETE,
4389 object: this,
4390 oldValue: value
4391 } : null;
4392 if (notifySpy && "development" !== "production") {
4393 spyReportStart(_change2);
4394 }
4395 transaction(function () {
4396 _this3.atom_.reportChanged();
4397 _this3.data_["delete"](value);
4398 });
4399 if (notify) {
4400 notifyListeners(this, _change2);
4401 }
4402 if (notifySpy && "development" !== "production") {
4403 spyReportEnd();
4404 }
4405 return true;
4406 }
4407 return false;
4408 };
4409 _proto.has = function has(value) {
4410 this.atom_.reportObserved();
4411 return this.data_.has(this.dehanceValue_(value));
4412 };
4413 _proto.entries = function entries() {
4414 var nextIndex = 0;
4415 var keys = Array.from(this.keys());
4416 var values = Array.from(this.values());
4417 return makeIterable({
4418 next: function next() {
4419 var index = nextIndex;
4420 nextIndex += 1;
4421 return index < values.length ? {
4422 value: [keys[index], values[index]],
4423 done: false
4424 } : {
4425 done: true
4426 };
4427 }
4428 });
4429 };
4430 _proto.keys = function keys() {
4431 return this.values();
4432 };
4433 _proto.values = function values() {
4434 this.atom_.reportObserved();
4435 var self = this;
4436 var nextIndex = 0;
4437 var observableValues = Array.from(this.data_.values());
4438 return makeIterable({
4439 next: function next() {
4440 return nextIndex < observableValues.length ? {
4441 value: self.dehanceValue_(observableValues[nextIndex++]),
4442 done: false
4443 } : {
4444 done: true
4445 };
4446 }
4447 });
4448 };
4449 _proto.replace = function replace(other) {
4450 var _this4 = this;
4451 if (isObservableSet(other)) {
4452 other = new Set(other);
4453 }
4454 transaction(function () {
4455 if (Array.isArray(other)) {
4456 _this4.clear();
4457 other.forEach(function (value) {
4458 return _this4.add(value);
4459 });
4460 } else if (isES6Set(other)) {
4461 _this4.clear();
4462 other.forEach(function (value) {
4463 return _this4.add(value);
4464 });
4465 } else if (other !== null && other !== undefined) {
4466 die("Cannot initialize set from " + other);
4467 }
4468 });
4469 return this;
4470 };
4471 _proto.observe_ = function observe_(listener, fireImmediately) {
4472 // ... 'fireImmediately' could also be true?
4473 if ( fireImmediately === true) {
4474 die("`observe` doesn't support fireImmediately=true in combination with sets.");
4475 }
4476 return registerListener(this, listener);
4477 };
4478 _proto.intercept_ = function intercept_(handler) {
4479 return registerInterceptor(this, handler);
4480 };
4481 _proto.toJSON = function toJSON() {
4482 return Array.from(this);
4483 };
4484 _proto.toString = function toString() {
4485 return "[object ObservableSet]";
4486 };
4487 _proto[_Symbol$iterator$1] = function () {
4488 return this.values();
4489 };
4490 _createClass(ObservableSet, [{
4491 key: "size",
4492 get: function get() {
4493 this.atom_.reportObserved();
4494 return this.data_.size;
4495 }
4496 }, {
4497 key: _Symbol$toStringTag$1,
4498 get: function get() {
4499 return "Set";
4500 }
4501 }]);
4502 return ObservableSet;
4503}();
4504// eslint-disable-next-line
4505var isObservableSet = /*#__PURE__*/createInstanceofPredicate("ObservableSet", ObservableSet);
4506
4507var descriptorCache = /*#__PURE__*/Object.create(null);
4508var REMOVE = "remove";
4509var ObservableObjectAdministration = /*#__PURE__*/function () {
4510 function ObservableObjectAdministration(target_, values_, name_,
4511 // Used anytime annotation is not explicitely provided
4512 defaultAnnotation_) {
4513 if (values_ === void 0) {
4514 values_ = new Map();
4515 }
4516 if (defaultAnnotation_ === void 0) {
4517 defaultAnnotation_ = autoAnnotation;
4518 }
4519 this.target_ = void 0;
4520 this.values_ = void 0;
4521 this.name_ = void 0;
4522 this.defaultAnnotation_ = void 0;
4523 this.keysAtom_ = void 0;
4524 this.changeListeners_ = void 0;
4525 this.interceptors_ = void 0;
4526 this.proxy_ = void 0;
4527 this.isPlainObject_ = void 0;
4528 this.appliedAnnotations_ = void 0;
4529 this.pendingKeys_ = void 0;
4530 this.target_ = target_;
4531 this.values_ = values_;
4532 this.name_ = name_;
4533 this.defaultAnnotation_ = defaultAnnotation_;
4534 this.keysAtom_ = new Atom( this.name_ + ".keys" );
4535 // Optimization: we use this frequently
4536 this.isPlainObject_ = isPlainObject(this.target_);
4537 if ( !isAnnotation(this.defaultAnnotation_)) {
4538 die("defaultAnnotation must be valid annotation");
4539 }
4540 {
4541 // Prepare structure for tracking which fields were already annotated
4542 this.appliedAnnotations_ = {};
4543 }
4544 }
4545 var _proto = ObservableObjectAdministration.prototype;
4546 _proto.getObservablePropValue_ = function getObservablePropValue_(key) {
4547 return this.values_.get(key).get();
4548 };
4549 _proto.setObservablePropValue_ = function setObservablePropValue_(key, newValue) {
4550 var observable = this.values_.get(key);
4551 if (observable instanceof ComputedValue) {
4552 observable.set(newValue);
4553 return true;
4554 }
4555 // intercept
4556 if (hasInterceptors(this)) {
4557 var change = interceptChange(this, {
4558 type: UPDATE,
4559 object: this.proxy_ || this.target_,
4560 name: key,
4561 newValue: newValue
4562 });
4563 if (!change) {
4564 return null;
4565 }
4566 newValue = change.newValue;
4567 }
4568 newValue = observable.prepareNewValue_(newValue);
4569 // notify spy & observers
4570 if (newValue !== globalState.UNCHANGED) {
4571 var notify = hasListeners(this);
4572 var notifySpy = isSpyEnabled();
4573 var _change = notify || notifySpy ? {
4574 type: UPDATE,
4575 observableKind: "object",
4576 debugObjectName: this.name_,
4577 object: this.proxy_ || this.target_,
4578 oldValue: observable.value_,
4579 name: key,
4580 newValue: newValue
4581 } : null;
4582 if ( notifySpy) {
4583 spyReportStart(_change);
4584 }
4585 observable.setNewValue_(newValue);
4586 if (notify) {
4587 notifyListeners(this, _change);
4588 }
4589 if ( notifySpy) {
4590 spyReportEnd();
4591 }
4592 }
4593 return true;
4594 };
4595 _proto.get_ = function get_(key) {
4596 if (globalState.trackingDerivation && !hasProp(this.target_, key)) {
4597 // Key doesn't exist yet, subscribe for it in case it's added later
4598 this.has_(key);
4599 }
4600 return this.target_[key];
4601 }
4602 /**
4603 * @param {PropertyKey} key
4604 * @param {any} value
4605 * @param {Annotation|boolean} annotation true - use default annotation, false - copy as is
4606 * @param {boolean} proxyTrap whether it's called from proxy trap
4607 * @returns {boolean|null} true on success, false on failure (proxyTrap + non-configurable), null when cancelled by interceptor
4608 */;
4609 _proto.set_ = function set_(key, value, proxyTrap) {
4610 if (proxyTrap === void 0) {
4611 proxyTrap = false;
4612 }
4613 // Don't use .has(key) - we care about own
4614 if (hasProp(this.target_, key)) {
4615 // Existing prop
4616 if (this.values_.has(key)) {
4617 // Observable (can be intercepted)
4618 return this.setObservablePropValue_(key, value);
4619 } else if (proxyTrap) {
4620 // Non-observable - proxy
4621 return Reflect.set(this.target_, key, value);
4622 } else {
4623 // Non-observable
4624 this.target_[key] = value;
4625 return true;
4626 }
4627 } else {
4628 // New prop
4629 return this.extend_(key, {
4630 value: value,
4631 enumerable: true,
4632 writable: true,
4633 configurable: true
4634 }, this.defaultAnnotation_, proxyTrap);
4635 }
4636 }
4637 // Trap for "in"
4638 ;
4639 _proto.has_ = function has_(key) {
4640 if (!globalState.trackingDerivation) {
4641 // Skip key subscription outside derivation
4642 return key in this.target_;
4643 }
4644 this.pendingKeys_ || (this.pendingKeys_ = new Map());
4645 var entry = this.pendingKeys_.get(key);
4646 if (!entry) {
4647 entry = new ObservableValue(key in this.target_, referenceEnhancer, this.name_ + "." + stringifyKey(key) + "?" , false);
4648 this.pendingKeys_.set(key, entry);
4649 }
4650 return entry.get();
4651 }
4652 /**
4653 * @param {PropertyKey} key
4654 * @param {Annotation|boolean} annotation true - use default annotation, false - ignore prop
4655 */;
4656 _proto.make_ = function make_(key, annotation) {
4657 if (annotation === true) {
4658 annotation = this.defaultAnnotation_;
4659 }
4660 if (annotation === false) {
4661 return;
4662 }
4663 assertAnnotable(this, annotation, key);
4664 if (!(key in this.target_)) {
4665 var _this$target_$storedA;
4666 // Throw on missing key, except for decorators:
4667 // Decorator annotations are collected from whole prototype chain.
4668 // When called from super() some props may not exist yet.
4669 // However we don't have to worry about missing prop,
4670 // because the decorator must have been applied to something.
4671 if ((_this$target_$storedA = this.target_[storedAnnotationsSymbol]) != null && _this$target_$storedA[key]) {
4672 return; // will be annotated by subclass constructor
4673 } else {
4674 die(1, annotation.annotationType_, this.name_ + "." + key.toString());
4675 }
4676 }
4677 var source = this.target_;
4678 while (source && source !== objectPrototype) {
4679 var descriptor = getDescriptor(source, key);
4680 if (descriptor) {
4681 var outcome = annotation.make_(this, key, descriptor, source);
4682 if (outcome === 0 /* Cancel */) {
4683 return;
4684 }
4685 if (outcome === 1 /* Break */) {
4686 break;
4687 }
4688 }
4689 source = Object.getPrototypeOf(source);
4690 }
4691 recordAnnotationApplied(this, annotation, key);
4692 }
4693 /**
4694 * @param {PropertyKey} key
4695 * @param {PropertyDescriptor} descriptor
4696 * @param {Annotation|boolean} annotation true - use default annotation, false - copy as is
4697 * @param {boolean} proxyTrap whether it's called from proxy trap
4698 * @returns {boolean|null} true on success, false on failure (proxyTrap + non-configurable), null when cancelled by interceptor
4699 */;
4700 _proto.extend_ = function extend_(key, descriptor, annotation, proxyTrap) {
4701 if (proxyTrap === void 0) {
4702 proxyTrap = false;
4703 }
4704 if (annotation === true) {
4705 annotation = this.defaultAnnotation_;
4706 }
4707 if (annotation === false) {
4708 return this.defineProperty_(key, descriptor, proxyTrap);
4709 }
4710 assertAnnotable(this, annotation, key);
4711 var outcome = annotation.extend_(this, key, descriptor, proxyTrap);
4712 if (outcome) {
4713 recordAnnotationApplied(this, annotation, key);
4714 }
4715 return outcome;
4716 }
4717 /**
4718 * @param {PropertyKey} key
4719 * @param {PropertyDescriptor} descriptor
4720 * @param {boolean} proxyTrap whether it's called from proxy trap
4721 * @returns {boolean|null} true on success, false on failure (proxyTrap + non-configurable), null when cancelled by interceptor
4722 */;
4723 _proto.defineProperty_ = function defineProperty_(key, descriptor, proxyTrap) {
4724 if (proxyTrap === void 0) {
4725 proxyTrap = false;
4726 }
4727 try {
4728 startBatch();
4729 // Delete
4730 var deleteOutcome = this.delete_(key);
4731 if (!deleteOutcome) {
4732 // Failure or intercepted
4733 return deleteOutcome;
4734 }
4735 // ADD interceptor
4736 if (hasInterceptors(this)) {
4737 var change = interceptChange(this, {
4738 object: this.proxy_ || this.target_,
4739 name: key,
4740 type: ADD,
4741 newValue: descriptor.value
4742 });
4743 if (!change) {
4744 return null;
4745 }
4746 var newValue = change.newValue;
4747 if (descriptor.value !== newValue) {
4748 descriptor = _extends({}, descriptor, {
4749 value: newValue
4750 });
4751 }
4752 }
4753 // Define
4754 if (proxyTrap) {
4755 if (!Reflect.defineProperty(this.target_, key, descriptor)) {
4756 return false;
4757 }
4758 } else {
4759 defineProperty(this.target_, key, descriptor);
4760 }
4761 // Notify
4762 this.notifyPropertyAddition_(key, descriptor.value);
4763 } finally {
4764 endBatch();
4765 }
4766 return true;
4767 }
4768 // If original descriptor becomes relevant, move this to annotation directly
4769 ;
4770 _proto.defineObservableProperty_ = function defineObservableProperty_(key, value, enhancer, proxyTrap) {
4771 if (proxyTrap === void 0) {
4772 proxyTrap = false;
4773 }
4774 try {
4775 startBatch();
4776 // Delete
4777 var deleteOutcome = this.delete_(key);
4778 if (!deleteOutcome) {
4779 // Failure or intercepted
4780 return deleteOutcome;
4781 }
4782 // ADD interceptor
4783 if (hasInterceptors(this)) {
4784 var change = interceptChange(this, {
4785 object: this.proxy_ || this.target_,
4786 name: key,
4787 type: ADD,
4788 newValue: value
4789 });
4790 if (!change) {
4791 return null;
4792 }
4793 value = change.newValue;
4794 }
4795 var cachedDescriptor = getCachedObservablePropDescriptor(key);
4796 var descriptor = {
4797 configurable: globalState.safeDescriptors ? this.isPlainObject_ : true,
4798 enumerable: true,
4799 get: cachedDescriptor.get,
4800 set: cachedDescriptor.set
4801 };
4802 // Define
4803 if (proxyTrap) {
4804 if (!Reflect.defineProperty(this.target_, key, descriptor)) {
4805 return false;
4806 }
4807 } else {
4808 defineProperty(this.target_, key, descriptor);
4809 }
4810 var observable = new ObservableValue(value, enhancer, "development" !== "production" ? this.name_ + "." + key.toString() : "ObservableObject.key", false);
4811 this.values_.set(key, observable);
4812 // Notify (value possibly changed by ObservableValue)
4813 this.notifyPropertyAddition_(key, observable.value_);
4814 } finally {
4815 endBatch();
4816 }
4817 return true;
4818 }
4819 // If original descriptor becomes relevant, move this to annotation directly
4820 ;
4821 _proto.defineComputedProperty_ = function defineComputedProperty_(key, options, proxyTrap) {
4822 if (proxyTrap === void 0) {
4823 proxyTrap = false;
4824 }
4825 try {
4826 startBatch();
4827 // Delete
4828 var deleteOutcome = this.delete_(key);
4829 if (!deleteOutcome) {
4830 // Failure or intercepted
4831 return deleteOutcome;
4832 }
4833 // ADD interceptor
4834 if (hasInterceptors(this)) {
4835 var change = interceptChange(this, {
4836 object: this.proxy_ || this.target_,
4837 name: key,
4838 type: ADD,
4839 newValue: undefined
4840 });
4841 if (!change) {
4842 return null;
4843 }
4844 }
4845 options.name || (options.name = "development" !== "production" ? this.name_ + "." + key.toString() : "ObservableObject.key");
4846 options.context = this.proxy_ || this.target_;
4847 var cachedDescriptor = getCachedObservablePropDescriptor(key);
4848 var descriptor = {
4849 configurable: globalState.safeDescriptors ? this.isPlainObject_ : true,
4850 enumerable: false,
4851 get: cachedDescriptor.get,
4852 set: cachedDescriptor.set
4853 };
4854 // Define
4855 if (proxyTrap) {
4856 if (!Reflect.defineProperty(this.target_, key, descriptor)) {
4857 return false;
4858 }
4859 } else {
4860 defineProperty(this.target_, key, descriptor);
4861 }
4862 this.values_.set(key, new ComputedValue(options));
4863 // Notify
4864 this.notifyPropertyAddition_(key, undefined);
4865 } finally {
4866 endBatch();
4867 }
4868 return true;
4869 }
4870 /**
4871 * @param {PropertyKey} key
4872 * @param {PropertyDescriptor} descriptor
4873 * @param {boolean} proxyTrap whether it's called from proxy trap
4874 * @returns {boolean|null} true on success, false on failure (proxyTrap + non-configurable), null when cancelled by interceptor
4875 */;
4876 _proto.delete_ = function delete_(key, proxyTrap) {
4877 if (proxyTrap === void 0) {
4878 proxyTrap = false;
4879 }
4880 // No such prop
4881 if (!hasProp(this.target_, key)) {
4882 return true;
4883 }
4884 // Intercept
4885 if (hasInterceptors(this)) {
4886 var change = interceptChange(this, {
4887 object: this.proxy_ || this.target_,
4888 name: key,
4889 type: REMOVE
4890 });
4891 // Cancelled
4892 if (!change) {
4893 return null;
4894 }
4895 }
4896 // Delete
4897 try {
4898 var _this$pendingKeys_, _this$pendingKeys_$ge;
4899 startBatch();
4900 var notify = hasListeners(this);
4901 var notifySpy = "development" !== "production" && isSpyEnabled();
4902 var observable = this.values_.get(key);
4903 // Value needed for spies/listeners
4904 var value = undefined;
4905 // Optimization: don't pull the value unless we will need it
4906 if (!observable && (notify || notifySpy)) {
4907 var _getDescriptor;
4908 value = (_getDescriptor = getDescriptor(this.target_, key)) == null ? void 0 : _getDescriptor.value;
4909 }
4910 // delete prop (do first, may fail)
4911 if (proxyTrap) {
4912 if (!Reflect.deleteProperty(this.target_, key)) {
4913 return false;
4914 }
4915 } else {
4916 delete this.target_[key];
4917 }
4918 // Allow re-annotating this field
4919 if ("development" !== "production") {
4920 delete this.appliedAnnotations_[key];
4921 }
4922 // Clear observable
4923 if (observable) {
4924 this.values_["delete"](key);
4925 // for computed, value is undefined
4926 if (observable instanceof ObservableValue) {
4927 value = observable.value_;
4928 }
4929 // Notify: autorun(() => obj[key]), see #1796
4930 propagateChanged(observable);
4931 }
4932 // Notify "keys/entries/values" observers
4933 this.keysAtom_.reportChanged();
4934 // Notify "has" observers
4935 // "in" as it may still exist in proto
4936 (_this$pendingKeys_ = this.pendingKeys_) == null ? void 0 : (_this$pendingKeys_$ge = _this$pendingKeys_.get(key)) == null ? void 0 : _this$pendingKeys_$ge.set(key in this.target_);
4937 // Notify spies/listeners
4938 if (notify || notifySpy) {
4939 var _change2 = {
4940 type: REMOVE,
4941 observableKind: "object",
4942 object: this.proxy_ || this.target_,
4943 debugObjectName: this.name_,
4944 oldValue: value,
4945 name: key
4946 };
4947 if ("development" !== "production" && notifySpy) {
4948 spyReportStart(_change2);
4949 }
4950 if (notify) {
4951 notifyListeners(this, _change2);
4952 }
4953 if ("development" !== "production" && notifySpy) {
4954 spyReportEnd();
4955 }
4956 }
4957 } finally {
4958 endBatch();
4959 }
4960 return true;
4961 }
4962 /**
4963 * Observes this object. Triggers for the events 'add', 'update' and 'delete'.
4964 * See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/observe
4965 * for callback details
4966 */;
4967 _proto.observe_ = function observe_(callback, fireImmediately) {
4968 if ( fireImmediately === true) {
4969 die("`observe` doesn't support the fire immediately property for observable objects.");
4970 }
4971 return registerListener(this, callback);
4972 };
4973 _proto.intercept_ = function intercept_(handler) {
4974 return registerInterceptor(this, handler);
4975 };
4976 _proto.notifyPropertyAddition_ = function notifyPropertyAddition_(key, value) {
4977 var _this$pendingKeys_2, _this$pendingKeys_2$g;
4978 var notify = hasListeners(this);
4979 var notifySpy = isSpyEnabled();
4980 if (notify || notifySpy) {
4981 var change = notify || notifySpy ? {
4982 type: ADD,
4983 observableKind: "object",
4984 debugObjectName: this.name_,
4985 object: this.proxy_ || this.target_,
4986 name: key,
4987 newValue: value
4988 } : null;
4989 if ( notifySpy) {
4990 spyReportStart(change);
4991 }
4992 if (notify) {
4993 notifyListeners(this, change);
4994 }
4995 if ( notifySpy) {
4996 spyReportEnd();
4997 }
4998 }
4999 (_this$pendingKeys_2 = this.pendingKeys_) == null ? void 0 : (_this$pendingKeys_2$g = _this$pendingKeys_2.get(key)) == null ? void 0 : _this$pendingKeys_2$g.set(true);
5000 // Notify "keys/entries/values" observers
5001 this.keysAtom_.reportChanged();
5002 };
5003 _proto.ownKeys_ = function ownKeys_() {
5004 this.keysAtom_.reportObserved();
5005 return ownKeys(this.target_);
5006 };
5007 _proto.keys_ = function keys_() {
5008 // Returns enumerable && own, but unfortunately keysAtom will report on ANY key change.
5009 // There is no way to distinguish between Object.keys(object) and Reflect.ownKeys(object) - both are handled by ownKeys trap.
5010 // We can either over-report in Object.keys(object) or under-report in Reflect.ownKeys(object)
5011 // We choose to over-report in Object.keys(object), because:
5012 // - typically it's used with simple data objects
5013 // - when symbolic/non-enumerable keys are relevant Reflect.ownKeys works as expected
5014 this.keysAtom_.reportObserved();
5015 return Object.keys(this.target_);
5016 };
5017 return ObservableObjectAdministration;
5018}();
5019function asObservableObject(target, options) {
5020 var _options$name;
5021 if ( options && isObservableObject(target)) {
5022 die("Options can't be provided for already observable objects.");
5023 }
5024 if (hasProp(target, $mobx)) {
5025 if ( !(getAdministration(target) instanceof ObservableObjectAdministration)) {
5026 die("Cannot convert '" + getDebugName(target) + "' into observable object:" + "\nThe target is already observable of different type." + "\nExtending builtins is not supported.");
5027 }
5028 return target;
5029 }
5030 if ( !Object.isExtensible(target)) {
5031 die("Cannot make the designated object observable; it is not extensible");
5032 }
5033 var name = (_options$name = options == null ? void 0 : options.name) != null ? _options$name : (isPlainObject(target) ? "ObservableObject" : target.constructor.name) + "@" + getNextId() ;
5034 var adm = new ObservableObjectAdministration(target, new Map(), String(name), getAnnotationFromOptions(options));
5035 addHiddenProp(target, $mobx, adm);
5036 return target;
5037}
5038var isObservableObjectAdministration = /*#__PURE__*/createInstanceofPredicate("ObservableObjectAdministration", ObservableObjectAdministration);
5039function getCachedObservablePropDescriptor(key) {
5040 return descriptorCache[key] || (descriptorCache[key] = {
5041 get: function get() {
5042 return this[$mobx].getObservablePropValue_(key);
5043 },
5044 set: function set(value) {
5045 return this[$mobx].setObservablePropValue_(key, value);
5046 }
5047 });
5048}
5049function isObservableObject(thing) {
5050 if (isObject(thing)) {
5051 return isObservableObjectAdministration(thing[$mobx]);
5052 }
5053 return false;
5054}
5055function recordAnnotationApplied(adm, annotation, key) {
5056 var _adm$target_$storedAn;
5057 {
5058 adm.appliedAnnotations_[key] = annotation;
5059 }
5060 // Remove applied decorator annotation so we don't try to apply it again in subclass constructor
5061 (_adm$target_$storedAn = adm.target_[storedAnnotationsSymbol]) == null ? true : delete _adm$target_$storedAn[key];
5062}
5063function assertAnnotable(adm, annotation, key) {
5064 // Valid annotation
5065 if ( !isAnnotation(annotation)) {
5066 die("Cannot annotate '" + adm.name_ + "." + key.toString() + "': Invalid annotation.");
5067 }
5068 /*
5069 // Configurable, not sealed, not frozen
5070 // Possibly not needed, just a little better error then the one thrown by engine.
5071 // Cases where this would be useful the most (subclass field initializer) are not interceptable by this.
5072 if (__DEV__) {
5073 const configurable = getDescriptor(adm.target_, key)?.configurable
5074 const frozen = Object.isFrozen(adm.target_)
5075 const sealed = Object.isSealed(adm.target_)
5076 if (!configurable || frozen || sealed) {
5077 const fieldName = `${adm.name_}.${key.toString()}`
5078 const requestedAnnotationType = annotation.annotationType_
5079 let error = `Cannot apply '${requestedAnnotationType}' to '${fieldName}':`
5080 if (frozen) {
5081 error += `\nObject is frozen.`
5082 }
5083 if (sealed) {
5084 error += `\nObject is sealed.`
5085 }
5086 if (!configurable) {
5087 error += `\nproperty is not configurable.`
5088 // Mention only if caused by us to avoid confusion
5089 if (hasProp(adm.appliedAnnotations!, key)) {
5090 error += `\nTo prevent accidental re-definition of a field by a subclass, `
5091 error += `all annotated fields of non-plain objects (classes) are not configurable.`
5092 }
5093 }
5094 die(error)
5095 }
5096 }
5097 */
5098 // Not annotated
5099 if ( !isOverride(annotation) && hasProp(adm.appliedAnnotations_, key)) {
5100 var fieldName = adm.name_ + "." + key.toString();
5101 var currentAnnotationType = adm.appliedAnnotations_[key].annotationType_;
5102 var requestedAnnotationType = annotation.annotationType_;
5103 die("Cannot apply '" + requestedAnnotationType + "' to '" + fieldName + "':" + ("\nThe field is already annotated with '" + currentAnnotationType + "'.") + "\nRe-annotating fields is not allowed." + "\nUse 'override' annotation for methods overridden by subclass.");
5104 }
5105}
5106
5107// Bug in safari 9.* (or iOS 9 safari mobile). See #364
5108var ENTRY_0 = /*#__PURE__*/createArrayEntryDescriptor(0);
5109/**
5110 * This array buffer contains two lists of properties, so that all arrays
5111 * can recycle their property definitions, which significantly improves performance of creating
5112 * properties on the fly.
5113 */
5114var OBSERVABLE_ARRAY_BUFFER_SIZE = 0;
5115// Typescript workaround to make sure ObservableArray extends Array
5116var StubArray = function StubArray() {};
5117function inherit(ctor, proto) {
5118 if (Object.setPrototypeOf) {
5119 Object.setPrototypeOf(ctor.prototype, proto);
5120 } else if (ctor.prototype.__proto__ !== undefined) {
5121 ctor.prototype.__proto__ = proto;
5122 } else {
5123 ctor.prototype = proto;
5124 }
5125}
5126inherit(StubArray, Array.prototype);
5127// Weex proto freeze protection was here,
5128// but it is unclear why the hack is need as MobX never changed the prototype
5129// anyway, so removed it in V6
5130var LegacyObservableArray = /*#__PURE__*/function (_StubArray, _Symbol$toStringTag, _Symbol$iterator) {
5131 _inheritsLoose(LegacyObservableArray, _StubArray);
5132 function LegacyObservableArray(initialValues, enhancer, name, owned) {
5133 var _this;
5134 if (name === void 0) {
5135 name = "ObservableArray@" + getNextId() ;
5136 }
5137 if (owned === void 0) {
5138 owned = false;
5139 }
5140 _this = _StubArray.call(this) || this;
5141 var adm = new ObservableArrayAdministration(name, enhancer, owned, true);
5142 adm.proxy_ = _assertThisInitialized(_this);
5143 addHiddenFinalProp(_assertThisInitialized(_this), $mobx, adm);
5144 if (initialValues && initialValues.length) {
5145 var prev = allowStateChangesStart(true);
5146 // @ts-ignore
5147 _this.spliceWithArray(0, 0, initialValues);
5148 allowStateChangesEnd(prev);
5149 }
5150 {
5151 // Seems that Safari won't use numeric prototype setter untill any * numeric property is
5152 // defined on the instance. After that it works fine, even if this property is deleted.
5153 Object.defineProperty(_assertThisInitialized(_this), "0", ENTRY_0);
5154 }
5155 return _this;
5156 }
5157 var _proto = LegacyObservableArray.prototype;
5158 _proto.concat = function concat() {
5159 this[$mobx].atom_.reportObserved();
5160 for (var _len = arguments.length, arrays = new Array(_len), _key = 0; _key < _len; _key++) {
5161 arrays[_key] = arguments[_key];
5162 }
5163 return Array.prototype.concat.apply(this.slice(),
5164 //@ts-ignore
5165 arrays.map(function (a) {
5166 return isObservableArray(a) ? a.slice() : a;
5167 }));
5168 };
5169 _proto[_Symbol$iterator] = function () {
5170 var self = this;
5171 var nextIndex = 0;
5172 return makeIterable({
5173 next: function next() {
5174 return nextIndex < self.length ? {
5175 value: self[nextIndex++],
5176 done: false
5177 } : {
5178 done: true,
5179 value: undefined
5180 };
5181 }
5182 });
5183 };
5184 _createClass(LegacyObservableArray, [{
5185 key: "length",
5186 get: function get() {
5187 return this[$mobx].getArrayLength_();
5188 },
5189 set: function set(newLength) {
5190 this[$mobx].setArrayLength_(newLength);
5191 }
5192 }, {
5193 key: _Symbol$toStringTag,
5194 get: function get() {
5195 return "Array";
5196 }
5197 }]);
5198 return LegacyObservableArray;
5199}(StubArray, Symbol.toStringTag, Symbol.iterator);
5200Object.entries(arrayExtensions).forEach(function (_ref) {
5201 var prop = _ref[0],
5202 fn = _ref[1];
5203 if (prop !== "concat") {
5204 addHiddenProp(LegacyObservableArray.prototype, prop, fn);
5205 }
5206});
5207function createArrayEntryDescriptor(index) {
5208 return {
5209 enumerable: false,
5210 configurable: true,
5211 get: function get() {
5212 return this[$mobx].get_(index);
5213 },
5214 set: function set(value) {
5215 this[$mobx].set_(index, value);
5216 }
5217 };
5218}
5219function createArrayBufferItem(index) {
5220 defineProperty(LegacyObservableArray.prototype, "" + index, createArrayEntryDescriptor(index));
5221}
5222function reserveArrayBuffer(max) {
5223 if (max > OBSERVABLE_ARRAY_BUFFER_SIZE) {
5224 for (var index = OBSERVABLE_ARRAY_BUFFER_SIZE; index < max + 100; index++) {
5225 createArrayBufferItem(index);
5226 }
5227 OBSERVABLE_ARRAY_BUFFER_SIZE = max;
5228 }
5229}
5230reserveArrayBuffer(1000);
5231function createLegacyArray(initialValues, enhancer, name) {
5232 return new LegacyObservableArray(initialValues, enhancer, name);
5233}
5234
5235function getAtom(thing, property) {
5236 if (typeof thing === "object" && thing !== null) {
5237 if (isObservableArray(thing)) {
5238 if (property !== undefined) {
5239 die(23);
5240 }
5241 return thing[$mobx].atom_;
5242 }
5243 if (isObservableSet(thing)) {
5244 return thing.atom_;
5245 }
5246 if (isObservableMap(thing)) {
5247 if (property === undefined) {
5248 return thing.keysAtom_;
5249 }
5250 var observable = thing.data_.get(property) || thing.hasMap_.get(property);
5251 if (!observable) {
5252 die(25, property, getDebugName(thing));
5253 }
5254 return observable;
5255 }
5256 if (isObservableObject(thing)) {
5257 if (!property) {
5258 return die(26);
5259 }
5260 var _observable = thing[$mobx].values_.get(property);
5261 if (!_observable) {
5262 die(27, property, getDebugName(thing));
5263 }
5264 return _observable;
5265 }
5266 if (isAtom(thing) || isComputedValue(thing) || isReaction(thing)) {
5267 return thing;
5268 }
5269 } else if (isFunction(thing)) {
5270 if (isReaction(thing[$mobx])) {
5271 // disposer function
5272 return thing[$mobx];
5273 }
5274 }
5275 die(28);
5276}
5277function getAdministration(thing, property) {
5278 if (!thing) {
5279 die(29);
5280 }
5281 if (property !== undefined) {
5282 return getAdministration(getAtom(thing, property));
5283 }
5284 if (isAtom(thing) || isComputedValue(thing) || isReaction(thing)) {
5285 return thing;
5286 }
5287 if (isObservableMap(thing) || isObservableSet(thing)) {
5288 return thing;
5289 }
5290 if (thing[$mobx]) {
5291 return thing[$mobx];
5292 }
5293 die(24, thing);
5294}
5295function getDebugName(thing, property) {
5296 var named;
5297 if (property !== undefined) {
5298 named = getAtom(thing, property);
5299 } else if (isAction(thing)) {
5300 return thing.name;
5301 } else if (isObservableObject(thing) || isObservableMap(thing) || isObservableSet(thing)) {
5302 named = getAdministration(thing);
5303 } else {
5304 // valid for arrays as well
5305 named = getAtom(thing);
5306 }
5307 return named.name_;
5308}
5309
5310var toString = objectPrototype.toString;
5311function deepEqual(a, b, depth) {
5312 if (depth === void 0) {
5313 depth = -1;
5314 }
5315 return eq(a, b, depth);
5316}
5317// Copied from https://github.com/jashkenas/underscore/blob/5c237a7c682fb68fd5378203f0bf22dce1624854/underscore.js#L1186-L1289
5318// Internal recursive comparison function for `isEqual`.
5319function eq(a, b, depth, aStack, bStack) {
5320 // Identical objects are equal. `0 === -0`, but they aren't identical.
5321 // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal).
5322 if (a === b) {
5323 return a !== 0 || 1 / a === 1 / b;
5324 }
5325 // `null` or `undefined` only equal to itself (strict comparison).
5326 if (a == null || b == null) {
5327 return false;
5328 }
5329 // `NaN`s are equivalent, but non-reflexive.
5330 if (a !== a) {
5331 return b !== b;
5332 }
5333 // Exhaust primitive checks
5334 var type = typeof a;
5335 if (type !== "function" && type !== "object" && typeof b != "object") {
5336 return false;
5337 }
5338 // Compare `[[Class]]` names.
5339 var className = toString.call(a);
5340 if (className !== toString.call(b)) {
5341 return false;
5342 }
5343 switch (className) {
5344 // Strings, numbers, regular expressions, dates, and booleans are compared by value.
5345 case "[object RegExp]":
5346 // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i')
5347 case "[object String]":
5348 // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
5349 // equivalent to `new String("5")`.
5350 return "" + a === "" + b;
5351 case "[object Number]":
5352 // `NaN`s are equivalent, but non-reflexive.
5353 // Object(NaN) is equivalent to NaN.
5354 if (+a !== +a) {
5355 return +b !== +b;
5356 }
5357 // An `egal` comparison is performed for other numeric values.
5358 return +a === 0 ? 1 / +a === 1 / b : +a === +b;
5359 case "[object Date]":
5360 case "[object Boolean]":
5361 // Coerce dates and booleans to numeric primitive values. Dates are compared by their
5362 // millisecond representations. Note that invalid dates with millisecond representations
5363 // of `NaN` are not equivalent.
5364 return +a === +b;
5365 case "[object Symbol]":
5366 return typeof Symbol !== "undefined" && Symbol.valueOf.call(a) === Symbol.valueOf.call(b);
5367 case "[object Map]":
5368 case "[object Set]":
5369 // Maps and Sets are unwrapped to arrays of entry-pairs, adding an incidental level.
5370 // Hide this extra level by increasing the depth.
5371 if (depth >= 0) {
5372 depth++;
5373 }
5374 break;
5375 }
5376 // Unwrap any wrapped objects.
5377 a = unwrap(a);
5378 b = unwrap(b);
5379 var areArrays = className === "[object Array]";
5380 if (!areArrays) {
5381 if (typeof a != "object" || typeof b != "object") {
5382 return false;
5383 }
5384 // Objects with different constructors are not equivalent, but `Object`s or `Array`s
5385 // from different frames are.
5386 var aCtor = a.constructor,
5387 bCtor = b.constructor;
5388 if (aCtor !== bCtor && !(isFunction(aCtor) && aCtor instanceof aCtor && isFunction(bCtor) && bCtor instanceof bCtor) && "constructor" in a && "constructor" in b) {
5389 return false;
5390 }
5391 }
5392 if (depth === 0) {
5393 return false;
5394 } else if (depth < 0) {
5395 depth = -1;
5396 }
5397 // Assume equality for cyclic structures. The algorithm for detecting cyclic
5398 // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
5399 // Initializing stack of traversed objects.
5400 // It's done here since we only need them for objects and arrays comparison.
5401 aStack = aStack || [];
5402 bStack = bStack || [];
5403 var length = aStack.length;
5404 while (length--) {
5405 // Linear search. Performance is inversely proportional to the number of
5406 // unique nested structures.
5407 if (aStack[length] === a) {
5408 return bStack[length] === b;
5409 }
5410 }
5411 // Add the first object to the stack of traversed objects.
5412 aStack.push(a);
5413 bStack.push(b);
5414 // Recursively compare objects and arrays.
5415 if (areArrays) {
5416 // Compare array lengths to determine if a deep comparison is necessary.
5417 length = a.length;
5418 if (length !== b.length) {
5419 return false;
5420 }
5421 // Deep compare the contents, ignoring non-numeric properties.
5422 while (length--) {
5423 if (!eq(a[length], b[length], depth - 1, aStack, bStack)) {
5424 return false;
5425 }
5426 }
5427 } else {
5428 // Deep compare objects.
5429 var keys = Object.keys(a);
5430 var key;
5431 length = keys.length;
5432 // Ensure that both objects contain the same number of properties before comparing deep equality.
5433 if (Object.keys(b).length !== length) {
5434 return false;
5435 }
5436 while (length--) {
5437 // Deep compare each member
5438 key = keys[length];
5439 if (!(hasProp(b, key) && eq(a[key], b[key], depth - 1, aStack, bStack))) {
5440 return false;
5441 }
5442 }
5443 }
5444 // Remove the first object from the stack of traversed objects.
5445 aStack.pop();
5446 bStack.pop();
5447 return true;
5448}
5449function unwrap(a) {
5450 if (isObservableArray(a)) {
5451 return a.slice();
5452 }
5453 if (isES6Map(a) || isObservableMap(a)) {
5454 return Array.from(a.entries());
5455 }
5456 if (isES6Set(a) || isObservableSet(a)) {
5457 return Array.from(a.entries());
5458 }
5459 return a;
5460}
5461
5462function makeIterable(iterator) {
5463 iterator[Symbol.iterator] = getSelf;
5464 return iterator;
5465}
5466function getSelf() {
5467 return this;
5468}
5469
5470function isAnnotation(thing) {
5471 return (
5472 // Can be function
5473 thing instanceof Object && typeof thing.annotationType_ === "string" && isFunction(thing.make_) && isFunction(thing.extend_)
5474 );
5475}
5476
5477/**
5478 * (c) Michel Weststrate 2015 - 2020
5479 * MIT Licensed
5480 *
5481 * Welcome to the mobx sources! To get a global overview of how MobX internally works,
5482 * this is a good place to start:
5483 * https://medium.com/@mweststrate/becoming-fully-reactive-an-in-depth-explanation-of-mobservable-55995262a254#.xvbh6qd74
5484 *
5485 * Source folders:
5486 * ===============
5487 *
5488 * - api/ Most of the public static methods exposed by the module can be found here.
5489 * - core/ Implementation of the MobX algorithm; atoms, derivations, reactions, dependency trees, optimizations. Cool stuff can be found here.
5490 * - types/ All the magic that is need to have observable objects, arrays and values is in this folder. Including the modifiers like `asFlat`.
5491 * - utils/ Utility stuff.
5492 *
5493 */
5494["Symbol", "Map", "Set"].forEach(function (m) {
5495 var g = getGlobal();
5496 if (typeof g[m] === "undefined") {
5497 die("MobX requires global '" + m + "' to be available or polyfilled");
5498 }
5499});
5500if (typeof __MOBX_DEVTOOLS_GLOBAL_HOOK__ === "object") {
5501 // See: https://github.com/andykog/mobx-devtools/
5502 __MOBX_DEVTOOLS_GLOBAL_HOOK__.injectMobx({
5503 spy: spy,
5504 extras: {
5505 getDebugName: getDebugName
5506 },
5507 $mobx: $mobx
5508 });
5509}
5510
5511export { $mobx, FlowCancellationError, ObservableMap, ObservableSet, Reaction, allowStateChanges as _allowStateChanges, runInAction as _allowStateChangesInsideComputed, allowStateReadsEnd as _allowStateReadsEnd, allowStateReadsStart as _allowStateReadsStart, autoAction as _autoAction, _endAction, getAdministration as _getAdministration, getGlobalState as _getGlobalState, interceptReads as _interceptReads, isComputingDerivation as _isComputingDerivation, resetGlobalState as _resetGlobalState, _startAction, action, autorun, comparer, computed, configure, createAtom, apiDefineProperty as defineProperty, entries, extendObservable, flow, flowResult, get, getAtom, getDebugName, getDependencyTree, getObserverTree, has, intercept, isAction, isObservableValue as isBoxedObservable, isComputed, isComputedProp, isFlow, isFlowCancellationError, isObservable, isObservableArray, isObservableMap, isObservableObject, isObservableProp, isObservableSet, keys, makeAutoObservable, makeObservable, observable, observe, onBecomeObserved, onBecomeUnobserved, onReactionError, override, apiOwnKeys as ownKeys, reaction, remove, runInAction, set, spy, toJS, trace, transaction, untracked, values, when };
5512//# sourceMappingURL=mobx.esm.development.js.map