mobx-keystone 1.21.0 → 1.23.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 (72) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/mobx-keystone.esm.js +6769 -5815
  3. package/dist/mobx-keystone.esm.mjs +6769 -5815
  4. package/dist/mobx-keystone.umd.js +6785 -5816
  5. package/dist/types/action/runUnprotected.d.ts +8 -4
  6. package/dist/types/model/Model.d.ts +5 -0
  7. package/dist/types/modelShared/prop.d.ts +8 -4
  8. package/dist/types/redux/connectReduxDevTools.d.ts +17 -4
  9. package/dist/types/snapshot/modelInitialData.d.ts +1 -0
  10. package/dist/types/tweaker/treeNodeMetadata.d.ts +1 -0
  11. package/dist/types/types/TypeCheckError.d.ts +12 -2
  12. package/dist/types/types/createCachedTypeCheck.d.ts +1 -0
  13. package/package.json +18 -17
  14. package/src/action/middleware.ts +5 -18
  15. package/src/action/mutationBatch.ts +72 -0
  16. package/src/action/runUnprotected.ts +21 -8
  17. package/src/action/wrapInAction.ts +45 -15
  18. package/src/dataModel/BaseDataModel.ts +4 -8
  19. package/src/deepChange/onDeepChange.ts +246 -16
  20. package/src/model/BaseModel.ts +4 -12
  21. package/src/model/Model.ts +5 -0
  22. package/src/model/newModel.ts +68 -36
  23. package/src/modelShared/prop.ts +105 -63
  24. package/src/modelShared/sharedInternalModel.ts +91 -60
  25. package/src/parent/core.ts +16 -10
  26. package/src/parent/coreObjectChildren.ts +219 -21
  27. package/src/parent/path.ts +6 -5
  28. package/src/parent/setParent.ts +5 -5
  29. package/src/patch/emitPatch.ts +102 -20
  30. package/src/redux/connectReduxDevTools.ts +37 -5
  31. package/src/snapshot/fromArraySnapshot.ts +13 -10
  32. package/src/snapshot/fromModelSnapshot.ts +10 -3
  33. package/src/snapshot/fromPlainObjectSnapshot.ts +27 -11
  34. package/src/snapshot/fromSnapshot.ts +33 -12
  35. package/src/snapshot/getSnapshot.ts +8 -3
  36. package/src/snapshot/internal.ts +243 -82
  37. package/src/snapshot/modelInitialData.ts +41 -0
  38. package/src/snapshot/reconcileArraySnapshot.ts +9 -3
  39. package/src/snapshot/reconcileModelSnapshot.ts +97 -17
  40. package/src/snapshot/reconcilePlainObjectSnapshot.ts +9 -3
  41. package/src/tweaker/core.ts +30 -5
  42. package/src/tweaker/treeNodeMetadata.ts +38 -0
  43. package/src/tweaker/tweak.ts +15 -4
  44. package/src/tweaker/tweakArray.ts +191 -98
  45. package/src/tweaker/tweakFrozen.ts +2 -2
  46. package/src/tweaker/tweakModel.ts +2 -2
  47. package/src/tweaker/tweakPlainObject.ts +114 -122
  48. package/src/tweaker/typeChecking.ts +10 -1
  49. package/src/types/TypeCheckError.ts +23 -5
  50. package/src/types/TypeChecker.ts +261 -15
  51. package/src/types/arrayBased/typesArray.ts +38 -40
  52. package/src/types/arrayBased/typesTuple.ts +51 -34
  53. package/src/types/createCachedTypeCheck.ts +181 -0
  54. package/src/types/objectBased/typesArraySet.ts +42 -32
  55. package/src/types/objectBased/typesDataModelData.ts +18 -11
  56. package/src/types/objectBased/typesModel.ts +1 -1
  57. package/src/types/objectBased/typesObject.ts +57 -28
  58. package/src/types/objectBased/typesObjectMap.ts +51 -40
  59. package/src/types/objectBased/typesRecord.ts +59 -39
  60. package/src/types/objectBased/typesRef.ts +1 -1
  61. package/src/types/primitiveBased/typesPrimitive.ts +9 -9
  62. package/src/types/tProp.ts +80 -44
  63. package/src/types/utility/typesOr.ts +35 -24
  64. package/src/types/utility/typesRefinement.ts +21 -8
  65. package/src/types/utility/typesSkipCheck.ts +21 -8
  66. package/src/types/utility/typesTag.ts +21 -9
  67. package/src/types/utility/typesUnchecked.ts +2 -3
  68. package/src/utils/ModelPool.ts +34 -19
  69. package/src/utils/errorDiagnostics.ts +60 -18
  70. package/src/utils/index.ts +9 -7
  71. package/src/types/createPerEntryCachedCheck.ts +0 -166
  72. /package/dist/types/{types/createPerEntryCachedCheck.d.ts → action/mutationBatch.d.ts} +0 -0
