jotai-state-tree 1.5.0 → 1.6.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.
@@ -1,5 +1,5 @@
1
1
  // src/primitives.ts
2
- function createSimpleType(name, validator, defaultValue) {
2
+ function createSimpleType(name, validator) {
3
3
  return {
4
4
  name,
5
5
  _kind: "simple",
@@ -8,9 +8,6 @@ function createSimpleType(name, validator, defaultValue) {
8
8
  _T: void 0,
9
9
  create(snapshot) {
10
10
  if (snapshot === void 0) {
11
- if (defaultValue !== void 0) {
12
- return defaultValue;
13
- }
14
11
  throw new Error(`[jotai-state-tree] A value of type '${name}' is required`);
15
12
  }
16
13
  if (!validator(snapshot)) {
package/dist/index.d.mts CHANGED
@@ -1,5 +1,5 @@
1
- import { I as ISimpleType, a as IType, b as IIdentifierType, c as IIdentifierNumberType, d as ILiteralType, e as IEnumerationType, f as IFrozenType, M as ModelProperties, g as IModelType, h as MixinConfig, i as IMixin, j as IAnyType, k as IArrayType, l as IMapType, m as IOptionalType, n as IMaybeType, o as IMaybeNullType, p as IUnionType, U as UnionOptions, q as ILateType, r as IAnyModelType, R as ReferenceOptions, s as IReferenceType, t as ISafeReferenceType, u as IRefinementType, v as IDisposer, S as SnapshotIn, w as Instance } from './router-D1t27vXg.mjs';
2
- export { L as CustomTypeOptions, aG as IActionRecorder, aH as IActionRecording, C as IAnyComplexType, D as IAnyMixin, aE as IHistoryEntry, F as IJsonPatch, y as IMSTArray, z as IMSTMap, G as IReversibleJsonPatch, x as IStateTreeNode, aF as ITimeTravelManager, aC as IUndoManager, aD as IUndoManagerOptions, H as IValidationContext, K as IValidationError, J as IValidationResult, A as ModelInstance, E as ModelSelf, aJ as RouteDefinition, aI as RouterModel, B as SnapshotOut, T as applyPatch, O as applySnapshot, aw as cleanupStaleEntries, ax as clearAllRegistries, aa as clone, aq as cloneDeep, aB as createActionRecorder, aK as createRouter, aA as createTimeTravelManager, az as createUndoManager, a8 as destroy, a9 as detach, am as findAll, an as findFirst, as as freeze, a2 as getEnv, ag as getGlobalStore, a4 as getIdentifier, af as getMembers, ar as getOrCreatePath, Y as getParent, $ as getParentOfType, a0 as getPath, a1 as getPathParts, av as getRegistryStats, aj as getRelativePath, X as getRoot, N as getSnapshot, ap as getTreeStats, a3 as getType, _ as hasParent, al as haveSameRoot, a5 as isAlive, ak as isAncestor, at as isFrozen, a6 as isRoot, a7 as isStateTreeNode, ao as isValidReference, W as onAction, ay as onLifecycleChange, Q as onPatch, P as onSnapshot, V as recordPatches, ai as resetGlobalStore, ae as resolveIdentifier, ac as resolvePath, ah as setGlobalStore, Z as tryGetParent, ad as tryResolve, au as unfreeze, ab as walk } from './router-D1t27vXg.mjs';
1
+ import { I as ILiteralType, a as IEnumerationType, b as IFrozenType, c as IType, d as ISimpleType, e as IIdentifierType, f as IIdentifierNumberType, M as ModelProperties, g as IModelType, h as MixinConfig, i as IMixin, j as IAnyType, k as IArrayType, l as IMapType, m as IOptionalType, n as IMaybeType, o as IMaybeNullType, p as IUnionType, U as UnionOptions, q as ILateType, r as IAnyModelType, R as ReferenceOptions, s as IReferenceType, t as ISafeReferenceType, u as IRefinementType, v as IDisposer, S as SnapshotIn, w as Instance } from './router-DzUdXVV7.mjs';
2
+ export { L as CustomTypeOptions, aG as IActionRecorder, aH as IActionRecording, C as IAnyComplexType, D as IAnyMixin, aE as IHistoryEntry, F as IJsonPatch, y as IMSTArray, z as IMSTMap, G as IReversibleJsonPatch, x as IStateTreeNode, aF as ITimeTravelManager, aC as IUndoManager, aD as IUndoManagerOptions, H as IValidationContext, K as IValidationError, J as IValidationResult, A as ModelInstance, E as ModelSelf, aJ as RouteDefinition, aI as RouterModel, B as SnapshotOut, T as applyPatch, O as applySnapshot, aw as cleanupStaleEntries, ax as clearAllRegistries, aa as clone, aq as cloneDeep, aB as createActionRecorder, aK as createRouter, aA as createTimeTravelManager, az as createUndoManager, a8 as destroy, a9 as detach, am as findAll, an as findFirst, as as freeze, a2 as getEnv, ag as getGlobalStore, a4 as getIdentifier, af as getMembers, ar as getOrCreatePath, Y as getParent, $ as getParentOfType, a0 as getPath, a1 as getPathParts, av as getRegistryStats, aj as getRelativePath, X as getRoot, N as getSnapshot, ap as getTreeStats, a3 as getType, _ as hasParent, al as haveSameRoot, a5 as isAlive, ak as isAncestor, at as isFrozen, a6 as isRoot, a7 as isStateTreeNode, ao as isValidReference, W as onAction, ay as onLifecycleChange, Q as onPatch, P as onSnapshot, V as recordPatches, ai as resetGlobalStore, ae as resolveIdentifier, ac as resolvePath, ah as setGlobalStore, Z as tryGetParent, ad as tryResolve, au as unfreeze, ab as walk } from './router-DzUdXVV7.mjs';
3
3
  import 'jotai/vanilla/internals';
4
4
  import 'jotai';
5
5
  import 'react';
@@ -493,6 +493,14 @@ declare function safeCreate<T extends IAnyType>(type: T, snapshot: unknown, env?
493
493
  * Create an instance with defaults for missing values
494
494
  */
495
495
  declare function createWithDefaults<T extends IAnyType>(type: T, snapshot?: Partial<SnapshotIn<T>>, env?: unknown): Instance<T>;
496
+ /**
497
+ * Check if a type is a refinement type
498
+ */
499
+ declare function isRefinementType(type: unknown): boolean;
500
+ /**
501
+ * Check if a reference is valid, returning the target if valid and undefined otherwise
502
+ */
503
+ declare function tryReference<T>(getter: () => T | null | undefined, checkIfAlive?: boolean): T | undefined;
496
504
 
497
505
  /**
498
506
  * The `types` namespace contains all type constructors.
@@ -593,4 +601,4 @@ declare function typecheck<T>(type: {
593
601
  is(v: unknown): v is T;
594
602
  }, value: unknown): void;
595
603
 
596
- export { DatePrimitive as Date, type DynamicReferenceOptions, IAnyModelType, IAnyType, IArrayType, IDisposer, IEnumerationType, IFrozenType, IIdentifierNumberType, IIdentifierType, ILateType, ILiteralType, IMapType, IMaybeNullType, IMaybeType, type IMiddlewareEvent, type IMiddlewareHandler, IMixin, IModelType, IOptionalType, IReferenceType, IRefinementType, ISafeReferenceType, type ISerializedActionCall, ISimpleType, IType, IUnionType, Instance, MixinConfig, ModelProperties, ReferenceOptions, SnapshotIn, UnionOptions, addMiddleware, applyAction, array, boolean, cast, castToReferenceSnapshot, castToSnapshot, clearModelRegistry, cloneFrozen, compose, createWithDefaults, custom, types as default, dynamicReference, enumeration, escapeJsonPath, finite, float, flow, frozen, getDebugInfo, getIdentifierAttribute, getModelMetadata, getOrCreate, getRegisteredModelNames, getTypeName, getValidationError, hasIdentifier, identifier, identifierNumber, integer, isArrayType, isFrozenType, isIdentifierType, isInstanceOf, isLateType, isLiteralType, isMapType, isModelRegistered, isModelType, isOptionalType, isPrimitiveType, isProtected, isReferenceType, isType, isUnionType, isValidSnapshot, joinJsonPath, late, lateModel, literal, map, maybe, maybeNull, mixin, model, nullType, nullable, number, onModelRegistered, optional, printTree, protect, recordActions, reference, refinement, registerModel, resolveModel, resolveModelAsync, safeCreate, safeDynamicReference, safeReference, snapshotProcessor, splitJsonPath, string, tryResolveModel, typecheck, types, undefinedType, unescapeJsonPath, union, unprotect, unregisterModel };
604
+ export { DatePrimitive as Date, type DynamicReferenceOptions, IAnyModelType, IAnyType, IArrayType, IDisposer, IEnumerationType, IFrozenType, IIdentifierNumberType, IIdentifierType, ILateType, ILiteralType, IMapType, IMaybeNullType, IMaybeType, type IMiddlewareEvent, type IMiddlewareHandler, IMixin, IModelType, IOptionalType, IReferenceType, IRefinementType, ISafeReferenceType, type ISerializedActionCall, ISimpleType, IType, IUnionType, Instance, MixinConfig, ModelProperties, ReferenceOptions, SnapshotIn, UnionOptions, addMiddleware, applyAction, array, boolean, cast, castToReferenceSnapshot, castToSnapshot, clearModelRegistry, cloneFrozen, compose, createWithDefaults, custom, types as default, dynamicReference, enumeration, escapeJsonPath, finite, float, flow, frozen, getDebugInfo, getIdentifierAttribute, getModelMetadata, getOrCreate, getRegisteredModelNames, getTypeName, getValidationError, hasIdentifier, identifier, identifierNumber, integer, isArrayType, isFrozenType, isIdentifierType, isInstanceOf, isLateType, isLiteralType, isMapType, isModelRegistered, isModelType, isOptionalType, isPrimitiveType, isProtected, isReferenceType, isRefinementType, isType, isUnionType, isValidSnapshot, joinJsonPath, late, lateModel, literal, map, maybe, maybeNull, mixin, model, nullType, nullable, number, onModelRegistered, optional, printTree, protect, recordActions, reference, refinement, registerModel, resolveModel, resolveModelAsync, safeCreate, safeDynamicReference, safeReference, snapshotProcessor, splitJsonPath, string, types as t, tryReference, tryResolveModel, typecheck, types, undefinedType, unescapeJsonPath, union, unprotect, unregisterModel };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { I as ISimpleType, a as IType, b as IIdentifierType, c as IIdentifierNumberType, d as ILiteralType, e as IEnumerationType, f as IFrozenType, M as ModelProperties, g as IModelType, h as MixinConfig, i as IMixin, j as IAnyType, k as IArrayType, l as IMapType, m as IOptionalType, n as IMaybeType, o as IMaybeNullType, p as IUnionType, U as UnionOptions, q as ILateType, r as IAnyModelType, R as ReferenceOptions, s as IReferenceType, t as ISafeReferenceType, u as IRefinementType, v as IDisposer, S as SnapshotIn, w as Instance } from './router-D1t27vXg.js';
2
- export { L as CustomTypeOptions, aG as IActionRecorder, aH as IActionRecording, C as IAnyComplexType, D as IAnyMixin, aE as IHistoryEntry, F as IJsonPatch, y as IMSTArray, z as IMSTMap, G as IReversibleJsonPatch, x as IStateTreeNode, aF as ITimeTravelManager, aC as IUndoManager, aD as IUndoManagerOptions, H as IValidationContext, K as IValidationError, J as IValidationResult, A as ModelInstance, E as ModelSelf, aJ as RouteDefinition, aI as RouterModel, B as SnapshotOut, T as applyPatch, O as applySnapshot, aw as cleanupStaleEntries, ax as clearAllRegistries, aa as clone, aq as cloneDeep, aB as createActionRecorder, aK as createRouter, aA as createTimeTravelManager, az as createUndoManager, a8 as destroy, a9 as detach, am as findAll, an as findFirst, as as freeze, a2 as getEnv, ag as getGlobalStore, a4 as getIdentifier, af as getMembers, ar as getOrCreatePath, Y as getParent, $ as getParentOfType, a0 as getPath, a1 as getPathParts, av as getRegistryStats, aj as getRelativePath, X as getRoot, N as getSnapshot, ap as getTreeStats, a3 as getType, _ as hasParent, al as haveSameRoot, a5 as isAlive, ak as isAncestor, at as isFrozen, a6 as isRoot, a7 as isStateTreeNode, ao as isValidReference, W as onAction, ay as onLifecycleChange, Q as onPatch, P as onSnapshot, V as recordPatches, ai as resetGlobalStore, ae as resolveIdentifier, ac as resolvePath, ah as setGlobalStore, Z as tryGetParent, ad as tryResolve, au as unfreeze, ab as walk } from './router-D1t27vXg.js';
1
+ import { I as ILiteralType, a as IEnumerationType, b as IFrozenType, c as IType, d as ISimpleType, e as IIdentifierType, f as IIdentifierNumberType, M as ModelProperties, g as IModelType, h as MixinConfig, i as IMixin, j as IAnyType, k as IArrayType, l as IMapType, m as IOptionalType, n as IMaybeType, o as IMaybeNullType, p as IUnionType, U as UnionOptions, q as ILateType, r as IAnyModelType, R as ReferenceOptions, s as IReferenceType, t as ISafeReferenceType, u as IRefinementType, v as IDisposer, S as SnapshotIn, w as Instance } from './router-DzUdXVV7.js';
2
+ export { L as CustomTypeOptions, aG as IActionRecorder, aH as IActionRecording, C as IAnyComplexType, D as IAnyMixin, aE as IHistoryEntry, F as IJsonPatch, y as IMSTArray, z as IMSTMap, G as IReversibleJsonPatch, x as IStateTreeNode, aF as ITimeTravelManager, aC as IUndoManager, aD as IUndoManagerOptions, H as IValidationContext, K as IValidationError, J as IValidationResult, A as ModelInstance, E as ModelSelf, aJ as RouteDefinition, aI as RouterModel, B as SnapshotOut, T as applyPatch, O as applySnapshot, aw as cleanupStaleEntries, ax as clearAllRegistries, aa as clone, aq as cloneDeep, aB as createActionRecorder, aK as createRouter, aA as createTimeTravelManager, az as createUndoManager, a8 as destroy, a9 as detach, am as findAll, an as findFirst, as as freeze, a2 as getEnv, ag as getGlobalStore, a4 as getIdentifier, af as getMembers, ar as getOrCreatePath, Y as getParent, $ as getParentOfType, a0 as getPath, a1 as getPathParts, av as getRegistryStats, aj as getRelativePath, X as getRoot, N as getSnapshot, ap as getTreeStats, a3 as getType, _ as hasParent, al as haveSameRoot, a5 as isAlive, ak as isAncestor, at as isFrozen, a6 as isRoot, a7 as isStateTreeNode, ao as isValidReference, W as onAction, ay as onLifecycleChange, Q as onPatch, P as onSnapshot, V as recordPatches, ai as resetGlobalStore, ae as resolveIdentifier, ac as resolvePath, ah as setGlobalStore, Z as tryGetParent, ad as tryResolve, au as unfreeze, ab as walk } from './router-DzUdXVV7.js';
3
3
  import 'jotai/vanilla/internals';
4
4
  import 'jotai';
5
5
  import 'react';
@@ -493,6 +493,14 @@ declare function safeCreate<T extends IAnyType>(type: T, snapshot: unknown, env?
493
493
  * Create an instance with defaults for missing values
494
494
  */
495
495
  declare function createWithDefaults<T extends IAnyType>(type: T, snapshot?: Partial<SnapshotIn<T>>, env?: unknown): Instance<T>;
496
+ /**
497
+ * Check if a type is a refinement type
498
+ */
499
+ declare function isRefinementType(type: unknown): boolean;
500
+ /**
501
+ * Check if a reference is valid, returning the target if valid and undefined otherwise
502
+ */
503
+ declare function tryReference<T>(getter: () => T | null | undefined, checkIfAlive?: boolean): T | undefined;
496
504
 
497
505
  /**
498
506
  * The `types` namespace contains all type constructors.
@@ -593,4 +601,4 @@ declare function typecheck<T>(type: {
593
601
  is(v: unknown): v is T;
594
602
  }, value: unknown): void;
595
603
 
596
- export { DatePrimitive as Date, type DynamicReferenceOptions, IAnyModelType, IAnyType, IArrayType, IDisposer, IEnumerationType, IFrozenType, IIdentifierNumberType, IIdentifierType, ILateType, ILiteralType, IMapType, IMaybeNullType, IMaybeType, type IMiddlewareEvent, type IMiddlewareHandler, IMixin, IModelType, IOptionalType, IReferenceType, IRefinementType, ISafeReferenceType, type ISerializedActionCall, ISimpleType, IType, IUnionType, Instance, MixinConfig, ModelProperties, ReferenceOptions, SnapshotIn, UnionOptions, addMiddleware, applyAction, array, boolean, cast, castToReferenceSnapshot, castToSnapshot, clearModelRegistry, cloneFrozen, compose, createWithDefaults, custom, types as default, dynamicReference, enumeration, escapeJsonPath, finite, float, flow, frozen, getDebugInfo, getIdentifierAttribute, getModelMetadata, getOrCreate, getRegisteredModelNames, getTypeName, getValidationError, hasIdentifier, identifier, identifierNumber, integer, isArrayType, isFrozenType, isIdentifierType, isInstanceOf, isLateType, isLiteralType, isMapType, isModelRegistered, isModelType, isOptionalType, isPrimitiveType, isProtected, isReferenceType, isType, isUnionType, isValidSnapshot, joinJsonPath, late, lateModel, literal, map, maybe, maybeNull, mixin, model, nullType, nullable, number, onModelRegistered, optional, printTree, protect, recordActions, reference, refinement, registerModel, resolveModel, resolveModelAsync, safeCreate, safeDynamicReference, safeReference, snapshotProcessor, splitJsonPath, string, tryResolveModel, typecheck, types, undefinedType, unescapeJsonPath, union, unprotect, unregisterModel };
604
+ export { DatePrimitive as Date, type DynamicReferenceOptions, IAnyModelType, IAnyType, IArrayType, IDisposer, IEnumerationType, IFrozenType, IIdentifierNumberType, IIdentifierType, ILateType, ILiteralType, IMapType, IMaybeNullType, IMaybeType, type IMiddlewareEvent, type IMiddlewareHandler, IMixin, IModelType, IOptionalType, IReferenceType, IRefinementType, ISafeReferenceType, type ISerializedActionCall, ISimpleType, IType, IUnionType, Instance, MixinConfig, ModelProperties, ReferenceOptions, SnapshotIn, UnionOptions, addMiddleware, applyAction, array, boolean, cast, castToReferenceSnapshot, castToSnapshot, clearModelRegistry, cloneFrozen, compose, createWithDefaults, custom, types as default, dynamicReference, enumeration, escapeJsonPath, finite, float, flow, frozen, getDebugInfo, getIdentifierAttribute, getModelMetadata, getOrCreate, getRegisteredModelNames, getTypeName, getValidationError, hasIdentifier, identifier, identifierNumber, integer, isArrayType, isFrozenType, isIdentifierType, isInstanceOf, isLateType, isLiteralType, isMapType, isModelRegistered, isModelType, isOptionalType, isPrimitiveType, isProtected, isReferenceType, isRefinementType, isType, isUnionType, isValidSnapshot, joinJsonPath, late, lateModel, literal, map, maybe, maybeNull, mixin, model, nullType, nullable, number, onModelRegistered, optional, printTree, protect, recordActions, reference, refinement, registerModel, resolveModel, resolveModelAsync, safeCreate, safeDynamicReference, safeReference, snapshotProcessor, splitJsonPath, string, types as t, tryReference, tryResolveModel, typecheck, types, undefinedType, unescapeJsonPath, union, unprotect, unregisterModel };
package/dist/index.js CHANGED
@@ -102,6 +102,7 @@ __export(index_exports, {
102
102
  isPrimitiveType: () => isPrimitiveType,
103
103
  isProtected: () => isProtected,
104
104
  isReferenceType: () => isReferenceType,
105
+ isRefinementType: () => isRefinementType,
105
106
  isRoot: () => isRoot,
106
107
  isStateTreeNode: () => isStateTreeNode,
107
108
  isType: () => isType,
@@ -145,7 +146,9 @@ __export(index_exports, {
145
146
  snapshotProcessor: () => snapshotProcessor,
146
147
  splitJsonPath: () => splitJsonPath,
147
148
  string: () => string,
149
+ t: () => types,
148
150
  tryGetParent: () => tryGetParent,
151
+ tryReference: () => tryReference,
149
152
  tryResolve: () => tryResolve,
150
153
  tryResolveModel: () => tryResolveModel,
151
154
  typecheck: () => typecheck,
@@ -161,7 +164,7 @@ __export(index_exports, {
161
164
  module.exports = __toCommonJS(index_exports);
162
165
 
163
166
  // src/primitives.ts
164
- function createSimpleType(name, validator, defaultValue) {
167
+ function createSimpleType(name, validator) {
165
168
  return {
166
169
  name,
167
170
  _kind: "simple",
@@ -170,9 +173,6 @@ function createSimpleType(name, validator, defaultValue) {
170
173
  _T: void 0,
171
174
  create(snapshot) {
172
175
  if (snapshot === void 0) {
173
- if (defaultValue !== void 0) {
174
- return defaultValue;
175
- }
176
176
  throw new Error(`[jotai-state-tree] A value of type '${name}' is required`);
177
177
  }
178
178
  if (!validator(snapshot)) {
@@ -2849,14 +2849,12 @@ function array(itemType) {
2849
2849
  var MSTMap = class extends Map {
2850
2850
  constructor(node, valueType, entries) {
2851
2851
  super();
2852
- this.initialized = false;
2853
2852
  this.node = node;
2854
2853
  this.valueType = valueType;
2855
- this.initialized = true;
2856
- if (entries) {
2857
- for (const [key, value] of entries) {
2858
- super.set(key, value);
2859
- }
2854
+ for (const [key, value] of entries) {
2855
+ super.set(key, value);
2856
+ }
2857
+ if (entries.length > 0) {
2860
2858
  this.syncToNode();
2861
2859
  }
2862
2860
  }
@@ -2910,13 +2908,9 @@ var MSTMap = class extends Map {
2910
2908
  }
2911
2909
  // Override mutating methods to sync
2912
2910
  set(key, value) {
2913
- if (this.initialized) {
2914
- this.checkWrite();
2915
- }
2911
+ this.checkWrite();
2916
2912
  super.set(key, value);
2917
- if (this.initialized) {
2918
- this.syncToNode();
2919
- }
2913
+ this.syncToNode();
2920
2914
  return this;
2921
2915
  }
2922
2916
  get(key) {
@@ -2933,23 +2927,17 @@ var MSTMap = class extends Map {
2933
2927
  return super.get(key);
2934
2928
  }
2935
2929
  delete(key) {
2936
- if (this.initialized) {
2937
- this.checkWrite();
2938
- }
2930
+ this.checkWrite();
2939
2931
  const result = super.delete(key);
2940
- if (result && this.initialized) {
2932
+ if (result) {
2941
2933
  this.syncToNode();
2942
2934
  }
2943
2935
  return result;
2944
2936
  }
2945
2937
  clear() {
2946
- if (this.initialized) {
2947
- this.checkWrite();
2948
- }
2938
+ this.checkWrite();
2949
2939
  super.clear();
2950
- if (this.initialized) {
2951
- this.syncToNode();
2952
- }
2940
+ this.syncToNode();
2953
2941
  }
2954
2942
  toJSON() {
2955
2943
  const result = {};
@@ -3461,10 +3449,19 @@ function resolveModelAsync(name, timeout = 3e4) {
3461
3449
  return Promise.resolve(entry.type);
3462
3450
  }
3463
3451
  return new Promise((resolve, reject) => {
3464
- const timeoutId = setTimeout(() => {
3452
+ let timeoutId;
3453
+ const wrappedResolve = (type) => {
3454
+ clearTimeout(timeoutId);
3455
+ resolve(type);
3456
+ };
3457
+ const wrappedReject = (error) => {
3458
+ clearTimeout(timeoutId);
3459
+ reject(error);
3460
+ };
3461
+ timeoutId = setTimeout(() => {
3465
3462
  const pending = pendingResolutions.get(name);
3466
3463
  if (pending) {
3467
- const index = pending.findIndex((p) => p.resolve === resolve);
3464
+ const index = pending.findIndex((p) => p.reject === wrappedReject);
3468
3465
  if (index >= 0) {
3469
3466
  pending.splice(index, 1);
3470
3467
  if (pending.length === 0) {
@@ -3478,14 +3475,6 @@ function resolveModelAsync(name, timeout = 3e4) {
3478
3475
  )
3479
3476
  );
3480
3477
  }, timeout);
3481
- const wrappedResolve = (type) => {
3482
- clearTimeout(timeoutId);
3483
- resolve(type);
3484
- };
3485
- const wrappedReject = (error) => {
3486
- clearTimeout(timeoutId);
3487
- reject(error);
3488
- };
3489
3478
  if (!pendingResolutions.has(name)) {
3490
3479
  pendingResolutions.set(name, []);
3491
3480
  }
@@ -3845,6 +3834,29 @@ function safeCreate(type, snapshot, env) {
3845
3834
  function createWithDefaults(type, snapshot = {}, env) {
3846
3835
  return type.create(snapshot, env);
3847
3836
  }
3837
+ function isRefinementType(type) {
3838
+ return type !== null && typeof type === "object" && "_kind" in type && type._kind === "refinement";
3839
+ }
3840
+ function tryReference(getter, checkIfAlive = true) {
3841
+ try {
3842
+ const node = getter();
3843
+ if (node === void 0 || node === null) {
3844
+ return void 0;
3845
+ }
3846
+ if (hasStateTreeNode(node)) {
3847
+ if (!checkIfAlive) {
3848
+ return node;
3849
+ }
3850
+ return isAlive(node) ? node : void 0;
3851
+ }
3852
+ return void 0;
3853
+ } catch (e) {
3854
+ if (e instanceof Error && e.message.includes("Failed to resolve reference")) {
3855
+ return void 0;
3856
+ }
3857
+ throw e;
3858
+ }
3859
+ }
3848
3860
 
3849
3861
  // src/undo.ts
3850
3862
  var import_jotai3 = require("jotai");
@@ -4850,6 +4862,7 @@ var index_default = types;
4850
4862
  isPrimitiveType,
4851
4863
  isProtected,
4852
4864
  isReferenceType,
4865
+ isRefinementType,
4853
4866
  isRoot,
4854
4867
  isStateTreeNode,
4855
4868
  isType,
@@ -4893,7 +4906,9 @@ var index_default = types;
4893
4906
  snapshotProcessor,
4894
4907
  splitJsonPath,
4895
4908
  string,
4909
+ t,
4896
4910
  tryGetParent,
4911
+ tryReference,
4897
4912
  tryResolve,
4898
4913
  tryResolveModel,
4899
4914
  typecheck,
package/dist/index.mjs CHANGED
@@ -96,20 +96,18 @@ import {
96
96
  union,
97
97
  unprotect,
98
98
  walk
99
- } from "./chunk-MEX2M3XM.mjs";
99
+ } from "./chunk-HHDXRF6H.mjs";
100
100
 
101
101
  // src/map.ts
102
102
  var MSTMap = class extends Map {
103
103
  constructor(node, valueType, entries) {
104
104
  super();
105
- this.initialized = false;
106
105
  this.node = node;
107
106
  this.valueType = valueType;
108
- this.initialized = true;
109
- if (entries) {
110
- for (const [key, value] of entries) {
111
- super.set(key, value);
112
- }
107
+ for (const [key, value] of entries) {
108
+ super.set(key, value);
109
+ }
110
+ if (entries.length > 0) {
113
111
  this.syncToNode();
114
112
  }
115
113
  }
@@ -163,13 +161,9 @@ var MSTMap = class extends Map {
163
161
  }
164
162
  // Override mutating methods to sync
165
163
  set(key, value) {
166
- if (this.initialized) {
167
- this.checkWrite();
168
- }
164
+ this.checkWrite();
169
165
  super.set(key, value);
170
- if (this.initialized) {
171
- this.syncToNode();
172
- }
166
+ this.syncToNode();
173
167
  return this;
174
168
  }
175
169
  get(key) {
@@ -186,23 +180,17 @@ var MSTMap = class extends Map {
186
180
  return super.get(key);
187
181
  }
188
182
  delete(key) {
189
- if (this.initialized) {
190
- this.checkWrite();
191
- }
183
+ this.checkWrite();
192
184
  const result = super.delete(key);
193
- if (result && this.initialized) {
185
+ if (result) {
194
186
  this.syncToNode();
195
187
  }
196
188
  return result;
197
189
  }
198
190
  clear() {
199
- if (this.initialized) {
200
- this.checkWrite();
201
- }
191
+ this.checkWrite();
202
192
  super.clear();
203
- if (this.initialized) {
204
- this.syncToNode();
205
- }
193
+ this.syncToNode();
206
194
  }
207
195
  toJSON() {
208
196
  const result = {};
@@ -362,10 +350,19 @@ function resolveModelAsync(name, timeout = 3e4) {
362
350
  return Promise.resolve(entry.type);
363
351
  }
364
352
  return new Promise((resolve, reject) => {
365
- const timeoutId = setTimeout(() => {
353
+ let timeoutId;
354
+ const wrappedResolve = (type) => {
355
+ clearTimeout(timeoutId);
356
+ resolve(type);
357
+ };
358
+ const wrappedReject = (error) => {
359
+ clearTimeout(timeoutId);
360
+ reject(error);
361
+ };
362
+ timeoutId = setTimeout(() => {
366
363
  const pending = pendingResolutions.get(name);
367
364
  if (pending) {
368
- const index = pending.findIndex((p) => p.resolve === resolve);
365
+ const index = pending.findIndex((p) => p.reject === wrappedReject);
369
366
  if (index >= 0) {
370
367
  pending.splice(index, 1);
371
368
  if (pending.length === 0) {
@@ -379,14 +376,6 @@ function resolveModelAsync(name, timeout = 3e4) {
379
376
  )
380
377
  );
381
378
  }, timeout);
382
- const wrappedResolve = (type) => {
383
- clearTimeout(timeoutId);
384
- resolve(type);
385
- };
386
- const wrappedReject = (error) => {
387
- clearTimeout(timeoutId);
388
- reject(error);
389
- };
390
379
  if (!pendingResolutions.has(name)) {
391
380
  pendingResolutions.set(name, []);
392
381
  }
@@ -746,6 +735,29 @@ function safeCreate(type, snapshot, env) {
746
735
  function createWithDefaults(type, snapshot = {}, env) {
747
736
  return type.create(snapshot, env);
748
737
  }
738
+ function isRefinementType(type) {
739
+ return type !== null && typeof type === "object" && "_kind" in type && type._kind === "refinement";
740
+ }
741
+ function tryReference(getter, checkIfAlive = true) {
742
+ try {
743
+ const node = getter();
744
+ if (node === void 0 || node === null) {
745
+ return void 0;
746
+ }
747
+ if (hasStateTreeNode(node)) {
748
+ if (!checkIfAlive) {
749
+ return node;
750
+ }
751
+ return isAlive(node) ? node : void 0;
752
+ }
753
+ return void 0;
754
+ } catch (e) {
755
+ if (e instanceof Error && e.message.includes("Failed to resolve reference")) {
756
+ return void 0;
757
+ }
758
+ throw e;
759
+ }
760
+ }
749
761
 
750
762
  // src/index.ts
751
763
  var types = {
@@ -926,6 +938,7 @@ export {
926
938
  isPrimitiveType,
927
939
  isProtected,
928
940
  isReferenceType,
941
+ isRefinementType,
929
942
  isRoot,
930
943
  isStateTreeNode,
931
944
  isType,
@@ -969,7 +982,9 @@ export {
969
982
  snapshotProcessor,
970
983
  splitJsonPath,
971
984
  string,
985
+ types as t,
972
986
  tryGetParent,
987
+ tryReference,
973
988
  tryResolve,
974
989
  tryResolveModel,
975
990
  typecheck,
package/dist/react.d.mts CHANGED
@@ -1,6 +1,6 @@
1
1
  import React, { ComponentType, FC, ReactNode } from 'react';
2
- import { ag as getGlobalStore, aD as IUndoManagerOptions, aC as IUndoManager, aF as ITimeTravelManager } from './router-D1t27vXg.mjs';
3
- export { aM as RouterContext, aL as hasStateTreeNode, aN as useRouter } from './router-D1t27vXg.mjs';
2
+ import { ag as getGlobalStore, aD as IUndoManagerOptions, aC as IUndoManager, aF as ITimeTravelManager } from './router-DzUdXVV7.mjs';
3
+ export { aM as RouterContext, aL as hasStateTreeNode, aN as useRouter } from './router-DzUdXVV7.mjs';
4
4
  import 'jotai/vanilla/internals';
5
5
  import 'jotai';
6
6
 
package/dist/react.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import React, { ComponentType, FC, ReactNode } from 'react';
2
- import { ag as getGlobalStore, aD as IUndoManagerOptions, aC as IUndoManager, aF as ITimeTravelManager } from './router-D1t27vXg.js';
3
- export { aM as RouterContext, aL as hasStateTreeNode, aN as useRouter } from './router-D1t27vXg.js';
2
+ import { ag as getGlobalStore, aD as IUndoManagerOptions, aC as IUndoManager, aF as ITimeTravelManager } from './router-DzUdXVV7.js';
3
+ export { aM as RouterContext, aL as hasStateTreeNode, aN as useRouter } from './router-DzUdXVV7.js';
4
4
  import 'jotai/vanilla/internals';
5
5
  import 'jotai';
6
6
 
package/dist/react.js CHANGED
@@ -982,7 +982,7 @@ var import_react = require("react");
982
982
  var import_jotai4 = require("jotai");
983
983
 
984
984
  // src/primitives.ts
985
- function createSimpleType(name, validator, defaultValue) {
985
+ function createSimpleType(name, validator) {
986
986
  return {
987
987
  name,
988
988
  _kind: "simple",
@@ -991,9 +991,6 @@ function createSimpleType(name, validator, defaultValue) {
991
991
  _T: void 0,
992
992
  create(snapshot) {
993
993
  if (snapshot === void 0) {
994
- if (defaultValue !== void 0) {
995
- return defaultValue;
996
- }
997
994
  throw new Error(`[jotai-state-tree] A value of type '${name}' is required`);
998
995
  }
999
996
  if (!validator(snapshot)) {
@@ -2797,10 +2794,7 @@ function useRouter() {
2797
2794
  }
2798
2795
 
2799
2796
  // src/react.ts
2800
- var ObserverTrackingContext = import_react2.default.createContext(null);
2801
2797
  function useObserverTracking() {
2802
- const contextFn = import_react2.default.useContext(ObserverTrackingContext);
2803
- if (contextFn) return contextFn;
2804
2798
  const activeFn = getActiveTrackingFn();
2805
2799
  if (activeFn) {
2806
2800
  return (node) => {
@@ -2817,7 +2811,7 @@ function observer(Component, options) {
2817
2811
  if (options?.forwardRef) {
2818
2812
  ObserverComponent = (0, import_react2.memo)((0, import_react2.forwardRef)((props, ref) => {
2819
2813
  return useObserver(() => {
2820
- if (typeof Component === "function") {
2814
+ if (typeof Component === "function" && !(Component.prototype && Component.prototype.isReactComponent)) {
2821
2815
  return Component(props, ref);
2822
2816
  }
2823
2817
  return import_react2.default.createElement(Component, { ...props, ref });
@@ -2827,7 +2821,7 @@ function observer(Component, options) {
2827
2821
  } else {
2828
2822
  ObserverComponent = (0, import_react2.memo)((props) => {
2829
2823
  return useObserver(() => {
2830
- if (typeof Component === "function") {
2824
+ if (typeof Component === "function" && !(Component.prototype && Component.prototype.isReactComponent)) {
2831
2825
  return Component(props);
2832
2826
  }
2833
2827
  return import_react2.default.createElement(Component, props);
package/dist/react.mjs CHANGED
@@ -12,7 +12,7 @@ import {
12
12
  setActiveTrackingFn,
13
13
  setIsApplyingSnapshotOrPatch,
14
14
  useRouter
15
- } from "./chunk-MEX2M3XM.mjs";
15
+ } from "./chunk-HHDXRF6H.mjs";
16
16
 
17
17
  // src/react.ts
18
18
  import React, {
@@ -28,10 +28,7 @@ import {
28
28
  useAtomValue
29
29
  } from "jotai";
30
30
  import { useHydrateAtoms } from "jotai/utils";
31
- var ObserverTrackingContext = React.createContext(null);
32
31
  function useObserverTracking() {
33
- const contextFn = React.useContext(ObserverTrackingContext);
34
- if (contextFn) return contextFn;
35
32
  const activeFn = getActiveTrackingFn();
36
33
  if (activeFn) {
37
34
  return (node) => {
@@ -48,7 +45,7 @@ function observer(Component, options) {
48
45
  if (options?.forwardRef) {
49
46
  ObserverComponent = memo(forwardRef((props, ref) => {
50
47
  return useObserver(() => {
51
- if (typeof Component === "function") {
48
+ if (typeof Component === "function" && !(Component.prototype && Component.prototype.isReactComponent)) {
52
49
  return Component(props, ref);
53
50
  }
54
51
  return React.createElement(Component, { ...props, ref });
@@ -58,7 +55,7 @@ function observer(Component, options) {
58
55
  } else {
59
56
  ObserverComponent = memo((props) => {
60
57
  return useObserver(() => {
61
- if (typeof Component === "function") {
58
+ if (typeof Component === "function" && !(Component.prototype && Component.prototype.isReactComponent)) {
62
59
  return Component(props);
63
60
  }
64
61
  return React.createElement(Component, props);
@@ -725,4 +725,4 @@ declare function createRouter(config: {
725
725
  declare const RouterContext: React.Context<any>;
726
726
  declare function useRouter(): any;
727
727
 
728
- export { getParentOfType as $, type ModelInstance as A, type SnapshotOut as B, type IAnyComplexType as C, type IAnyMixin as D, type ModelSelf as E, type IJsonPatch as F, type IReversibleJsonPatch as G, type IValidationContext as H, type ISimpleType as I, type IValidationResult as J, type IValidationError as K, type CustomTypeOptions as L, type ModelProperties as M, getSnapshot as N, applySnapshot as O, onSnapshot as P, onPatch as Q, type ReferenceOptions as R, type SnapshotIn as S, applyPatch as T, type UnionOptions as U, recordPatches as V, onAction as W, getRoot as X, getParent as Y, tryGetParent as Z, hasParent as _, type IType as a, getPath as a0, getPathParts as a1, getEnv as a2, getType as a3, getIdentifier as a4, isAlive as a5, isRoot as a6, isStateTreeNode as a7, destroy as a8, detach as a9, createTimeTravelManager as aA, createActionRecorder as aB, type IUndoManager as aC, type IUndoManagerOptions as aD, type IHistoryEntry as aE, type ITimeTravelManager as aF, type IActionRecorder as aG, type IActionRecording as aH, RouterModel as aI, RouteDefinition as aJ, createRouter as aK, hasStateTreeNode as aL, RouterContext as aM, useRouter as aN, clone as aa, walk as ab, resolvePath as ac, tryResolve as ad, resolveIdentifier as ae, getMembers as af, getGlobalStore as ag, setGlobalStore as ah, resetGlobalStore as ai, getRelativePath as aj, isAncestor as ak, haveSameRoot as al, findAll as am, findFirst as an, isValidReference as ao, getTreeStats as ap, cloneDeep as aq, getOrCreatePath as ar, freeze as as, isFrozen as at, unfreeze as au, getRegistryStats as av, cleanupStaleEntries as aw, clearAllRegistries as ax, onLifecycleChange as ay, createUndoManager as az, type IIdentifierType as b, type IIdentifierNumberType as c, type ILiteralType as d, type IEnumerationType as e, type IFrozenType as f, type IModelType as g, type MixinConfig as h, type IMixin as i, type IAnyType as j, type IArrayType as k, type IMapType as l, type IOptionalType as m, type IMaybeType as n, type IMaybeNullType as o, type IUnionType as p, type ILateType as q, type IAnyModelType as r, type IReferenceType as s, type ISafeReferenceType as t, type IRefinementType as u, type IDisposer as v, type Instance as w, type IStateTreeNode as x, type IMSTArray as y, type IMSTMap as z };
728
+ export { getParentOfType as $, type ModelInstance as A, type SnapshotOut as B, type IAnyComplexType as C, type IAnyMixin as D, type ModelSelf as E, type IJsonPatch as F, type IReversibleJsonPatch as G, type IValidationContext as H, type ILiteralType as I, type IValidationResult as J, type IValidationError as K, type CustomTypeOptions as L, type ModelProperties as M, getSnapshot as N, applySnapshot as O, onSnapshot as P, onPatch as Q, type ReferenceOptions as R, type SnapshotIn as S, applyPatch as T, type UnionOptions as U, recordPatches as V, onAction as W, getRoot as X, getParent as Y, tryGetParent as Z, hasParent as _, type IEnumerationType as a, getPath as a0, getPathParts as a1, getEnv as a2, getType as a3, getIdentifier as a4, isAlive as a5, isRoot as a6, isStateTreeNode as a7, destroy as a8, detach as a9, createTimeTravelManager as aA, createActionRecorder as aB, type IUndoManager as aC, type IUndoManagerOptions as aD, type IHistoryEntry as aE, type ITimeTravelManager as aF, type IActionRecorder as aG, type IActionRecording as aH, RouterModel as aI, RouteDefinition as aJ, createRouter as aK, hasStateTreeNode as aL, RouterContext as aM, useRouter as aN, clone as aa, walk as ab, resolvePath as ac, tryResolve as ad, resolveIdentifier as ae, getMembers as af, getGlobalStore as ag, setGlobalStore as ah, resetGlobalStore as ai, getRelativePath as aj, isAncestor as ak, haveSameRoot as al, findAll as am, findFirst as an, isValidReference as ao, getTreeStats as ap, cloneDeep as aq, getOrCreatePath as ar, freeze as as, isFrozen as at, unfreeze as au, getRegistryStats as av, cleanupStaleEntries as aw, clearAllRegistries as ax, onLifecycleChange as ay, createUndoManager as az, type IFrozenType as b, type IType as c, type ISimpleType as d, type IIdentifierType as e, type IIdentifierNumberType as f, type IModelType as g, type MixinConfig as h, type IMixin as i, type IAnyType as j, type IArrayType as k, type IMapType as l, type IOptionalType as m, type IMaybeType as n, type IMaybeNullType as o, type IUnionType as p, type ILateType as q, type IAnyModelType as r, type IReferenceType as s, type ISafeReferenceType as t, type IRefinementType as u, type IDisposer as v, type Instance as w, type IStateTreeNode as x, type IMSTArray as y, type IMSTMap as z };
@@ -725,4 +725,4 @@ declare function createRouter(config: {
725
725
  declare const RouterContext: React.Context<any>;
726
726
  declare function useRouter(): any;
727
727
 
728
- export { getParentOfType as $, type ModelInstance as A, type SnapshotOut as B, type IAnyComplexType as C, type IAnyMixin as D, type ModelSelf as E, type IJsonPatch as F, type IReversibleJsonPatch as G, type IValidationContext as H, type ISimpleType as I, type IValidationResult as J, type IValidationError as K, type CustomTypeOptions as L, type ModelProperties as M, getSnapshot as N, applySnapshot as O, onSnapshot as P, onPatch as Q, type ReferenceOptions as R, type SnapshotIn as S, applyPatch as T, type UnionOptions as U, recordPatches as V, onAction as W, getRoot as X, getParent as Y, tryGetParent as Z, hasParent as _, type IType as a, getPath as a0, getPathParts as a1, getEnv as a2, getType as a3, getIdentifier as a4, isAlive as a5, isRoot as a6, isStateTreeNode as a7, destroy as a8, detach as a9, createTimeTravelManager as aA, createActionRecorder as aB, type IUndoManager as aC, type IUndoManagerOptions as aD, type IHistoryEntry as aE, type ITimeTravelManager as aF, type IActionRecorder as aG, type IActionRecording as aH, RouterModel as aI, RouteDefinition as aJ, createRouter as aK, hasStateTreeNode as aL, RouterContext as aM, useRouter as aN, clone as aa, walk as ab, resolvePath as ac, tryResolve as ad, resolveIdentifier as ae, getMembers as af, getGlobalStore as ag, setGlobalStore as ah, resetGlobalStore as ai, getRelativePath as aj, isAncestor as ak, haveSameRoot as al, findAll as am, findFirst as an, isValidReference as ao, getTreeStats as ap, cloneDeep as aq, getOrCreatePath as ar, freeze as as, isFrozen as at, unfreeze as au, getRegistryStats as av, cleanupStaleEntries as aw, clearAllRegistries as ax, onLifecycleChange as ay, createUndoManager as az, type IIdentifierType as b, type IIdentifierNumberType as c, type ILiteralType as d, type IEnumerationType as e, type IFrozenType as f, type IModelType as g, type MixinConfig as h, type IMixin as i, type IAnyType as j, type IArrayType as k, type IMapType as l, type IOptionalType as m, type IMaybeType as n, type IMaybeNullType as o, type IUnionType as p, type ILateType as q, type IAnyModelType as r, type IReferenceType as s, type ISafeReferenceType as t, type IRefinementType as u, type IDisposer as v, type Instance as w, type IStateTreeNode as x, type IMSTArray as y, type IMSTMap as z };
728
+ export { getParentOfType as $, type ModelInstance as A, type SnapshotOut as B, type IAnyComplexType as C, type IAnyMixin as D, type ModelSelf as E, type IJsonPatch as F, type IReversibleJsonPatch as G, type IValidationContext as H, type ILiteralType as I, type IValidationResult as J, type IValidationError as K, type CustomTypeOptions as L, type ModelProperties as M, getSnapshot as N, applySnapshot as O, onSnapshot as P, onPatch as Q, type ReferenceOptions as R, type SnapshotIn as S, applyPatch as T, type UnionOptions as U, recordPatches as V, onAction as W, getRoot as X, getParent as Y, tryGetParent as Z, hasParent as _, type IEnumerationType as a, getPath as a0, getPathParts as a1, getEnv as a2, getType as a3, getIdentifier as a4, isAlive as a5, isRoot as a6, isStateTreeNode as a7, destroy as a8, detach as a9, createTimeTravelManager as aA, createActionRecorder as aB, type IUndoManager as aC, type IUndoManagerOptions as aD, type IHistoryEntry as aE, type ITimeTravelManager as aF, type IActionRecorder as aG, type IActionRecording as aH, RouterModel as aI, RouteDefinition as aJ, createRouter as aK, hasStateTreeNode as aL, RouterContext as aM, useRouter as aN, clone as aa, walk as ab, resolvePath as ac, tryResolve as ad, resolveIdentifier as ae, getMembers as af, getGlobalStore as ag, setGlobalStore as ah, resetGlobalStore as ai, getRelativePath as aj, isAncestor as ak, haveSameRoot as al, findAll as am, findFirst as an, isValidReference as ao, getTreeStats as ap, cloneDeep as aq, getOrCreatePath as ar, freeze as as, isFrozen as at, unfreeze as au, getRegistryStats as av, cleanupStaleEntries as aw, clearAllRegistries as ax, onLifecycleChange as ay, createUndoManager as az, type IFrozenType as b, type IType as c, type ISimpleType as d, type IIdentifierType as e, type IIdentifierNumberType as f, type IModelType as g, type MixinConfig as h, type IMixin as i, type IAnyType as j, type IArrayType as k, type IMapType as l, type IOptionalType as m, type IMaybeType as n, type IMaybeNullType as o, type IUnionType as p, type ILateType as q, type IAnyModelType as r, type IReferenceType as s, type ISafeReferenceType as t, type IRefinementType as u, type IDisposer as v, type Instance as w, type IStateTreeNode as x, type IMSTArray as y, type IMSTMap as z };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "jotai-state-tree",
3
- "version": "1.5.0",
3
+ "version": "1.6.0",
4
4
  "description": "MobX-State-Tree API compatible library powered by Jotai",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",