mobx-keystone 1.25.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/CHANGELOG.md +123 -0
  2. package/dist/mobx-keystone.esm.js +1478 -952
  3. package/dist/mobx-keystone.esm.mjs +1478 -952
  4. package/dist/mobx-keystone.umd.js +1483 -952
  5. package/dist/types/actionMiddlewares/actionSerialization/dateSerializer.d.ts +1 -1
  6. package/dist/types/dataModel/dataModelInstanceCache.d.ts +1 -0
  7. package/dist/types/deepChange/onDeepChange.d.ts +9 -0
  8. package/dist/types/parent/detach.d.ts +1 -1
  9. package/dist/types/parent/findChildren.d.ts +1 -1
  10. package/dist/types/patch/applyPatches.d.ts +2 -0
  11. package/dist/types/redux/connectReduxDevTools.d.ts +2 -1
  12. package/dist/types/snapshot/SnapshotOf.d.ts +2 -2
  13. package/dist/types/standardActions/arrayActions.d.ts +1 -1
  14. package/dist/types/treeUtils/sandbox.d.ts +0 -4
  15. package/dist/types/types/TypeCheckError.d.ts +1 -0
  16. package/dist/types/types/utility/typesRefinement.d.ts +2 -2
  17. package/dist/types/utils/forEachWithDelayedThrow.d.ts +1 -0
  18. package/dist/types/utils/index.d.ts +13 -0
  19. package/dist/types/utils/mapUtils.d.ts +2 -2
  20. package/dist/types/utils/setLike.d.ts +1 -0
  21. package/package.json +1 -1
  22. package/src/action/applyAction.ts +1 -1
  23. package/src/action/middleware.ts +17 -36
  24. package/src/action/modelFlow.ts +4 -5
  25. package/src/action/mutationBatch.ts +10 -10
  26. package/src/action/pendingActions.ts +3 -4
  27. package/src/actionMiddlewares/actionSerialization/actionSerialization.ts +19 -14
  28. package/src/actionMiddlewares/actionSerialization/applySerializedAction.ts +29 -20
  29. package/src/actionMiddlewares/actionSerialization/arraySerializer.ts +1 -1
  30. package/src/actionMiddlewares/actionSerialization/dateSerializer.ts +4 -3
  31. package/src/actionMiddlewares/actionSerialization/mapSerializer.ts +4 -12
  32. package/src/actionMiddlewares/actionSerialization/setSerializer.ts +4 -13
  33. package/src/actionMiddlewares/actionTrackingMiddleware.ts +11 -13
  34. package/src/actionMiddlewares/transactionMiddleware.ts +42 -11
  35. package/src/actionMiddlewares/undoMiddleware.ts +65 -46
  36. package/src/actionMiddlewares/utils.ts +2 -1
  37. package/src/computedTree/computedTree.ts +14 -3
  38. package/src/context/context.ts +17 -45
  39. package/src/dataModel/BaseDataModel.ts +20 -16
  40. package/src/dataModel/dataModelInstanceCache.ts +8 -0
  41. package/src/deepChange/onDeepChange.ts +179 -24
  42. package/src/frozen/Frozen.ts +50 -33
  43. package/src/model/BaseModel.ts +4 -9
  44. package/src/model/newModel.ts +21 -24
  45. package/src/model/utils.ts +2 -2
  46. package/src/modelShared/modelClassInitializer.ts +3 -2
  47. package/src/modelShared/modelDecorator.ts +34 -14
  48. package/src/modelShared/modelInfo.ts +1 -1
  49. package/src/modelShared/prop.ts +6 -9
  50. package/src/modelShared/sharedInternalModel.ts +16 -3
  51. package/src/parent/detach.ts +1 -1
  52. package/src/parent/findChildren.ts +4 -7
  53. package/src/parent/onChildAttachedTo.ts +44 -28
  54. package/src/parent/path.ts +5 -3
  55. package/src/parent/setParent.ts +7 -0
  56. package/src/parent/walkTree.ts +21 -37
  57. package/src/patch/applyPatches.ts +69 -34
  58. package/src/patch/emitPatch.ts +142 -26
  59. package/src/patch/jsonPatch.ts +5 -0
  60. package/src/patch/patchRecorder.ts +18 -14
  61. package/src/redux/connectReduxDevTools.ts +24 -18
  62. package/src/redux/redux.ts +5 -21
  63. package/src/ref/core.ts +18 -2
  64. package/src/rootStore/attachDetach.ts +27 -16
  65. package/src/rootStore/rootStore.ts +10 -6
  66. package/src/snapshot/SnapshotOf.ts +2 -2
  67. package/src/snapshot/applySnapshot.ts +1 -1
  68. package/src/snapshot/clone.ts +1 -2
  69. package/src/snapshot/cloneTreeValue.ts +1 -2
  70. package/src/snapshot/fromModelSnapshot.ts +6 -2
  71. package/src/snapshot/internal.ts +22 -9
  72. package/src/snapshot/onSnapshot.ts +12 -1
  73. package/src/snapshot/reconcileModelSnapshot.ts +6 -6
  74. package/src/snapshot/reconcilePlainObjectSnapshot.ts +5 -4
  75. package/src/standardActions/arrayActions.ts +12 -2
  76. package/src/standardActions/objectActions.ts +3 -2
  77. package/src/transforms/ImmutableDate.ts +4 -0
  78. package/src/transforms/asMap.ts +3 -1
  79. package/src/treeUtils/deepEquals.ts +15 -13
  80. package/src/treeUtils/draft.ts +8 -0
  81. package/src/treeUtils/sandbox.ts +31 -27
  82. package/src/tweaker/core.ts +2 -4
  83. package/src/tweaker/tweak.ts +2 -1
  84. package/src/tweaker/tweakArray.ts +83 -20
  85. package/src/tweaker/tweakPlainObject.ts +76 -23
  86. package/src/tweaker/typeChecking.ts +124 -15
  87. package/src/types/TypeCheckError.ts +17 -19
  88. package/src/types/createCachedTypeCheck.ts +27 -2
  89. package/src/types/objectBased/typesDataModelData.ts +4 -2
  90. package/src/types/objectBased/typesModel.ts +4 -2
  91. package/src/types/objectBased/typesObject.ts +20 -16
  92. package/src/types/objectBased/typesRecord.ts +6 -13
  93. package/src/types/objectBased/typesRef.ts +2 -2
  94. package/src/types/primitiveBased/typesEnum.ts +4 -2
  95. package/src/types/primitiveBased/typesPrimitive.ts +9 -4
  96. package/src/types/typeCheckErrorUtils.ts +1 -0
  97. package/src/types/utility/typesCodecSupport.ts +97 -56
  98. package/src/types/utility/typesMap.ts +24 -41
  99. package/src/types/utility/typesRefinement.ts +3 -2
  100. package/src/types/utility/typesSet.ts +24 -0
  101. package/src/utils/ModelPool.ts +3 -3
  102. package/src/utils/chainFns.ts +4 -0
  103. package/src/utils/decorators.ts +1 -1
  104. package/src/utils/errorDiagnostics.ts +6 -2
  105. package/src/utils/forEachWithDelayedThrow.ts +83 -0
  106. package/src/utils/index.ts +34 -2
  107. package/src/utils/mapUtils.ts +3 -7
  108. package/src/utils/setIfDifferent.ts +3 -2
  109. package/src/utils/setLike.ts +134 -0
  110. package/src/wrappers/ArraySet.ts +5 -9
  111. package/src/wrappers/ObjectMap.ts +15 -11
  112. package/src/wrappers/asMap.ts +30 -18
  113. package/src/wrappers/asSet.ts +36 -12
  114. package/dist/types/action/modelFlowPromiseGenerator.d.ts +0 -1
  115. package/src/action/modelFlowPromiseGenerator.ts +0 -127