@@ -9,26 +9,42 @@ import { applySnapshot } from "../snapshot/applySnapshot"
9
9
  import { getSnapshot } from "../snapshot/getSnapshot"
10
10
  import { assertTweakedObject } from "../tweaker/core"
11
11
 
12
+ export interface ConnectReduxDevToolsOptions {
13
+ /**
14
+ * If it should show the arguments near the action name.
15
+ *
16
+ * @default true
17
+ */
18
+ logArgsNearName?: boolean
19
+
20
+ /**
21
+ * If it should log child actions when they run inside another action tracked
22
+ * by the same target tree.
23
+ *
24
+ * @default true
25
+ */
26
+ logChildActions?: boolean
27
+ }
28
+
12
29
  /**
13
30
  * Connects a tree node to a redux dev tools instance.
14
31
  *
15
32
  * @param remotedevPackage The remotedev package (usually the result of `require("remoteDev")`) (https://www.npmjs.com/package/remotedev).
16
33
  * @param remotedevConnection The result of a connect method from the remotedev package (usually the result of `remoteDev.connectViaExtension(...)`).
17
34
  * @param target Object to use as root.
18
- * @param [options] Optional options object. `logArgsNearName` if it should show the arguments near the action name (default is `true`).
35
+ * @param [options] Optional options object.
19
36
  */
20
37
  export function connectReduxDevTools(
21
38
  remotedevPackage: any,
22
39
  remotedevConnection: any,
23
40
  target: object,
24
- options?: {
25
- logArgsNearName?: boolean
26
- }
41
+ options?: ConnectReduxDevToolsOptions
27
42
  ) {
28
43
  assertTweakedObject(target, "target")
29
44
 
30
45
  const opts = {
31
46
  logArgsNearName: true,
47
+ logChildActions: true,
32
48
  ...options,
33
49
  }
34
50
 
@@ -48,12 +64,15 @@ export function connectReduxDevTools(
48
64
  const actionIdSymbol = Symbol("actionId")
49
65
 
50
66
  actionTrackingMiddleware(target, {
67
+ filter(ctx) {
68
+ return opts.logChildActions || !hasDevToolsTrackedParentContext(ctx)
69
+ },
51
70
  onStart(ctx) {
52
71
  ctx.data[actionIdSymbol] = currentActionId++
53
72
  },
54
73
  onResume(ctx) {
55
74
  // give a chance to the parent to log its own changes before the child starts
56
- if (ctx.parentContext) {
75
+ if (opts.logChildActions && ctx.parentContext) {
57
76
  log(ctx.parentContext, undefined)
58
77
  }
59
78
  log(ctx, undefined)
@@ -184,4 +203,17 @@ export function connectReduxDevTools(
184
203
 
185
204
  return name
186
205
  }
206
+
207
+ function hasDevToolsTrackedParentContext(ctx: SimpleActionContext) {
208
+ let parentContext = ctx.parentContext
209
+
210
+ while (parentContext) {
211
+ if (parentContext.data[actionIdSymbol] !== undefined) {
212
+ return true
213
+ }
214
+ parentContext = parentContext.parentContext
215
+ }
216
+
217
+ return false
218
+ }
187
219
  }
@@ -1,21 +1,24 @@
1
- import { observable } from "mobx"
2
1
  import { tweakArray } from "../tweaker/tweakArray"
3
2
  import { isArray } from "../utils"
4
- import { withErrorPathSegment } from "../utils/errorDiagnostics"
5
- import {
6
- type FromSnapshotContext,
7
- internalFromSnapshot,
8
- observableOptions,
9
- registerSnapshotter,
10
- } from "./fromSnapshot"
3
+ import { getCurrentErrorDiagnosticsContext } from "../utils/errorDiagnostics"
4
+ import { type FromSnapshotContext, internalFromSnapshot, registerSnapshotter } from "./fromSnapshot"
11
5
  import type { SnapshotInOfObject } from "./SnapshotOf"
12
6
  import { SnapshotterAndReconcilerPriority } from "./SnapshotterAndReconcilerPriority"
13
7
 
14
8
  function fromArraySnapshot(sn: SnapshotInOfObject<any>, ctx: FromSnapshotContext): any[] {
15
- const arr = observable.array([] as any[], observableOptions)
16
9
  const ln = sn.length
10
+ const arr: any[] = new Array(ln)
11
+ // Hydration visits every slot. Keep this direct stack use rather than
12
+ // withErrorPathSegment: it avoids one callback closure per item and has a
13
+ // measured production hydration win.
14
+ const errorDiagnosticsContext = getCurrentErrorDiagnosticsContext()
17
15
  for (let i = 0; i < ln; i++) {
18
- arr.push(withErrorPathSegment(i, () => internalFromSnapshot(sn[i], ctx)))
16
+ errorDiagnosticsContext?.pushPath(i)
17
+ try {
18
+ arr[i] = internalFromSnapshot(sn[i], ctx)
19
+ } finally {
20
+ errorDiagnosticsContext?.popPath()
21
+ }
19
22
  }
20
23
  return tweakArray(arr, undefined, true)
21
24
  }
@@ -5,7 +5,7 @@ import { modelTypeKey } from "../model/metadata"
5
5
  import { getModelOrSnapshotTypeAndId, getSnapshotModelType } from "../model/utils"
6
6
  import type { ModelClass } from "../modelShared/BaseModelShared"
7
7
  import { getModelInfoForName, getModelNotRegisteredErrorMessage } from "../modelShared/modelInfo"
8
- import { withErrorModelTrailEntry } from "../utils/errorDiagnostics"
8
+ import { getCurrentErrorDiagnosticsContext } from "../utils/errorDiagnostics"
9
9
  import { type FromSnapshotContext, registerSnapshotter } from "./fromSnapshot"
10
10
  import type { SnapshotInOfModel } from "./SnapshotOf"
11
11
  import { SnapshotProcessingError } from "./SnapshotProcessingError"
@@ -40,7 +40,12 @@ function fromModelSnapshot(sn: SnapshotInOfModel<AnyModel>, ctx: FromSnapshotCon
40
40
  const modelTypeAndId = getModelOrSnapshotTypeAndId(sn)
41
41
  const modelId = modelTypeAndId?.modelId
42
42
 
43
- return withErrorModelTrailEntry(type, modelId, () => {
43
+ // Hydration constructs every model. Keep this direct stack use rather than
44
+ // withErrorModelTrailEntry: it avoids one callback closure per model and
45
+ // has a measured production hydration win.
46
+ const errorDiagnosticsContext = getCurrentErrorDiagnosticsContext()
47
+ errorDiagnosticsContext?.pushModelTrail(type, modelId)
48
+ try {
44
49
  return new (modelInfo.class as any)(undefined, {
45
50
  snapshotInitialData: {
46
51
  unprocessedSnapshot: sn,
@@ -54,7 +59,9 @@ function fromModelSnapshot(sn: SnapshotInOfModel<AnyModel>, ctx: FromSnapshotCon
54
59
  },
55
60
  generateNewIds: ctx.options.generateNewIds,
56
61
  } satisfies ModelConstructorOptions)
57
- })
62
+ } finally {
63
+ errorDiagnosticsContext?.popModelTrail()
64
+ }
58
65
  }
59
66
 
60
67
  /**
@@ -1,7 +1,7 @@
1
- import { observable, set } from "mobx"
1
+ import { observable } from "mobx"
2
2
  import { tweakPlainObject } from "../tweaker/tweakPlainObject"
3
- import { isPlainObject } from "../utils"
4
- import { withErrorPathSegment } from "../utils/errorDiagnostics"
3
+ import { isPlainObject, setProtoProp } from "../utils"
4
+ import { getCurrentErrorDiagnosticsContext } from "../utils/errorDiagnostics"
5
5
  import {
6
6
  type FromSnapshotContext,
7
7
  internalFromSnapshot,
@@ -12,21 +12,37 @@ import type { SnapshotInOfObject } from "./SnapshotOf"
12
12
  import { SnapshotterAndReconcilerPriority } from "./SnapshotterAndReconcilerPriority"
13
13
 
14
14
  function fromPlainObjectSnapshot(sn: SnapshotInOfObject<any>, ctx: FromSnapshotContext): object {
15
- const plainObj = observable.object({}, undefined, observableOptions)
15
+ const plainObj: Record<string, unknown> = {}
16
+ // Hydration visits every property. Keep this direct stack use rather than
17
+ // withErrorPathSegment: it avoids one callback closure per property and has
18
+ // a measured production hydration win.
19
+ const errorDiagnosticsContext = getCurrentErrorDiagnosticsContext()
16
20
 
17
21
  const snKeys = Object.keys(sn)
18
22
  const snKeysLen = snKeys.length
19
23
  for (let i = 0; i < snKeysLen; i++) {
20
24
  const k = snKeys[i]
21
25
  const v = sn[k]
22
- // setIfDifferent not required
23
- set(
24
- plainObj,
25
- k,
26
- withErrorPathSegment(k, () => internalFromSnapshot(v, ctx))
27
- )
26
+ errorDiagnosticsContext?.pushPath(k)
27
+ let snapshotValue: unknown
28
+ try {
29
+ snapshotValue = internalFromSnapshot(v, ctx)
30
+ } finally {
31
+ errorDiagnosticsContext?.popPath()
32
+ }
33
+ if (k === "__proto__") {
34
+ setProtoProp(plainObj, snapshotValue)
35
+ } else {
36
+ plainObj[k] = snapshotValue
37
+ }
28
38
  }
29
- return tweakPlainObject(plainObj, undefined, undefined, true, false)
39
+ return tweakPlainObject(
40
+ observable.object(plainObj, undefined, observableOptions),
41
+ undefined,
42
+ undefined,
43
+ true,
44
+ false
45
+ )
30
46
  }
31
47
 
32
48
  /**
@@ -1,12 +1,16 @@
1
- import { action, observable, set } from "mobx"
1
+ import { action, observable } from "mobx"
2
2
  import type { AnyModel } from "../model/BaseModel"
3
3
  import { isReservedModelKey } from "../model/metadata"
4
4
  import { resolveStandardTypeNoThrow, resolveTypeChecker } from "../types/resolveTypeChecker"
5
5
  import type { AnyType, TypeToData, TypeToSnapshotIn } from "../types/schemas"
6
6
  import { isLateTypeChecker, TypeChecker } from "../types/TypeChecker"
7
7
  import { resolveCodecSupport } from "../types/utility/typesCodec"
8
- import { isMap, isPrimitive, isSet } from "../utils"
9
- import { runWithErrorDiagnosticsContext, withErrorPathSegment } from "../utils/errorDiagnostics"
8
+ import { isMap, isPrimitive, isSet, setProtoProp } from "../utils"
9
+ import {
10
+ getCurrentErrorDiagnosticsContext,
11
+ runWithErrorDiagnosticsContext,
12
+ } from "../utils/errorDiagnostics"
13
+ import { setModelInitialDataSnapshot } from "./modelInitialData"
10
14
  import { registerDefaultSnapshotters } from "./registerDefaultSnapshotters"
11
15
  import type { SnapshotInOf, SnapshotInOfModel, SnapshotOutOf } from "./SnapshotOf"
12
16
  import { SnapshotProcessingError } from "./SnapshotProcessingError"
@@ -87,9 +91,8 @@ export function fromSnapshot<T>(arg1: any, arg2: any, arg3?: any): T {
87
91
 
88
92
  if (codecSupport.hasCodec) {
89
93
  unprocessedSnapshot = arg2
90
- snapshot = resolveTypeChecker(codecSupport.storedType).fromSnapshotProcessor(
91
- unprocessedSnapshot
92
- )
94
+ const processor = resolveTypeChecker(codecSupport.storedType).getFromSnapshotProcessor()
95
+ snapshot = processor ? processor(unprocessedSnapshot) : unprocessedSnapshot
93
96
  options = arg3
94
97
  const storedValue = fromSnapshotAction(snapshot, unprocessedSnapshot, options)
95
98
  return codecSupport.adapter.toRuntime(storedValue)
@@ -97,7 +100,8 @@ export function fromSnapshot<T>(arg1: any, arg2: any, arg3?: any): T {
97
100
 
98
101
  const typeChecker = resolveTypeChecker(resolvedType)
99
102
  unprocessedSnapshot = arg2
100
- snapshot = typeChecker.fromSnapshotProcessor(unprocessedSnapshot)
103
+ const processor = typeChecker.getFromSnapshotProcessor()
104
+ snapshot = processor ? processor(unprocessedSnapshot) : unprocessedSnapshot
101
105
  options = arg3
102
106
  } else {
103
107
  snapshot = arg1
@@ -178,7 +182,12 @@ function snapshotToInitialData(
178
182
  ctx: FromSnapshotContext,
179
183
  processedSn: SnapshotInOfModel<AnyModel>
180
184
  ): any {
181
- const initialData = observable.object({}, undefined, observableOptions)
185
+ const initialData: Record<string, unknown> = {}
186
+ let allValuesPrimitive = true
187
+ // Model hydration visits every data slot. Keep this direct stack use rather
188
+ // than withErrorPathSegment: it avoids one callback closure per slot and
189
+ // has a measured production hydration win.
190
+ const errorDiagnosticsContext = getCurrentErrorDiagnosticsContext()
182
191
 
183
192
  const processedSnKeys = Object.keys(processedSn)
184
193
  const processedSnKeysLen = processedSnKeys.length
@@ -186,12 +195,24 @@ function snapshotToInitialData(
186
195
  const k = processedSnKeys[i]
187
196
  if (!isReservedModelKey(k)) {
188
197
  const v = processedSn[k]
189
- const snapshotValue = withErrorPathSegment(k, () => internalFromSnapshot(v, ctx))
190
- // setIfDifferent not required
191
- set(initialData, k, snapshotValue)
198
+ errorDiagnosticsContext?.pushPath(k)
199
+ let snapshotValue: unknown
200
+ try {
201
+ snapshotValue = internalFromSnapshot(v, ctx)
202
+ } finally {
203
+ errorDiagnosticsContext?.popPath()
204
+ }
205
+ allValuesPrimitive &&= isPrimitive(snapshotValue)
206
+ if (k === "__proto__") {
207
+ setProtoProp(initialData, snapshotValue)
208
+ } else {
209
+ initialData[k] = snapshotValue
210
+ }
192
211
  }
193
212
  }
194
- return initialData
213
+ const observableInitialData = observable.object(initialData, undefined, observableOptions)
214
+ setModelInitialDataSnapshot(observableInitialData, initialData, allValuesPrimitive)
215
+ return observableInitialData
195
216
  }
196
217
 
197
218
  export const observableOptions = {
@@ -5,6 +5,7 @@ import type { AnyType, TypeToData, TypeToSnapshotOut } from "../types/schemas"
5
5
  import { resolveCodecSupport } from "../types/utility/typesCodec"
6
6
  import { failure, identityFn, isPrimitive } from "../utils"
7
7
  import {
8
+ flushInternalSnapshot,
8
9
  freezeInternalSnapshot,
9
10
  getInternalSnapshot,
10
11
  reportInternalSnapshotObserved,
@@ -48,16 +49,19 @@ export function getSnapshot(...args: [arg1: any] | [arg1: any, arg2: any]): any
48
49
  const storedValue = codecSupport.adapter.toStored(arg2)
49
50
 
50
51
  if (isPrimitive(storedValue)) {
51
- return storedTypeChecker.toSnapshotProcessor(storedValue)
52
+ const processor = storedTypeChecker.getToSnapshotProcessor()
53
+ return processor ? processor(storedValue) : storedValue
52
54
  }
53
55
 
54
56
  const storedTree = isTweakedObject(storedValue, true)
55
57
  ? storedValue
56
58
  : toTreeNode(codecSupport.storedType, storedValue)
57
- return storedTypeChecker.toSnapshotProcessor(getSnapshot(storedTree))
59
+ const storedSnapshot = getSnapshot(storedTree)
60
+ const processor = storedTypeChecker.getToSnapshotProcessor()
61
+ return processor ? processor(storedSnapshot) : storedSnapshot
58
62
  }
59
63
 
60
- toSnapshotProcessor = resolveTypeChecker(arg1).toSnapshotProcessor
64
+ toSnapshotProcessor = resolveTypeChecker(arg1).getToSnapshotProcessor() ?? identityFn
61
65
  nodeOrPrimitive = arg2
62
66
  } else {
63
67
  nodeOrPrimitive = arg1
@@ -74,6 +78,7 @@ export function getSnapshot(...args: [arg1: any] | [arg1: any, arg2: any]): any
74
78
  throw failure("getSnapshot is not supported for this kind of object")
75
79
  }
76
80
 
81
+ flushInternalSnapshot(nodeOrPrimitive, true)
77
82
  freezeInternalSnapshot(snapshot.transformed)
78
83
  reportInternalSnapshotObserved(snapshot)
79
84
  return toSnapshotProcessor(snapshot.transformed)