package/CHANGELOG.md CHANGED
@@ -1,5 +1,128 @@
1
1
  # Change Log
2
2
 
3
+ ## 2.0.0
4
+
5
+ - [BREAKING CHANGE] Preserve repeated property names and array indexes in type-check error paths when validating an attached subtree. Paths supplied to `TypeCheckError` and `TypeCheckErrorFailure` are now consistently treated as relative to the checked value; manually supplied rooted paths are no longer detected automatically.
6
+ - [BREAKING CHANGE] Continue transaction rollback after patch listeners or patch recorders throw, including all inverse patches of an array edit; if any fail, throw a `MobxKeystoneAggregateError` whose first error is the original action error, followed by the callback failures.
7
+ - [BREAKING CHANGE] Prevent replacement or deletion of checked frozen data and avoid repeated validation of shared frozen subtrees.
8
+ - [BREAKING CHANGE] Reject arrays consistently in `types.object` and `types.record`, including snapshot matching.
9
+ - [BREAKING CHANGE] Reject malformed JSON Pointer escapes instead of interpreting them as literal property names.
10
+ - [BREAKING CHANGE] Enforce refinements around codec-backed values during model construction and writes, including rollback of invalid writes.
11
+ - [BREAKING CHANGE] Support JSON Patch `"-"` array appends and root-content replacement at an empty path; reject root removal and malformed or out-of-range array indexes instead of silently changing unrelated data.
12
+ - [BREAKING CHANGE] Continue patch delivery to remaining listeners after a listener throws, then report the failures once delivery has finished. This also covers `patchRecorder` callbacks, so a failing recorder no longer silently stops the recorders registered on ancestor nodes, nor the deep-change listeners and the deferred patch listeners of the same mutation. Failures from all three are reported together.
13
+ - [BREAKING CHANGE] Added `MobxKeystoneAggregateError`, a `MobxKeystoneError` subclass with an `errors` array. Patch listeners, patch recorders, deep-change listeners and root store attachment hooks now share one failure rule: every callback runs, a lone failure is rethrown as is, and several failures are grouped in a `MobxKeystoneAggregateError` whose `errors` is a flat list, even across nested delivery.
14
+ - [BREAKING CHANGE] Validate that `types.ref` values belong to the specified reference constructor.
15
+ - [BREAKING CHANGE] Reject invalid undo/redo history limits instead of allowing negative limits to hang history trimming.
16
+ - [BREAKING CHANGE] Run child-hook disposal callbacks in reverse attachment order, including explicit disposal. Continue remaining detachments and attachments when a callback throws, then report the first error.
17
+ - [BREAKING CHANGE] Object property setters now use `SameValueZero` equality, so re-setting a `NaN` property is a no-op. `0` and `-0` are treated as the same value throughout, matching `deepEquals`, literal type checks and JSON.
18
+ - [BREAKING CHANGE] ID-checked path resolution now rejects missing array properties instead of resolving them as `undefined`.
19
+ - [BREAKING CHANGE] `resolvePath` now distinguishes missing properties from properties whose value is `undefined`.
20
+ - [BREAKING CHANGE] Validate `applyPatches` against the completed batch, including nested/reversed patch lists, newly created models, and synchronous listener-triggered edits. Rejected batches roll back with compensating patches instead of leaving earlier patches applied. Literal property deletion and field-update semantics remain unchanged.
21
+ - [BREAKING CHANGE] Continue deep-change delivery after a listener throws, so later global, subtree, and ancestor listeners observe the applied mutation, then report the failures once delivery completes.
22
+ - [BREAKING CHANGE] Emit deep-change notifications after individual mutations pass automatic type checking and update their snapshots. Rejected mutations and their quiet rollbacks no longer reach deep-change listeners or CRDT bindings.
23
+ - Keep `asMap` and `asSet` synchronized when an interceptor cancels additions or deletions on their backing data.
24
+ - Remove omitted prototype-named properties and restore their model defaults correctly when applying snapshots.
25
+ - Synchronize final model IDs and paths when serialized actions move, replace, or remove models before finishing.
26
+ - Improve action-tracking performance for flows with many yield steps.
27
+ - Correct `ObjectMap` and `ArraySet` input snapshot item types so defaulted model fields can be omitted.
28
+ - Fix partial draft operations through codec-backed model properties by checking model IDs along stored data paths.
29
+ - Synchronize back-references when a reference's resolved target changes before its first tracking run.
30
+ - Preserve default options when explicitly set to `undefined` in Redux DevTools logging and model/data-model `toString`.
31
+ - Report the previous tracked snapshot correctly when `onSnapshot` is registered inside an action that changes the observed node before the action finishes.
32
+ - Preserve empty-string model type names in registration, snapshots, restoration, and cloning.
33
+ - Keep default ID regeneration in `clone` and `cloneTreeValue` when `generateNewIds` is explicitly `undefined`.
34
+ - Keep immediate child attachment callbacks enabled when `fireForCurrentChildren` is explicitly `undefined`.
35
+ - Make data-model `toString()` include its backing data without throwing.
36
+ - Retry data-model initialization after construction fails, and preserve fields and run `onLazyInit` only once when reusing a successfully initialized wrapper.
37
+ - Support empty-string ID property names throughout construction, cloning, ID lookup, and snapshot reconciliation.
38
+ - Validate model and data-model `__proto__` properties and apply their defaults during construction, including model snapshot construction.
39
+ - Preserve `__proto__` entries when converting a map back through the deprecated `objectToMapTransform`.
40
+ - Keep action middleware chains stable when middleware registers or disposes during an action.
41
+ - Finish pending root attachment callbacks even if an earlier callback throws, and retain the correct cleanup when a model moves during its attachment hook. Skip attachment hooks for models already detached or moved by an earlier hook of the same attachment.
42
+ - Avoid stringifying action targets during replay; preserve sparse top-level action arguments through JSON serialization.
43
+ - Preserve custom model trails in cached type-check errors and own `__proto__` properties in model and data-model type information.
44
+ - Report unsupported symbol and unprintable values with library errors, and name the correct action decorator in legacy symbol diagnostics.
45
+ - Trim excess undo and redo history in one operation instead of repeatedly shifting entries.
46
+ - Preserve custom refinement error model trails through nested type checks.
47
+ - Allow context `apply` and `applyComputed` callbacks to return model data objects without trying to register them as providers.
48
+ - Initialize Redux DevTools state before subscribing, supporting synchronous monitor messages and avoiding subscriptions when initialization fails.
49
+ - Honor cached `undefined` values in custom codecs, and return `undefined` when codec-array `pop` or `shift` removes a hole.
50
+ - Load safely in environments without a global Node `process` object.
51
+ - Preserve diagnostic errors when the rejected value throws during string conversion.
52
+ - Ignore retained Redux DevTools monitor callbacks after disposal.
53
+ - Return the stored observable value from `asMap` insertion helpers on MobX 4/5.
54
+ - Support generated setters for empty-string property names.
55
+ - Keep published patch paths unchanged while tracking model ID overrides in serialized actions.
56
+ - Dispose serializers using their original registered ID, avoiding removal of another serializer after an ID edit.
57
+ - Deduplicate large enum definitions in linear time.
58
+ - Return an idempotent disposer from `connectReduxDevTools` to stop logging and unsubscribe from monitor messages.
59
+ - Preserve undefined entries in sparse action arrays through JSON serialization.
60
+ - Keep action serializer traversal stable when a serializer registers or unregisters handlers during serialization.
61
+ - Report unsupported symbol action arguments as `MobxKeystoneError`, and close set iterators when element serialization fails.
62
+ - Implement codec-backed set union, intersection, difference, and symmetric difference without requiring native set methods; intersection avoids decoding the larger operand.
63
+ - Avoid copying codec-backed sets for subset, superset, and disjoint checks; use size checks and early exits while honoring codec-set membership.
64
+ - Preserve current values when reusing writable custom codec views after they replace their stored data.
65
+ - Make codec-backed set operations match native set results and iteration order across supported MobX versions.
66
+ - Accumulate callback failures in linear time rather than repeatedly copying all preceding failures.
67
+ - Return the stored runtime view from codec-backed map insertion helpers, so mutations through returned collections update the map.
68
+ - Track entry additions and removals when observing `ObjectMap.forEach` on MobX 4.
69
+ - Preserve large nested callback failure batches without argument-limit errors interrupting delivery.
70
+ - Restore falsy undo/redo attached state, and avoid leaking a recorder when the initial attached-state callback throws.
71
+ - Keep transaction rollback recording active after nested actions return.
72
+ - Discard rejected nested sandbox edits instead of replaying them on commit, and synchronize the sandbox with changes triggered during commit. Commits now cost time proportional to the changes being committed rather than to the size of the tree.
73
+ - Balance parent action-tracking resume/suspend hooks when a child completion hook throws.
74
+ - Honor child-hook disposal during attachment callbacks, including whether pending cleanup should run.
75
+ - Preserve `__proto__` entries in `objectMap`, and return the stored value from its insertion helpers.
76
+ - Keep nested transforms' cache decisions independent, and retain cached transform values for `NaN`.
77
+ - Match native array argument handling for codec-backed `splice` and `at`, and support large codec-backed reversals and other whole-array mutations without argument-limit errors.
78
+ - Re-encode reused mutable codec inputs instead of returning stale encoded values, and preserve special property names in object, record, and map codecs.
79
+ - Pass the actual previous reference target to resolution-change callbacks on MobX 4/5.
80
+ - Support observable sets in JSON action-argument serialization.
81
+ - Restore sandbox state after a rejected commit so subsequent operations start from the actual original tree.
82
+ - Handle large undo patch batches without argument-limit errors, and avoid leaked undo recorders when attached-state saving fails.
83
+ - Invoke action-tracking completion hooks only once when a completion hook throws.
84
+ - Preserve explicitly supplied empty-string model IDs and reuse those models when snapshot reconciliation moves them.
85
+ - Restore the previous computed tree if its replacement cannot be attached.
86
+ - Ensure `objectActions.set` and `assign` update stored data and snapshots when used on observable models.
87
+ - Preserve Redux middleware handler state across dispatches and invoke the full downstream chain on repeated `next` calls.
88
+ - Make Redux DevTools reset use the latest committed state, and avoid logging no-op actions after time travel.
89
+ - Accept scalar values alongside arrays in `arrayActions.concat` TypeScript arguments.
90
+ - Prevent repeated undo-group completion from duplicating history, and keep empty groups from discarding redo history.
91
+ - Reject asynchronous flow promises when completion middleware or an undo group's final attached-state callback throws, instead of leaving them pending.
92
+ - Support deeply nested frozen data without overflowing the call stack.
93
+ - Preserve literal `__proto__` properties when processing typed object and record snapshots.
94
+ - Preserve object identity between `asMap`/`asSet` and their backing collections, both when wrapping shallow observables and when writes convert values into observable objects or tree nodes.
95
+ - `ArraySet.keys()` and `ArraySet.values()` iterators now visit values appended during iteration, matching the existing entries iterator.
96
+ - Keep root-store registration status reactive when attachment or disposal hooks throw, and continue remaining hooks before reporting the failures.
97
+ - Prevent subclass model initializers from running on base or sibling model instances.
98
+ - Exclude reverse-mapping names from numeric enums whose values include `NaN`.
99
+ - Make action-argument serializer disposers idempotent, so an old disposer cannot remove a later registration.
100
+ - Preserve invalid dates across JSON action-argument round trips.
101
+ - Prevent inherited property names and `__proto__` registrations from creating unintended model registry entries.
102
+ - Fixed `arrayActions.swap` reordering other items when both indexes are equal; non-integer indexes now return `false` without modifying the array.
103
+ - Empty paths in `Draft.commitByPath` and `Draft.resetByPath` now commit or reset the whole draft.
104
+ - Prevent the legacy `setYear` method from mutating immutable dates.
105
+ - Fixed stack overflows during children-first `walkTree` traversal of deeply nested trees.
106
+ - Fixed bigint literal type construction and `NaN` literal validation, including their type names in errors.
107
+ - Frozen-data validation now rejects cycles with a descriptive library error while continuing to allow shared descendants.
108
+ - Deduplicate `arraySet` initial values while preserving insertion order, so size and deletion behave consistently with a set.
109
+ - Fixed stack overflows in context value and provider lookups on deeply nested trees.
110
+ - Fixed `asSet.add` appending duplicate backing entries when the value is already present, which could leave stale entries after deletion or clearing.
111
+ - Fixed deletion of `NaN` in `ArraySet` and `asSet`, and updates/deletions of `NaN` keys in array-backed `asMap`, keeping backing arrays synchronized.
112
+ - Preserve literal `__proto__` entries in `mapToObject` conversions without changing the object prototype.
113
+ - Keep deep-change listener delivery stable when subscriptions change inside callbacks. Self-unsubscription no longer skips later listeners, listeners disposed while a change is being delivered no longer receive it, and duplicate callback registrations have independent, idempotent disposers.
114
+ - Preserve snapshot immutability when union types or custom output processors wrap shared child snapshots, including snapshots captured after earlier edits.
115
+ - Expose `DeepChange.isReentrant` for notifications that overlap listener-triggered mutations, allowing bindings to recover their final local state.
116
+ - Preserve chronological patch delivery and mutation-time paths when deep-change or patch listeners make reentrant edits. Patch recorders capture changes synchronously, preserving transaction rollback, recording scopes, and `withoutUndo` during listener-triggered edits.
117
+ - Fixed type-check error formatting for model data objects, allowing record-or-model unions to continue to a valid model alternative.
118
+ - Validate object key additions and removals without stale cached checks, including MobX 4 removal notifications, while preserving cached checks for unrelated subtrees.
119
+ - Fixed automatic type checking skipping a snapshot reconciliation target’s own model type. The target and its typed ancestors now validate the completed snapshot.
120
+ - Fixed stale snapshots after automatic type checking rejects snapshot reconciliation. Rollback now restores cached snapshots and emits compensating patches for already-published changes.
121
+ - Fixed argument-limit errors when large array splices update snapshots or emit forward/inverse patches; large snapshot splices now move the tail once without spreading inserted values into function arguments.
122
+ - Fixed snapshot reconciliation when replacing a nested model with a plain object, preserving the detached model instead of modifying its instance state.
123
+ - Improved `deepEquals` performance for primitive and shallow comparisons by avoiding redundant tree metadata and observable checks.
124
+ - Fixed stale parent snapshots when attaching a detached subtree with pending descendant changes, including model moves during snapshot reconciliation.
125
+
3
126
  ## 1.25.0
4
127
 
5
128
  - Performance: reduced scalar mutation overhead by returning primitive values before entering internal MobX actions used for tree bookkeeping.