@legendapp/state 3.0.0-alpha.1 → 3.0.0-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (327) hide show
  1. package/.DS_Store +0 -0
  2. package/CHANGELOG.md +1 -831
  3. package/LICENSE +1 -21
  4. package/README.md +1 -141
  5. package/as/arrayAsRecord.d.mts +5 -0
  6. package/as/arrayAsRecord.d.ts +5 -0
  7. package/as/arrayAsRecord.js +28 -0
  8. package/as/arrayAsRecord.mjs +26 -0
  9. package/as/arrayAsSet.d.mts +5 -0
  10. package/as/arrayAsSet.d.ts +5 -0
  11. package/as/arrayAsSet.js +13 -0
  12. package/as/arrayAsSet.mjs +11 -0
  13. package/as/arrayAsString.d.mts +5 -0
  14. package/as/arrayAsString.d.ts +5 -0
  15. package/as/arrayAsString.js +13 -0
  16. package/as/arrayAsString.mjs +11 -0
  17. package/as/numberAsString.d.mts +5 -0
  18. package/as/numberAsString.d.ts +5 -0
  19. package/as/numberAsString.js +13 -0
  20. package/as/numberAsString.mjs +11 -0
  21. package/as/recordAsArray.d.mts +5 -0
  22. package/as/recordAsArray.d.ts +5 -0
  23. package/as/recordAsArray.js +25 -0
  24. package/as/recordAsArray.mjs +23 -0
  25. package/as/recordAsString.d.mts +5 -0
  26. package/as/recordAsString.d.ts +5 -0
  27. package/as/recordAsString.js +13 -0
  28. package/as/recordAsString.mjs +11 -0
  29. package/as/setAsArray.d.mts +5 -0
  30. package/as/setAsArray.d.ts +5 -0
  31. package/as/setAsArray.js +13 -0
  32. package/as/setAsArray.mjs +11 -0
  33. package/as/setAsString.d.mts +5 -0
  34. package/as/setAsString.d.ts +5 -0
  35. package/as/setAsString.js +13 -0
  36. package/as/setAsString.mjs +11 -0
  37. package/as/stringAsArray.d.mts +5 -0
  38. package/as/stringAsArray.d.ts +5 -0
  39. package/as/stringAsArray.js +13 -0
  40. package/as/stringAsArray.mjs +11 -0
  41. package/as/stringAsNumber.d.mts +5 -0
  42. package/as/stringAsNumber.d.ts +5 -0
  43. package/as/stringAsNumber.js +16 -0
  44. package/as/stringAsNumber.mjs +14 -0
  45. package/as/stringAsRecord.d.mts +5 -0
  46. package/as/stringAsRecord.d.ts +5 -0
  47. package/as/stringAsRecord.js +15 -0
  48. package/as/stringAsRecord.mjs +13 -0
  49. package/as/stringAsSet.d.mts +5 -0
  50. package/as/stringAsSet.d.ts +5 -0
  51. package/as/stringAsSet.js +13 -0
  52. package/as/stringAsSet.mjs +11 -0
  53. package/babel.d.mts +21 -0
  54. package/babel.d.ts +21 -2
  55. package/babel.js +57 -53
  56. package/babel.mjs +65 -0
  57. package/config/enable$GetSet.js +13 -14
  58. package/config/enable$GetSet.mjs +13 -14
  59. package/config/enableReactComponents.d.mts +9 -0
  60. package/config/enableReactComponents.d.ts +4 -2
  61. package/config/enableReactComponents.js +13 -10
  62. package/config/enableReactComponents.mjs +13 -10
  63. package/config/enableReactNativeComponents.d.mts +22 -0
  64. package/config/enableReactNativeComponents.d.ts +6 -4
  65. package/config/enableReactNativeComponents.js +43 -47
  66. package/config/enableReactNativeComponents.mjs +43 -47
  67. package/config/enableReactTracking.d.mts +7 -0
  68. package/config/enableReactTracking.d.ts +3 -2
  69. package/config/enableReactTracking.js +33 -38
  70. package/config/enableReactTracking.mjs +33 -38
  71. package/config/enableReactUse.d.mts +10 -0
  72. package/config/enableReactUse.d.ts +4 -1
  73. package/config/enableReactUse.js +15 -14
  74. package/config/enableReactUse.mjs +15 -14
  75. package/config/{enable$GetSet.d.ts → enable_GetSet.d.mts} +4 -2
  76. package/config/enable_GetSet.d.ts +10 -0
  77. package/config/enable_PeekAssign.d.mts +10 -0
  78. package/config/enable_PeekAssign.d.ts +4 -2
  79. package/config/enable_PeekAssign.js +13 -14
  80. package/config/enable_PeekAssign.mjs +13 -14
  81. package/helpers/pageHash.d.mts +9 -0
  82. package/helpers/pageHash.d.ts +2 -0
  83. package/helpers/pageHash.js +25 -30
  84. package/helpers/pageHash.mjs +25 -30
  85. package/helpers/pageHashParams.d.mts +9 -0
  86. package/helpers/pageHashParams.d.ts +2 -0
  87. package/helpers/pageHashParams.js +34 -37
  88. package/helpers/pageHashParams.mjs +34 -37
  89. package/helpers/time.d.mts +6 -0
  90. package/helpers/time.d.ts +6 -3
  91. package/helpers/time.js +17 -17
  92. package/helpers/time.mjs +17 -17
  93. package/helpers/trackHistory.d.mts +6 -0
  94. package/helpers/trackHistory.d.ts +4 -2
  95. package/helpers/trackHistory.js +13 -16
  96. package/helpers/trackHistory.mjs +13 -16
  97. package/helpers/undoRedo.d.mts +37 -0
  98. package/helpers/undoRedo.d.ts +5 -3
  99. package/helpers/undoRedo.js +59 -94
  100. package/helpers/undoRedo.mjs +59 -94
  101. package/index.d.mts +404 -0
  102. package/index.d.ts +371 -28
  103. package/index.js +2003 -2164
  104. package/index.mjs +2003 -2164
  105. package/package.json +254 -195
  106. package/persist-plugins/async-storage.d.mts +18 -0
  107. package/persist-plugins/async-storage.d.ts +6 -3
  108. package/persist-plugins/async-storage.js +79 -86
  109. package/persist-plugins/async-storage.mjs +79 -86
  110. package/persist-plugins/indexeddb.d.mts +29 -0
  111. package/persist-plugins/indexeddb.d.ts +6 -3
  112. package/persist-plugins/indexeddb.js +331 -352
  113. package/persist-plugins/indexeddb.mjs +331 -352
  114. package/persist-plugins/local-storage.d.mts +23 -0
  115. package/persist-plugins/local-storage.d.ts +8 -5
  116. package/persist-plugins/local-storage.js +74 -76
  117. package/persist-plugins/local-storage.mjs +74 -76
  118. package/persist-plugins/mmkv.d.mts +18 -0
  119. package/persist-plugins/mmkv.d.ts +6 -3
  120. package/persist-plugins/mmkv.js +82 -86
  121. package/persist-plugins/mmkv.mjs +82 -86
  122. package/react-hooks/createObservableHook.d.mts +5 -0
  123. package/react-hooks/createObservableHook.d.ts +4 -1
  124. package/react-hooks/createObservableHook.js +29 -30
  125. package/react-hooks/createObservableHook.mjs +25 -30
  126. package/react-hooks/useHover.d.mts +5 -0
  127. package/react-hooks/useHover.d.ts +5 -3
  128. package/react-hooks/useHover.js +29 -29
  129. package/react-hooks/useHover.mjs +29 -29
  130. package/react-hooks/useMeasure.d.mts +9 -0
  131. package/react-hooks/useMeasure.d.ts +5 -2
  132. package/react-hooks/useMeasure.js +30 -32
  133. package/react-hooks/useMeasure.mjs +30 -32
  134. package/react-hooks/useObservableNextRouter.d.mts +35 -0
  135. package/react-hooks/useObservableNextRouter.d.ts +9 -7
  136. package/react-hooks/useObservableNextRouter.js +64 -77
  137. package/react-hooks/useObservableNextRouter.mjs +60 -77
  138. package/react.d.mts +157 -0
  139. package/react.d.ts +157 -21
  140. package/react.js +458 -749
  141. package/react.mjs +457 -752
  142. package/sync-plugins/crud.d.mts +54 -0
  143. package/sync-plugins/crud.d.ts +12 -10
  144. package/sync-plugins/crud.js +253 -270
  145. package/sync-plugins/crud.mjs +253 -270
  146. package/sync-plugins/fetch.d.mts +21 -0
  147. package/sync-plugins/fetch.d.ts +7 -4
  148. package/sync-plugins/fetch.js +50 -37
  149. package/sync-plugins/fetch.mjs +50 -37
  150. package/sync-plugins/keel.d.mts +108 -0
  151. package/sync-plugins/keel.d.ts +17 -15
  152. package/sync-plugins/keel.js +229 -462
  153. package/sync-plugins/keel.mjs +227 -464
  154. package/sync-plugins/supabase.d.mts +39 -0
  155. package/sync-plugins/supabase.d.ts +16 -14
  156. package/sync-plugins/supabase.js +128 -128
  157. package/sync-plugins/supabase.mjs +128 -128
  158. package/sync-plugins/tanstack-query.d.mts +14 -0
  159. package/sync-plugins/tanstack-query.d.ts +7 -4
  160. package/sync-plugins/tanstack-query.js +51 -57
  161. package/sync-plugins/tanstack-query.mjs +51 -57
  162. package/sync-plugins/tanstack-react-query.d.mts +8 -0
  163. package/sync-plugins/tanstack-react-query.d.ts +6 -1
  164. package/sync-plugins/tanstack-react-query.js +2 -2
  165. package/sync-plugins/tanstack-react-query.mjs +2 -2
  166. package/sync.d.mts +351 -0
  167. package/sync.d.ts +349 -9
  168. package/sync.js +909 -962
  169. package/sync.mjs +919 -972
  170. package/trace.d.mts +9 -0
  171. package/trace.d.ts +9 -4
  172. package/trace.js +72 -62
  173. package/trace.mjs +72 -62
  174. package/types/babel.d.ts +1 -12
  175. package/babel.js.map +0 -1
  176. package/config/enable$GetSet.js.map +0 -1
  177. package/config/enable$GetSet.mjs.map +0 -1
  178. package/config/enableReactComponents.js.map +0 -1
  179. package/config/enableReactComponents.mjs.map +0 -1
  180. package/config/enableReactNativeComponents.js.map +0 -1
  181. package/config/enableReactNativeComponents.mjs.map +0 -1
  182. package/config/enableReactTracking.js.map +0 -1
  183. package/config/enableReactTracking.mjs.map +0 -1
  184. package/config/enableReactUse.js.map +0 -1
  185. package/config/enableReactUse.mjs.map +0 -1
  186. package/config/enable_PeekAssign.js.map +0 -1
  187. package/config/enable_PeekAssign.mjs.map +0 -1
  188. package/helpers/pageHash.js.map +0 -1
  189. package/helpers/pageHash.mjs.map +0 -1
  190. package/helpers/pageHashParams.js.map +0 -1
  191. package/helpers/pageHashParams.mjs.map +0 -1
  192. package/helpers/time.js.map +0 -1
  193. package/helpers/time.mjs.map +0 -1
  194. package/helpers/trackHistory.js.map +0 -1
  195. package/helpers/trackHistory.mjs.map +0 -1
  196. package/helpers/undoRedo.js.map +0 -1
  197. package/helpers/undoRedo.mjs.map +0 -1
  198. package/history.d.ts +0 -1
  199. package/history.js +0 -24
  200. package/history.js.map +0 -1
  201. package/history.mjs +0 -22
  202. package/history.mjs.map +0 -1
  203. package/index.js.map +0 -1
  204. package/index.mjs.map +0 -1
  205. package/persist-plugins/async-storage.js.map +0 -1
  206. package/persist-plugins/async-storage.mjs.map +0 -1
  207. package/persist-plugins/indexeddb.js.map +0 -1
  208. package/persist-plugins/indexeddb.mjs.map +0 -1
  209. package/persist-plugins/local-storage.js.map +0 -1
  210. package/persist-plugins/local-storage.mjs.map +0 -1
  211. package/persist-plugins/mmkv.js.map +0 -1
  212. package/persist-plugins/mmkv.mjs.map +0 -1
  213. package/react-hooks/createObservableHook.js.map +0 -1
  214. package/react-hooks/createObservableHook.mjs.map +0 -1
  215. package/react-hooks/useHover.js.map +0 -1
  216. package/react-hooks/useHover.mjs.map +0 -1
  217. package/react-hooks/useMeasure.js.map +0 -1
  218. package/react-hooks/useMeasure.mjs.map +0 -1
  219. package/react-hooks/useObservableNextRouter.js.map +0 -1
  220. package/react-hooks/useObservableNextRouter.mjs.map +0 -1
  221. package/react.js.map +0 -1
  222. package/react.mjs.map +0 -1
  223. package/src/ObservableObject.ts +0 -1350
  224. package/src/ObservablePrimitive.ts +0 -62
  225. package/src/babel/index.ts +0 -83
  226. package/src/batching.ts +0 -357
  227. package/src/computed.ts +0 -18
  228. package/src/config/enable$GetSet.ts +0 -30
  229. package/src/config/enableReactComponents.ts +0 -26
  230. package/src/config/enableReactNativeComponents.ts +0 -102
  231. package/src/config/enableReactTracking.ts +0 -62
  232. package/src/config/enableReactUse.ts +0 -32
  233. package/src/config/enable_PeekAssign.ts +0 -31
  234. package/src/config.ts +0 -47
  235. package/src/createObservable.ts +0 -47
  236. package/src/event.ts +0 -26
  237. package/src/globals.ts +0 -235
  238. package/src/helpers/pageHash.ts +0 -41
  239. package/src/helpers/pageHashParams.ts +0 -55
  240. package/src/helpers/time.ts +0 -30
  241. package/src/helpers/trackHistory.ts +0 -29
  242. package/src/helpers/undoRedo.ts +0 -111
  243. package/src/helpers.ts +0 -231
  244. package/src/is.ts +0 -63
  245. package/src/linked.ts +0 -17
  246. package/src/observable.ts +0 -32
  247. package/src/observableInterfaces.ts +0 -151
  248. package/src/observableTypes.ts +0 -232
  249. package/src/observe.ts +0 -89
  250. package/src/old-plugins/firebase.ts +0 -1053
  251. package/src/onChange.ts +0 -146
  252. package/src/persist/configureObservablePersistence.ts +0 -7
  253. package/src/persist/fieldTransformer.ts +0 -149
  254. package/src/persist/observablePersistRemoteFunctionsAdapter.ts +0 -39
  255. package/src/persist/persistObservable.ts +0 -1034
  256. package/src/persist-plugins/async-storage.ts +0 -99
  257. package/src/persist-plugins/indexeddb.ts +0 -439
  258. package/src/persist-plugins/local-storage.ts +0 -86
  259. package/src/persist-plugins/mmkv.ts +0 -91
  260. package/src/proxy.ts +0 -28
  261. package/src/react/Computed.tsx +0 -8
  262. package/src/react/For.tsx +0 -116
  263. package/src/react/Memo.tsx +0 -4
  264. package/src/react/Reactive.tsx +0 -53
  265. package/src/react/Show.tsx +0 -33
  266. package/src/react/Switch.tsx +0 -43
  267. package/src/react/react-globals.ts +0 -3
  268. package/src/react/reactInterfaces.ts +0 -32
  269. package/src/react/reactive-observer.tsx +0 -210
  270. package/src/react/useComputed.ts +0 -36
  271. package/src/react/useEffectOnce.ts +0 -41
  272. package/src/react/useIsMounted.ts +0 -16
  273. package/src/react/useMount.ts +0 -15
  274. package/src/react/useObservable.ts +0 -24
  275. package/src/react/useObservableReducer.ts +0 -52
  276. package/src/react/useObservableState.ts +0 -30
  277. package/src/react/useObserve.ts +0 -54
  278. package/src/react/useObserveEffect.ts +0 -40
  279. package/src/react/usePauseProvider.tsx +0 -16
  280. package/src/react/useSelector.ts +0 -167
  281. package/src/react/useUnmount.ts +0 -8
  282. package/src/react/useWhen.ts +0 -9
  283. package/src/react-hooks/createObservableHook.ts +0 -53
  284. package/src/react-hooks/useHover.ts +0 -40
  285. package/src/react-hooks/useMeasure.ts +0 -48
  286. package/src/react-hooks/useObservableNextRouter.ts +0 -137
  287. package/src/retry.ts +0 -71
  288. package/src/setupTracking.ts +0 -26
  289. package/src/sync/activateSyncedNode.ts +0 -128
  290. package/src/sync/configureObservableSync.ts +0 -7
  291. package/src/sync/persistTypes.ts +0 -216
  292. package/src/sync/syncHelpers.ts +0 -180
  293. package/src/sync/syncObservable.ts +0 -1056
  294. package/src/sync/syncObservableAdapter.ts +0 -31
  295. package/src/sync/syncTypes.ts +0 -189
  296. package/src/sync/synced.ts +0 -21
  297. package/src/sync-plugins/crud.ts +0 -412
  298. package/src/sync-plugins/fetch.ts +0 -80
  299. package/src/sync-plugins/keel.ts +0 -495
  300. package/src/sync-plugins/supabase.ts +0 -249
  301. package/src/sync-plugins/tanstack-query.ts +0 -113
  302. package/src/sync-plugins/tanstack-react-query.ts +0 -12
  303. package/src/trace/traceHelpers.ts +0 -11
  304. package/src/trace/useTraceListeners.ts +0 -34
  305. package/src/trace/useTraceUpdates.ts +0 -24
  306. package/src/trace/useVerifyNotTracking.ts +0 -33
  307. package/src/trace/useVerifyOneRender.ts +0 -10
  308. package/src/trackSelector.ts +0 -52
  309. package/src/tracking.ts +0 -43
  310. package/src/types/babel.d.ts +0 -12
  311. package/src/when.ts +0 -75
  312. package/sync-plugins/crud.js.map +0 -1
  313. package/sync-plugins/crud.mjs.map +0 -1
  314. package/sync-plugins/fetch.js.map +0 -1
  315. package/sync-plugins/fetch.mjs.map +0 -1
  316. package/sync-plugins/keel.js.map +0 -1
  317. package/sync-plugins/keel.mjs.map +0 -1
  318. package/sync-plugins/supabase.js.map +0 -1
  319. package/sync-plugins/supabase.mjs.map +0 -1
  320. package/sync-plugins/tanstack-query.js.map +0 -1
  321. package/sync-plugins/tanstack-query.mjs.map +0 -1
  322. package/sync-plugins/tanstack-react-query.js.map +0 -1
  323. package/sync-plugins/tanstack-react-query.mjs.map +0 -1
  324. package/sync.js.map +0 -1
  325. package/sync.mjs.map +0 -1
  326. package/trace.js.map +0 -1
  327. package/trace.mjs.map +0 -1
package/index.js CHANGED
@@ -1,2456 +1,2296 @@
1
1
  'use strict';
2
2
 
3
- const hasOwnProperty = Object.prototype.hasOwnProperty;
3
+ // src/is.ts
4
+ var hasOwnProperty = Object.prototype.hasOwnProperty;
4
5
  function isArray(obj) {
5
- return Array.isArray(obj);
6
+ return Array.isArray(obj);
6
7
  }
7
8
  function isString(obj) {
8
- return typeof obj === 'string';
9
+ return typeof obj === "string";
9
10
  }
10
11
  function isObject(obj) {
11
- return !!obj && typeof obj === 'object' && !(obj instanceof Date) && !isArray(obj);
12
+ return !!obj && typeof obj === "object" && !(obj instanceof Date) && !isArray(obj);
12
13
  }
13
14
  function isFunction(obj) {
14
- return typeof obj === 'function';
15
+ return typeof obj === "function";
15
16
  }
16
17
  function isPrimitive(arg) {
17
- const type = typeof arg;
18
- return arg !== undefined && (isDate(arg) || (type !== 'object' && type !== 'function'));
18
+ const type = typeof arg;
19
+ return arg !== void 0 && (isDate(arg) || type !== "object" && type !== "function");
19
20
  }
20
21
  function isDate(obj) {
21
- return obj instanceof Date;
22
+ return obj instanceof Date;
22
23
  }
23
24
  function isSymbol(obj) {
24
- return typeof obj === 'symbol';
25
+ return typeof obj === "symbol";
25
26
  }
26
27
  function isBoolean(obj) {
27
- return typeof obj === 'boolean';
28
+ return typeof obj === "boolean";
28
29
  }
29
30
  function isPromise(obj) {
30
- return obj instanceof Promise;
31
+ return obj instanceof Promise;
31
32
  }
32
33
  function isMap(obj) {
33
- return obj instanceof Map;
34
+ return obj instanceof Map;
34
35
  }
35
36
  function isNumber(obj) {
36
- const n = obj;
37
- return n - n < 1;
37
+ const n = obj;
38
+ return n - n < 1;
38
39
  }
39
40
  function isEmpty(obj) {
40
- // Looping and returning false on the first property is faster than Object.keys(obj).length === 0
41
- // https://jsbench.me/qfkqv692c8
42
- if (!obj)
43
- return false;
44
- if (isArray(obj))
45
- return obj.length === 0;
46
- for (const key in obj) {
47
- if (hasOwnProperty.call(obj, key)) {
48
- return false;
49
- }
41
+ if (!obj)
42
+ return false;
43
+ if (isArray(obj))
44
+ return obj.length === 0;
45
+ for (const key in obj) {
46
+ if (hasOwnProperty.call(obj, key)) {
47
+ return false;
50
48
  }
51
- return true;
49
+ }
50
+ return true;
52
51
  }
53
52
  function isNullOrUndefined(value) {
54
- return value === undefined || value === null;
53
+ return value === void 0 || value === null;
55
54
  }
56
- const setPrimitives = new Set(['boolean', 'string', 'number']);
57
- /** @internal */
55
+ var setPrimitives = /* @__PURE__ */ new Set(["boolean", "string", "number"]);
58
56
  function isActualPrimitive(arg) {
59
- return setPrimitives.has(typeof arg);
57
+ return setPrimitives.has(typeof arg);
60
58
  }
61
- /** @internal */
62
59
  function isChildNodeValue(node) {
63
- return !!node.parent;
60
+ return !!node.parent;
64
61
  }
65
62
 
66
- const symbolToPrimitive = Symbol.toPrimitive;
67
- const symbolGetNode = Symbol('getNode');
68
- const symbolDelete = /* @__PURE__ */ Symbol('delete');
69
- const symbolOpaque = Symbol('opaque');
70
- const optimized = Symbol('optimized');
71
- const symbolLinked = Symbol('linked');
72
- const globalState = {
73
- isLoadingLocal: false,
74
- isMerging: false,
75
- isLoadingRemote: false,
76
- activateSyncedNode: undefined,
77
- pendingNodes: new Map(),
78
- dirtyNodes: new Set(),
79
- replacer: undefined,
80
- reviver: undefined,
63
+ // src/globals.ts
64
+ var symbolToPrimitive = Symbol.toPrimitive;
65
+ var symbolGetNode = Symbol("getNode");
66
+ var symbolDelete = /* @__PURE__ */ Symbol("delete");
67
+ var symbolOpaque = Symbol("opaque");
68
+ var optimized = Symbol("optimized");
69
+ var symbolLinked = Symbol("linked");
70
+ var globalState = {
71
+ isLoadingLocal: false,
72
+ isMerging: false,
73
+ isLoadingRemote: false,
74
+ activateSyncedNode: void 0,
75
+ pendingNodes: /* @__PURE__ */ new Map(),
76
+ dirtyNodes: /* @__PURE__ */ new Set(),
77
+ replacer: void 0,
78
+ reviver: void 0
81
79
  };
82
80
  function getPathType(value) {
83
- return isArray(value) ? 'array' : isMap(value) ? 'map' : value instanceof Set ? 'set' : 'object';
81
+ return isArray(value) ? "array" : isMap(value) ? "map" : value instanceof Set ? "set" : "object";
84
82
  }
85
83
  function replacer(key, value) {
86
- if (isMap(value)) {
87
- return {
88
- __LSType: 'Map',
89
- value: Array.from(value.entries()), // or with spread: value: [...value]
90
- };
91
- }
92
- else if (value instanceof Set) {
93
- return {
94
- __LSType: 'Set',
95
- value: Array.from(value), // or with spread: value: [...value]
96
- };
97
- }
98
- else if (globalState.replacer) {
99
- value = globalState.replacer(key, value);
100
- }
101
- return value;
84
+ if (isMap(value)) {
85
+ return {
86
+ __LSType: "Map",
87
+ value: Array.from(value.entries())
88
+ // or with spread: value: [...value]
89
+ };
90
+ } else if (value instanceof Set) {
91
+ return {
92
+ __LSType: "Set",
93
+ value: Array.from(value)
94
+ // or with spread: value: [...value]
95
+ };
96
+ } else if (globalState.replacer) {
97
+ value = globalState.replacer(key, value);
98
+ }
99
+ return value;
102
100
  }
103
- const ISO8601 = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3}Z$/;
101
+ var ISO8601 = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3}Z$/;
104
102
  function reviver(key, value) {
105
- if (value) {
106
- if (typeof value === 'string' && ISO8601.test(value)) {
107
- return new Date(value);
108
- }
109
- if (typeof value === 'object') {
110
- if (value.__LSType === 'Map') {
111
- return new Map(value.value);
112
- }
113
- else if (value.__LSType === 'Set') {
114
- return new Set(value.value);
115
- }
116
- }
117
- if (globalState.reviver) {
118
- value = globalState.reviver(key, value);
119
- }
103
+ if (value) {
104
+ if (typeof value === "string" && ISO8601.test(value)) {
105
+ return new Date(value);
120
106
  }
121
- return value;
107
+ if (typeof value === "object") {
108
+ if (value.__LSType === "Map") {
109
+ return new Map(value.value);
110
+ } else if (value.__LSType === "Set") {
111
+ return new Set(value.value);
112
+ }
113
+ }
114
+ if (globalState.reviver) {
115
+ value = globalState.reviver(key, value);
116
+ }
117
+ }
118
+ return value;
122
119
  }
123
120
  function safeStringify(value) {
124
- return JSON.stringify(value, replacer);
121
+ return JSON.stringify(value, replacer);
125
122
  }
126
123
  function safeParse(value) {
127
- return JSON.parse(value, reviver);
124
+ return JSON.parse(value, reviver);
128
125
  }
129
126
  function clone(value) {
130
- return safeParse(safeStringify(value));
127
+ return safeParse(safeStringify(value));
131
128
  }
132
129
  function isObservable(value$) {
133
- return !!value$ && !!value$[symbolGetNode];
130
+ return !!value$ && !!value$[symbolGetNode];
134
131
  }
135
132
  function getNode(value$) {
136
- return value$ && value$[symbolGetNode];
133
+ return value$ && value$[symbolGetNode];
137
134
  }
138
135
  function isEvent(value$) {
139
- var _a;
140
- return value$ && ((_a = value$[symbolGetNode]) === null || _a === void 0 ? void 0 : _a.isEvent);
136
+ var _a;
137
+ return value$ && ((_a = value$[symbolGetNode]) == null ? void 0 : _a.isEvent);
141
138
  }
142
139
  function setNodeValue(node, newValue) {
143
- var _a, _b, _c;
144
- const parentNode = (_a = node.parent) !== null && _a !== void 0 ? _a : node;
145
- const key = node.parent ? node.key : '_';
146
- const isDelete = newValue === symbolDelete;
147
- if (isDelete)
148
- newValue = undefined;
149
- // Get the value of the parent
150
- const parentValue = node.parent ? ensureNodeValue(parentNode) : parentNode.root;
151
- // Save the previous value first
152
- const prevValue = parentValue[key];
153
- const isFunc = isFunction(newValue);
154
- // Compute newValue if newValue is a function or an observable
155
- newValue = !parentNode.isAssigning && isFunc && !isFunction(prevValue) ? newValue(prevValue) : newValue;
156
- if (!globalState.isMerging ||
157
- isNullOrUndefined(prevValue) ||
158
- isFunction(prevValue) ||
159
- !((_c = (_b = node.parent) === null || _b === void 0 ? void 0 : _b.functions) === null || _c === void 0 ? void 0 : _c.get(key))) {
160
- try {
161
- parentNode.isSetting = (parentNode.isSetting || 0) + 1;
162
- const useMapFn = isMap(parentValue);
163
- // Save the new value
164
- if (isDelete) {
165
- if (useMapFn) {
166
- parentValue.delete(key);
167
- }
168
- else {
169
- delete parentValue[key];
170
- }
171
- }
172
- else {
173
- const useMapFn = isMap(parentValue);
174
- if (useMapFn) {
175
- parentValue.set(key, newValue);
176
- }
177
- else {
178
- parentValue[key] = newValue;
179
- }
180
- }
181
- }
182
- finally {
183
- parentNode.isSetting--;
184
- }
185
- }
186
- return { prevValue, newValue };
187
- }
188
- const arrNodeKeys = [];
140
+ var _a, _b, _c;
141
+ const parentNode = (_a = node.parent) != null ? _a : node;
142
+ const key = node.parent ? node.key : "_";
143
+ const isDelete = newValue === symbolDelete;
144
+ if (isDelete)
145
+ newValue = void 0;
146
+ const parentValue = node.parent ? ensureNodeValue(parentNode) : parentNode.root;
147
+ const prevValue = parentValue[key];
148
+ const isFunc = isFunction(newValue);
149
+ newValue = !parentNode.isAssigning && isFunc && !isFunction(prevValue) ? newValue(prevValue) : newValue;
150
+ if (!globalState.isMerging || isNullOrUndefined(prevValue) || isFunction(prevValue) || !((_c = (_b = node.parent) == null ? void 0 : _b.functions) == null ? void 0 : _c.get(key))) {
151
+ try {
152
+ parentNode.isSetting = (parentNode.isSetting || 0) + 1;
153
+ const useMapFn = isMap(parentValue);
154
+ if (isDelete) {
155
+ if (useMapFn) {
156
+ parentValue.delete(key);
157
+ } else {
158
+ delete parentValue[key];
159
+ }
160
+ } else {
161
+ const useMapFn2 = isMap(parentValue);
162
+ if (useMapFn2) {
163
+ parentValue.set(key, newValue);
164
+ } else {
165
+ parentValue[key] = newValue;
166
+ }
167
+ }
168
+ } finally {
169
+ parentNode.isSetting--;
170
+ }
171
+ }
172
+ return { prevValue, newValue };
173
+ }
174
+ var arrNodeKeys = [];
189
175
  function getNodeValue(node) {
190
- let count = 0;
191
- let n = node;
192
- while (isChildNodeValue(n)) {
193
- arrNodeKeys[count++] = n.key;
194
- n = n.parent;
195
- }
196
- let child = node.root._;
197
- for (let i = count - 1; child && i >= 0; i--) {
198
- const key = arrNodeKeys[i];
199
- child = key !== 'size' && (isMap(child) || child instanceof WeakMap) ? child.get(key) : child[key];
200
- }
201
- return child;
176
+ let count = 0;
177
+ let n = node;
178
+ while (isChildNodeValue(n)) {
179
+ arrNodeKeys[count++] = n.key;
180
+ n = n.parent;
181
+ }
182
+ let child = node.root._;
183
+ for (let i = count - 1; child && i >= 0; i--) {
184
+ const key = arrNodeKeys[i];
185
+ child = key !== "size" && (isMap(child) || child instanceof WeakMap) ? child.get(key) : child[key];
186
+ }
187
+ return child;
202
188
  }
203
189
  function getChildNode(node, key, asFunction) {
204
- var _a, _b;
205
- // Get the child by key
206
- let child = (_a = node.children) === null || _a === void 0 ? void 0 : _a.get(key);
207
- // Create the child node if it doesn't already exist
208
- if (!child) {
209
- child = {
210
- root: node.root,
211
- parent: node,
212
- key,
213
- lazy: true,
214
- numListenersRecursive: 0,
215
- };
216
- // Lookup functions are bound with the child key
217
- if (((_b = node.lazyFn) === null || _b === void 0 ? void 0 : _b.length) === 1) {
218
- asFunction = node.lazyFn.bind(node, key);
219
- }
220
- if (isFunction(asFunction)) {
221
- child = Object.assign(() => { }, child);
222
- child.lazyFn = asFunction;
223
- }
224
- if (!node.children) {
225
- node.children = new Map();
226
- }
227
- node.children.set(key, child);
190
+ var _a, _b;
191
+ let child = (_a = node.children) == null ? void 0 : _a.get(key);
192
+ if (!child) {
193
+ child = {
194
+ root: node.root,
195
+ parent: node,
196
+ key,
197
+ lazy: true,
198
+ numListenersRecursive: 0
199
+ };
200
+ if (((_b = node.lazyFn) == null ? void 0 : _b.length) === 1) {
201
+ asFunction = node.lazyFn.bind(node, key);
228
202
  }
229
- return child;
203
+ if (isFunction(asFunction)) {
204
+ child = Object.assign(() => {
205
+ }, child);
206
+ child.lazyFn = asFunction;
207
+ }
208
+ if (!node.children) {
209
+ node.children = /* @__PURE__ */ new Map();
210
+ }
211
+ node.children.set(key, child);
212
+ }
213
+ return child;
230
214
  }
231
215
  function ensureNodeValue(node) {
232
- let value = getNodeValue(node);
233
- if (!value || isFunction(value)) {
234
- if (isChildNodeValue(node)) {
235
- const parent = ensureNodeValue(node.parent);
236
- value = parent[node.key] = {};
237
- }
238
- else {
239
- value = node.root._ = {};
240
- }
216
+ let value = getNodeValue(node);
217
+ if (!value || isFunction(value)) {
218
+ if (isChildNodeValue(node)) {
219
+ const parent = ensureNodeValue(node.parent);
220
+ value = parent[node.key] = {};
221
+ } else {
222
+ value = node.root._ = {};
241
223
  }
242
- return value;
224
+ }
225
+ return value;
243
226
  }
244
227
  function findIDKey(obj, node) {
245
- var _a, _b;
246
- let idKey = isObservable(obj)
247
- ? undefined
248
- : isObject(obj)
249
- ? 'id' in obj
250
- ? 'id'
251
- : 'key' in obj
252
- ? 'key'
253
- : '_id' in obj
254
- ? '_id'
255
- : '__id' in obj
256
- ? '__id'
257
- : undefined
258
- : undefined;
259
- if (!idKey && node.parent) {
260
- const k = node.key + '_keyExtractor';
261
- const keyExtractor = (_b = (_a = node.functions) === null || _a === void 0 ? void 0 : _a.get(k)) !== null && _b !== void 0 ? _b : getNodeValue(node.parent)[node.key + '_keyExtractor'];
262
- if (keyExtractor && isFunction(keyExtractor)) {
263
- idKey = keyExtractor;
264
- }
228
+ var _a, _b;
229
+ let idKey = isObservable(obj) ? void 0 : isObject(obj) ? "id" in obj ? "id" : "key" in obj ? "key" : "_id" in obj ? "_id" : "__id" in obj ? "__id" : void 0 : void 0;
230
+ if (!idKey && node.parent) {
231
+ const k = node.key + "_keyExtractor";
232
+ const keyExtractor = (_b = (_a = node.functions) == null ? void 0 : _a.get(k)) != null ? _b : getNodeValue(node.parent)[node.key + "_keyExtractor"];
233
+ if (keyExtractor && isFunction(keyExtractor)) {
234
+ idKey = keyExtractor;
265
235
  }
266
- return idKey;
236
+ }
237
+ return idKey;
267
238
  }
268
239
  function extractFunction(node, key, fnOrComputed) {
269
- if (!node.functions) {
270
- node.functions = new Map();
271
- }
272
- node.functions.set(key, fnOrComputed);
240
+ if (!node.functions) {
241
+ node.functions = /* @__PURE__ */ new Map();
242
+ }
243
+ node.functions.set(key, fnOrComputed);
273
244
  }
274
245
  function equals(a, b) {
275
- return a === b || (isDate(a) && isDate(b) && +a === +b);
246
+ return a === b || isDate(a) && isDate(b) && +a === +b;
276
247
  }
277
248
 
249
+ // src/helpers.ts
278
250
  function computeSelector(selector, e, retainObservable) {
279
- let c = selector;
280
- if (!isObservable(c) && isFunction(c)) {
281
- c = e ? c(e) : c();
282
- }
283
- return isObservable(c) && !retainObservable ? c.get() : c;
251
+ let c = selector;
252
+ if (!isObservable(c) && isFunction(c)) {
253
+ c = e ? c(e) : c();
254
+ }
255
+ return isObservable(c) && !retainObservable ? c.get() : c;
284
256
  }
285
257
  function getObservableIndex(value$) {
286
- const node = getNode(value$);
287
- const n = +node.key;
288
- return isNumber(n) ? n : -1;
258
+ const node = getNode(value$);
259
+ const n = +node.key;
260
+ return isNumber(n) ? n : -1;
289
261
  }
290
262
  function opaqueObject(value) {
291
- if (value) {
292
- value[symbolOpaque] = true;
293
- }
294
- return value;
263
+ if (value) {
264
+ value[symbolOpaque] = true;
265
+ }
266
+ return value;
295
267
  }
296
- const getValueAtPathReducer = (o, p) => o && o[p];
297
- function getValueAtPath$1(obj, path) {
298
- return path.reduce(getValueAtPathReducer, obj);
268
+ var getValueAtPathReducer = (o, p) => o && o[p];
269
+ function getValueAtPath(obj, path) {
270
+ return path.reduce(getValueAtPathReducer, obj);
299
271
  }
300
272
  function setAtPath(obj, path, pathTypes, value, mode, fullObj, restore) {
301
- let p = undefined;
302
- let o = obj;
303
- if (path.length > 0) {
304
- let oFull = fullObj;
305
- for (let i = 0; i < path.length; i++) {
306
- p = path[i];
307
- if (o[p] === symbolDelete) {
308
- // If this was previously deleted, restore it
309
- if (oFull) {
310
- o[p] = oFull[p];
311
- restore === null || restore === void 0 ? void 0 : restore(path.slice(0, i + 1), o[p]);
312
- }
313
- return obj;
314
- }
315
- else if (o[p] === undefined && value === undefined && i === path.length - 1) {
316
- // If setting undefined and the key is undefined, no need to initialize or set it
317
- return obj;
318
- }
319
- else if (o[p] === undefined || o[p] === null) {
320
- o[p] = initializePathType(pathTypes[i]);
321
- }
322
- if (i < path.length - 1) {
323
- o = o[p];
324
- if (oFull) {
325
- oFull = oFull[p];
326
- }
327
- }
273
+ let p = void 0;
274
+ let o = obj;
275
+ if (path.length > 0) {
276
+ let oFull = fullObj;
277
+ for (let i = 0; i < path.length; i++) {
278
+ p = path[i];
279
+ if (o[p] === symbolDelete) {
280
+ if (oFull) {
281
+ o[p] = oFull[p];
282
+ restore == null ? void 0 : restore(path.slice(0, i + 1), o[p]);
283
+ }
284
+ return obj;
285
+ } else if (o[p] === void 0 && value === void 0 && i === path.length - 1) {
286
+ return obj;
287
+ } else if (o[p] === void 0 || o[p] === null) {
288
+ o[p] = initializePathType(pathTypes[i]);
289
+ }
290
+ if (i < path.length - 1) {
291
+ o = o[p];
292
+ if (oFull) {
293
+ oFull = oFull[p];
328
294
  }
295
+ }
329
296
  }
330
- // Don't set if the value is the same. This prevents creating a new key
331
- // when setting undefined on an object without this key
332
- if (p === undefined) {
333
- if (mode === 'merge') {
334
- obj = _mergeIntoObservable(obj, value);
335
- }
336
- else {
337
- obj = value;
338
- }
297
+ }
298
+ if (p === void 0) {
299
+ if (mode === "merge") {
300
+ obj = _mergeIntoObservable(obj, value);
301
+ } else {
302
+ obj = value;
339
303
  }
340
- else {
341
- if (mode === 'merge') {
342
- o[p] = _mergeIntoObservable(o[p], value);
343
- }
344
- else if (isMap(o)) {
345
- o.set(p, value);
346
- }
347
- else {
348
- o[p] = value;
349
- }
304
+ } else {
305
+ if (mode === "merge") {
306
+ o[p] = _mergeIntoObservable(o[p], value);
307
+ } else if (isMap(o)) {
308
+ o.set(p, value);
309
+ } else {
310
+ o[p] = value;
350
311
  }
351
- return obj;
312
+ }
313
+ return obj;
352
314
  }
353
315
  function setInObservableAtPath(value$, path, pathTypes, value, mode) {
354
- let o = value$;
355
- let v = value;
356
- for (let i = 0; i < path.length; i++) {
357
- const p = path[i];
358
- if (!o.peek()[p]) {
359
- o[p].set(initializePathType(pathTypes[i]));
360
- }
361
- o = o[p];
362
- v = v[p];
363
- }
364
- if (v === symbolDelete) {
365
- o.delete();
366
- }
367
- // Assign if possible, or set otherwise
368
- else if (mode === 'assign' && o.assign && isObject(o.peek())) {
369
- o.assign(v);
370
- }
371
- else if (mode === 'merge') {
372
- mergeIntoObservable(o, v);
373
- }
374
- else {
375
- o.set(v);
376
- }
316
+ let o = value$;
317
+ let v = value;
318
+ for (let i = 0; i < path.length; i++) {
319
+ const p = path[i];
320
+ if (!o.peek()[p]) {
321
+ o[p].set(initializePathType(pathTypes[i]));
322
+ }
323
+ o = o[p];
324
+ v = v[p];
325
+ }
326
+ if (v === symbolDelete) {
327
+ o.delete();
328
+ } else if (mode === "assign" && o.assign && isObject(o.peek())) {
329
+ o.assign(v);
330
+ } else if (mode === "merge") {
331
+ mergeIntoObservable(o, v);
332
+ } else {
333
+ o.set(v);
334
+ }
377
335
  }
378
336
  function mergeIntoObservable(target, ...sources) {
379
- beginBatch();
380
- globalState.isMerging = true;
381
- for (let i = 0; i < sources.length; i++) {
382
- target = _mergeIntoObservable(target, sources[i]);
383
- }
384
- globalState.isMerging = false;
385
- endBatch();
386
- return target;
337
+ beginBatch();
338
+ globalState.isMerging = true;
339
+ for (let i = 0; i < sources.length; i++) {
340
+ target = _mergeIntoObservable(target, sources[i]);
341
+ }
342
+ globalState.isMerging = false;
343
+ endBatch();
344
+ return target;
387
345
  }
388
346
  function _mergeIntoObservable(target, source) {
389
- var _a;
390
- if (isObservable(source)) {
391
- source = source.peek();
392
- }
393
- const needsSet = isObservable(target);
394
- const targetValue = needsSet ? target.peek() : target;
395
- const isTargetArr = isArray(targetValue);
396
- const isTargetObj = !isTargetArr && isObject(targetValue);
397
- if ((isTargetObj && isObject(source) && !isEmpty(targetValue)) || (isTargetArr && targetValue.length > 0)) {
398
- const keys = Object.keys(source);
399
- for (let i = 0; i < keys.length; i++) {
400
- const key = keys[i];
401
- const sourceValue = source[key];
402
- if (sourceValue === symbolDelete) {
403
- needsSet && ((_a = target[key]) === null || _a === void 0 ? void 0 : _a.delete)
404
- ? target[key].delete()
405
- : delete target[key];
406
- }
407
- else {
408
- const isObj = isObject(sourceValue);
409
- const isArr = !isObj && isArray(sourceValue);
410
- const targetChild = target[key];
411
- if ((isObj || isArr) && targetChild && (needsSet || !isEmpty(targetChild))) {
412
- if (!needsSet && (!targetChild || (isObj ? !isObject(targetChild) : !isArray(targetChild)))) {
413
- target[key] = sourceValue;
414
- }
415
- else {
416
- _mergeIntoObservable(targetChild, sourceValue);
417
- }
418
- }
419
- else {
420
- needsSet
421
- ? targetChild.set(sourceValue)
422
- : (target[key] = sourceValue);
423
- }
424
- }
425
- }
426
- }
427
- else if (source !== undefined) {
428
- needsSet ? target.set(source) : (target = source);
429
- }
430
- return target;
347
+ var _a;
348
+ if (isObservable(source)) {
349
+ source = source.peek();
350
+ }
351
+ const needsSet = isObservable(target);
352
+ const targetValue = needsSet ? target.peek() : target;
353
+ const isTargetArr = isArray(targetValue);
354
+ const isTargetObj = !isTargetArr && isObject(targetValue);
355
+ if (isTargetObj && isObject(source) && !isEmpty(targetValue) || isTargetArr && targetValue.length > 0) {
356
+ const keys = Object.keys(source);
357
+ for (let i = 0; i < keys.length; i++) {
358
+ const key = keys[i];
359
+ const sourceValue = source[key];
360
+ if (sourceValue === symbolDelete) {
361
+ needsSet && ((_a = target[key]) == null ? void 0 : _a.delete) ? target[key].delete() : delete target[key];
362
+ } else {
363
+ const isObj = isObject(sourceValue);
364
+ const isArr = !isObj && isArray(sourceValue);
365
+ const targetChild = target[key];
366
+ if ((isObj || isArr) && targetChild && (needsSet || !isEmpty(targetChild))) {
367
+ if (!needsSet && (!targetChild || (isObj ? !isObject(targetChild) : !isArray(targetChild)))) {
368
+ target[key] = sourceValue;
369
+ } else {
370
+ _mergeIntoObservable(targetChild, sourceValue);
371
+ }
372
+ } else {
373
+ needsSet ? targetChild.set(sourceValue) : target[key] = sourceValue;
374
+ }
375
+ }
376
+ }
377
+ } else if (source !== void 0) {
378
+ needsSet ? target.set(source) : target = source;
379
+ }
380
+ return target;
431
381
  }
432
382
  function constructObjectWithPath(path, pathTypes, value) {
433
- let out;
434
- if (path.length > 0) {
435
- let o = (out = {});
436
- for (let i = 0; i < path.length; i++) {
437
- const p = path[i];
438
- o[p] = i === path.length - 1 ? value : initializePathType(pathTypes[i]);
439
- o = o[p];
440
- }
441
- }
442
- else {
443
- out = value;
383
+ let out;
384
+ if (path.length > 0) {
385
+ let o = out = {};
386
+ for (let i = 0; i < path.length; i++) {
387
+ const p = path[i];
388
+ o[p] = i === path.length - 1 ? value : initializePathType(pathTypes[i]);
389
+ o = o[p];
444
390
  }
445
- return out;
391
+ } else {
392
+ out = value;
393
+ }
394
+ return out;
446
395
  }
447
396
  function deconstructObjectWithPath(path, pathTypes, value) {
448
- let o = value;
449
- for (let i = 0; i < path.length; i++) {
450
- const p = path[i];
451
- o = o ? o[p] : initializePathType(pathTypes[i]);
452
- }
453
- return o;
397
+ let o = value;
398
+ for (let i = 0; i < path.length; i++) {
399
+ const p = path[i];
400
+ o = o ? o[p] : initializePathType(pathTypes[i]);
401
+ }
402
+ return o;
454
403
  }
455
404
  function isObservableValueReady(value) {
456
- return !!value && ((!isObject(value) && !isArray(value)) || !isEmpty(value));
405
+ return !!value && (!isObject(value) && !isArray(value) || !isEmpty(value));
457
406
  }
458
407
  function setSilently(value$, newValue) {
459
- const node = getNode(value$);
460
- return setNodeValue(node, newValue).newValue;
408
+ const node = getNode(value$);
409
+ return setNodeValue(node, newValue).newValue;
461
410
  }
462
411
  function initializePathType(pathType) {
463
- switch (pathType) {
464
- case 'array':
465
- return [];
466
- case 'object':
467
- return {};
468
- case 'map':
469
- return new Map();
470
- case 'set':
471
- return new Set();
472
- }
412
+ switch (pathType) {
413
+ case "array":
414
+ return [];
415
+ case "object":
416
+ return {};
417
+ case "map":
418
+ return /* @__PURE__ */ new Map();
419
+ case "set":
420
+ return /* @__PURE__ */ new Set();
421
+ }
473
422
  }
474
423
  function applyChange(value, change, applyPrevious) {
475
- const { path, valueAtPath, prevAtPath, pathTypes } = change;
476
- return setAtPath(value, path, pathTypes, applyPrevious ? prevAtPath : valueAtPath);
424
+ const { path, valueAtPath, prevAtPath, pathTypes } = change;
425
+ return setAtPath(value, path, pathTypes, applyPrevious ? prevAtPath : valueAtPath);
477
426
  }
478
427
  function applyChanges(value, changes, applyPrevious) {
479
- for (let i = 0; i < changes.length; i++) {
480
- value = applyChange(value, changes[i], applyPrevious);
481
- }
482
- return value;
428
+ for (let i = 0; i < changes.length; i++) {
429
+ value = applyChange(value, changes[i], applyPrevious);
430
+ }
431
+ return value;
483
432
  }
484
433
 
485
- let timeout;
486
- let numInBatch = 0;
487
- let isRunningBatch = false;
488
- let didDelayEndBatch = false;
489
- let _batchMap = new Map();
434
+ // src/batching.ts
435
+ var timeout;
436
+ var numInBatch = 0;
437
+ var isRunningBatch = false;
438
+ var didDelayEndBatch = false;
439
+ var _batchMap = /* @__PURE__ */ new Map();
490
440
  function onActionTimeout() {
491
- if (_batchMap.size > 0) {
492
- if (process.env.NODE_ENV === 'development') {
493
- console.error('Forcibly completing observableBatcher because end() was never called. This may be due to an uncaught error between begin() and end().');
494
- }
495
- endBatch(/*force*/ true);
496
- }
441
+ if (_batchMap.size > 0) {
442
+ if (process.env.NODE_ENV === "development") {
443
+ console.error(
444
+ "Forcibly completing observableBatcher because end() was never called. This may be due to an uncaught error between begin() and end()."
445
+ );
446
+ }
447
+ endBatch(
448
+ /*force*/
449
+ true
450
+ );
451
+ }
497
452
  }
498
453
  function isArraySubset(mainArr, subsetArr) {
499
- for (let i = 0; i < mainArr.length; i++) {
500
- if (mainArr[i] !== subsetArr[i]) {
501
- return false;
502
- }
454
+ for (let i = 0; i < mainArr.length; i++) {
455
+ if (mainArr[i] !== subsetArr[i]) {
456
+ return false;
503
457
  }
504
- return true;
458
+ }
459
+ return true;
505
460
  }
506
461
  function createPreviousHandlerInner(value, changes) {
507
- try {
508
- // Clones the current state and inject the previous data at the changed path
509
- return applyChanges(value ? clone(value) : {}, changes, true);
510
- }
511
- catch (_a) {
512
- return undefined;
513
- }
462
+ try {
463
+ return applyChanges(value ? clone(value) : {}, changes, true);
464
+ } catch (e) {
465
+ return void 0;
466
+ }
514
467
  }
515
468
  function createPreviousHandler(value, changes) {
516
- // Create a function that generates the previous state
517
- // We don't want to always do this because cloning is expensive
518
- // so it's better to run on demand.
519
- return function () {
520
- return createPreviousHandlerInner(value, changes);
521
- };
469
+ return function() {
470
+ return createPreviousHandlerInner(value, changes);
471
+ };
522
472
  }
523
473
  function notify(node, value, prev, level, whenOptimizedOnlyIf) {
524
- // Run immediate listeners if there are any
525
- const changesInBatch = new Map();
526
- computeChangesRecursive(changesInBatch, node,
527
- /*loading*/ globalState.isLoadingLocal,
528
- /*remote*/ globalState.isLoadingRemote, value, [], [], value, prev,
529
- /*immediate*/ true, level, whenOptimizedOnlyIf);
530
- if (changesInBatch.size) {
531
- batchNotifyChanges(changesInBatch, /*immediate*/ true);
532
- }
533
- // Update the current batch
534
- const existing = _batchMap.get(node);
535
- if (existing) {
536
- existing.value = value;
537
- // TODO: level, whenOptimizedOnlyIf
538
- }
539
- else {
540
- _batchMap.set(node, {
541
- value,
542
- prev,
543
- level,
544
- whenOptimizedOnlyIf,
545
- remote: globalState.isLoadingRemote,
546
- loading: globalState.isLoadingLocal,
547
- });
548
- }
549
- // If not in a batch run it immediately
550
- if (numInBatch <= 0) {
551
- runBatch();
552
- }
474
+ const changesInBatch = /* @__PURE__ */ new Map();
475
+ computeChangesRecursive(
476
+ changesInBatch,
477
+ node,
478
+ /*loading*/
479
+ globalState.isLoadingLocal,
480
+ /*remote*/
481
+ globalState.isLoadingRemote,
482
+ value,
483
+ [],
484
+ [],
485
+ value,
486
+ prev,
487
+ /*immediate*/
488
+ true,
489
+ level,
490
+ whenOptimizedOnlyIf
491
+ );
492
+ if (changesInBatch.size) {
493
+ batchNotifyChanges(
494
+ changesInBatch,
495
+ /*immediate*/
496
+ true
497
+ );
498
+ }
499
+ const existing = _batchMap.get(node);
500
+ if (existing) {
501
+ existing.value = value;
502
+ } else {
503
+ _batchMap.set(node, {
504
+ value,
505
+ prev,
506
+ level,
507
+ whenOptimizedOnlyIf,
508
+ remote: globalState.isLoadingRemote,
509
+ loading: globalState.isLoadingLocal
510
+ });
511
+ }
512
+ if (numInBatch <= 0) {
513
+ runBatch();
514
+ }
553
515
  }
554
516
  function computeChangesAtNode(changesInBatch, node, loading, remote, value, path, pathTypes, valueAtPath, prevAtPath, immediate, level, whenOptimizedOnlyIf) {
555
- // If there are listeners at this node compute the changes that need to be run
556
- if (immediate ? node.listenersImmediate : node.listeners) {
557
- const change = {
558
- path,
559
- pathTypes,
560
- valueAtPath,
561
- prevAtPath,
562
- };
563
- const changeInBatch = changesInBatch.get(node);
564
- // If the node itself has been changed then we can ignore all the child changes
565
- if (changeInBatch && path.length > 0) {
566
- const { changes } = changeInBatch;
567
- if (!isArraySubset(changes[0].path, change.path)) {
568
- changes.push(change);
569
- }
570
- }
571
- else {
572
- changesInBatch.set(node, {
573
- level,
574
- value,
575
- remote,
576
- loading,
577
- whenOptimizedOnlyIf,
578
- changes: [change],
579
- });
580
- }
581
- }
517
+ if (immediate ? node.listenersImmediate : node.listeners) {
518
+ const change = {
519
+ path,
520
+ pathTypes,
521
+ valueAtPath,
522
+ prevAtPath
523
+ };
524
+ const changeInBatch = changesInBatch.get(node);
525
+ if (changeInBatch && path.length > 0) {
526
+ const { changes } = changeInBatch;
527
+ if (!isArraySubset(changes[0].path, change.path)) {
528
+ changes.push(change);
529
+ }
530
+ } else {
531
+ changesInBatch.set(node, {
532
+ level,
533
+ value,
534
+ remote,
535
+ loading,
536
+ whenOptimizedOnlyIf,
537
+ changes: [change]
538
+ });
539
+ }
540
+ }
582
541
  }
583
542
  function computeChangesRecursive(changesInBatch, node, loading, remote, value, path, pathTypes, valueAtPath, prevAtPath, immediate, level, whenOptimizedOnlyIf) {
584
- // Do the compute at this node
585
- computeChangesAtNode(changesInBatch, node, loading, remote, value, path, pathTypes, valueAtPath, prevAtPath, immediate, level, whenOptimizedOnlyIf);
586
- if (node.linkedFromNodes) {
587
- for (const linkedFromNode of node.linkedFromNodes) {
588
- const childNode = getNodeAtPath(linkedFromNode, path);
589
- computeChangesRecursive(changesInBatch, childNode, loading, remote, valueAtPath, [], [], valueAtPath, prevAtPath, immediate, 0, whenOptimizedOnlyIf);
590
- }
591
- }
592
- // If not root notify up through parents
593
- if (node.parent) {
594
- const parent = node.parent;
595
- if (parent) {
596
- const parentValue = getNodeValue(parent);
597
- computeChangesRecursive(changesInBatch, parent, loading, remote, parentValue, [node.key].concat(path), [getPathType(value)].concat(pathTypes), valueAtPath, prevAtPath, immediate, level + 1, whenOptimizedOnlyIf);
598
- }
599
- }
543
+ computeChangesAtNode(
544
+ changesInBatch,
545
+ node,
546
+ loading,
547
+ remote,
548
+ value,
549
+ path,
550
+ pathTypes,
551
+ valueAtPath,
552
+ prevAtPath,
553
+ immediate,
554
+ level,
555
+ whenOptimizedOnlyIf
556
+ );
557
+ if (node.linkedFromNodes) {
558
+ for (const linkedFromNode of node.linkedFromNodes) {
559
+ const childNode = getNodeAtPath(linkedFromNode, path);
560
+ computeChangesRecursive(
561
+ changesInBatch,
562
+ childNode,
563
+ loading,
564
+ remote,
565
+ valueAtPath,
566
+ [],
567
+ [],
568
+ valueAtPath,
569
+ prevAtPath,
570
+ immediate,
571
+ 0,
572
+ whenOptimizedOnlyIf
573
+ );
574
+ }
575
+ }
576
+ if (node.parent) {
577
+ const parent = node.parent;
578
+ if (parent) {
579
+ const parentValue = getNodeValue(parent);
580
+ computeChangesRecursive(
581
+ changesInBatch,
582
+ parent,
583
+ loading,
584
+ remote,
585
+ parentValue,
586
+ [node.key].concat(path),
587
+ [getPathType(value)].concat(pathTypes),
588
+ valueAtPath,
589
+ prevAtPath,
590
+ immediate,
591
+ level + 1,
592
+ whenOptimizedOnlyIf
593
+ );
594
+ }
595
+ }
600
596
  }
601
597
  function batchNotifyChanges(changesInBatch, immediate) {
602
- const listenersNotified = new Set();
603
- // For each change in the batch, notify all of the listeners
604
- changesInBatch.forEach(({ changes, level, value, loading, remote, whenOptimizedOnlyIf }, node) => {
605
- const listeners = immediate ? node.listenersImmediate : node.listeners;
606
- if (listeners) {
607
- let listenerParams;
608
- // Need to convert to an array here instead of using a for...of loop because listeners can change while iterating
609
- const arr = Array.from(listeners);
610
- for (let i = 0; i < arr.length; i++) {
611
- const listenerFn = arr[i];
612
- const { track, noArgs, listener } = listenerFn;
613
- if (!listenersNotified.has(listener)) {
614
- const ok = track === true ? level <= 0 : track === optimized ? whenOptimizedOnlyIf && level <= 0 : true;
615
- // Notify if listener is not shallow or if this is the first level
616
- if (ok) {
617
- // Create listenerParams if not already created
618
- if (!noArgs && !listenerParams) {
619
- listenerParams = {
620
- value,
621
- loading,
622
- remote,
623
- getPrevious: createPreviousHandler(value, changes),
624
- changes,
625
- };
626
- }
627
- if (!track) {
628
- listenersNotified.add(listener);
629
- }
630
- listener(listenerParams);
631
- }
632
- }
598
+ const listenersNotified = /* @__PURE__ */ new Set();
599
+ changesInBatch.forEach(({ changes, level, value, loading, remote, whenOptimizedOnlyIf }, node) => {
600
+ const listeners = immediate ? node.listenersImmediate : node.listeners;
601
+ if (listeners) {
602
+ let listenerParams;
603
+ const arr = Array.from(listeners);
604
+ for (let i = 0; i < arr.length; i++) {
605
+ const listenerFn = arr[i];
606
+ const { track, noArgs, listener } = listenerFn;
607
+ if (!listenersNotified.has(listener)) {
608
+ const ok = track === true ? level <= 0 : track === optimized ? whenOptimizedOnlyIf && level <= 0 : true;
609
+ if (ok) {
610
+ if (!noArgs && !listenerParams) {
611
+ listenerParams = {
612
+ value,
613
+ loading,
614
+ remote,
615
+ getPrevious: createPreviousHandler(value, changes),
616
+ changes
617
+ };
633
618
  }
619
+ if (!track) {
620
+ listenersNotified.add(listener);
621
+ }
622
+ listener(listenerParams);
623
+ }
634
624
  }
635
- });
625
+ }
626
+ }
627
+ });
636
628
  }
637
629
  function runBatch() {
638
- const dirtyNodes = Array.from(globalState.dirtyNodes);
639
- globalState.dirtyNodes.clear();
640
- dirtyNodes.forEach((node) => {
641
- const dirtyFn = node.dirtyFn;
642
- if (dirtyFn) {
643
- node.dirtyFn = undefined;
644
- dirtyFn();
645
- }
646
- });
647
- // Save batch locally and reset _batchMap first because a new batch could begin while looping over callbacks.
648
- // This can happen with computeds for example.
649
- const map = _batchMap;
650
- _batchMap = new Map();
651
- const changesInBatch = new Map();
652
- // First compute all of the changes at each node. It's important to do this first before
653
- // running all the notifications because createPreviousHandler depends on knowing
654
- // all of the changes happening at the node.
655
- map.forEach(({ value, prev, level, loading, remote, whenOptimizedOnlyIf }, node) => {
656
- computeChangesRecursive(changesInBatch, node, loading, remote, value, [], [], value, prev, false, level, whenOptimizedOnlyIf);
657
- });
658
- // Once all changes are computed, notify all listeners for each node with the computed changes.
659
- if (changesInBatch.size) {
660
- batchNotifyChanges(changesInBatch, false);
661
- }
630
+ const dirtyNodes = Array.from(globalState.dirtyNodes);
631
+ globalState.dirtyNodes.clear();
632
+ dirtyNodes.forEach((node) => {
633
+ const dirtyFn = node.dirtyFn;
634
+ if (dirtyFn) {
635
+ node.dirtyFn = void 0;
636
+ dirtyFn();
637
+ }
638
+ });
639
+ const map = _batchMap;
640
+ _batchMap = /* @__PURE__ */ new Map();
641
+ const changesInBatch = /* @__PURE__ */ new Map();
642
+ map.forEach(({ value, prev, level, loading, remote, whenOptimizedOnlyIf }, node) => {
643
+ computeChangesRecursive(
644
+ changesInBatch,
645
+ node,
646
+ loading,
647
+ remote,
648
+ value,
649
+ [],
650
+ [],
651
+ value,
652
+ prev,
653
+ false,
654
+ level,
655
+ whenOptimizedOnlyIf
656
+ );
657
+ });
658
+ if (changesInBatch.size) {
659
+ batchNotifyChanges(changesInBatch, false);
660
+ }
662
661
  }
663
662
  function batch(fn) {
664
- beginBatch();
665
- try {
666
- fn();
667
- }
668
- finally {
669
- endBatch();
670
- }
663
+ beginBatch();
664
+ try {
665
+ fn();
666
+ } finally {
667
+ endBatch();
668
+ }
671
669
  }
672
670
  function beginBatch() {
673
- numInBatch++;
674
- if (!timeout) {
675
- timeout = setTimeout(onActionTimeout, 0);
676
- }
671
+ numInBatch++;
672
+ if (!timeout) {
673
+ timeout = setTimeout(onActionTimeout, 0);
674
+ }
677
675
  }
678
676
  function endBatch(force) {
679
- numInBatch--;
680
- if (numInBatch <= 0 || force) {
681
- if (isRunningBatch) {
682
- // Don't want to run multiple endBatches recursively, so just note that an endBatch
683
- // was delayed so that the top level endBatch will run endBatch again after it's done.
684
- didDelayEndBatch = true;
685
- }
686
- else {
687
- if (timeout) {
688
- clearTimeout(timeout);
689
- timeout = undefined;
690
- }
691
- numInBatch = 0;
692
- isRunningBatch = true;
693
- runBatch();
694
- isRunningBatch = false;
695
- // If an endBatch was delayed run it now
696
- if (didDelayEndBatch) {
697
- didDelayEndBatch = false;
698
- endBatch(true);
699
- }
700
- }
701
- }
677
+ numInBatch--;
678
+ if (numInBatch <= 0 || force) {
679
+ if (isRunningBatch) {
680
+ didDelayEndBatch = true;
681
+ } else {
682
+ if (timeout) {
683
+ clearTimeout(timeout);
684
+ timeout = void 0;
685
+ }
686
+ numInBatch = 0;
687
+ isRunningBatch = true;
688
+ runBatch();
689
+ isRunningBatch = false;
690
+ if (didDelayEndBatch) {
691
+ didDelayEndBatch = false;
692
+ endBatch(true);
693
+ }
694
+ }
695
+ }
702
696
  }
703
697
  function getNodeAtPath(obj, path) {
704
- let o = obj;
705
- for (let i = 0; i < path.length; i++) {
706
- const p = path[i];
707
- o = getChildNode(o, p);
708
- }
709
- return o;
698
+ let o = obj;
699
+ for (let i = 0; i < path.length; i++) {
700
+ const p = path[i];
701
+ o = getChildNode(o, p);
702
+ }
703
+ return o;
710
704
  }
711
705
 
706
+ // src/linked.ts
712
707
  function linked(params, options) {
713
- if (isFunction(params)) {
714
- params = { get: params };
715
- }
716
- if (options) {
717
- params = { ...params, ...options };
718
- }
719
- const ret = function () {
720
- return { [symbolLinked]: params };
721
- };
722
- ret.prototype[symbolLinked] = params;
723
- return ret;
708
+ if (isFunction(params)) {
709
+ params = { get: params };
710
+ }
711
+ if (options) {
712
+ params = { ...params, ...options };
713
+ }
714
+ const ret = function() {
715
+ return { [symbolLinked]: params };
716
+ };
717
+ ret.prototype[symbolLinked] = params;
718
+ return ret;
724
719
  }
725
720
 
726
- function createObservable(value, makePrimitive, extractPromise, createObject, createPrimitive) {
727
- if (isObservable(value)) {
728
- return value;
729
- }
730
- const valueIsPromise = isPromise(value);
731
- const valueIsFunction = isFunction(value);
732
- const root = {
733
- _: value,
734
- };
735
- let node = {
736
- root,
737
- lazy: true,
738
- numListenersRecursive: 0,
739
- };
740
- if (valueIsFunction) {
741
- node = Object.assign(() => { }, node);
742
- node.lazyFn = value;
743
- }
744
- const prim = makePrimitive || isActualPrimitive(value);
745
- const obs = prim
746
- ? new createPrimitive(node)
747
- : createObject(node);
748
- if (valueIsPromise) {
749
- setNodeValue(node, undefined);
750
- extractPromise(node, value);
751
- }
752
- return obs;
721
+ // src/createObservable.ts
722
+ function createObservable(value, makePrimitive, extractPromise2, createObject, createPrimitive) {
723
+ if (isObservable(value)) {
724
+ return value;
725
+ }
726
+ const valueIsPromise = isPromise(value);
727
+ const valueIsFunction = isFunction(value);
728
+ const root = {
729
+ _: value
730
+ };
731
+ let node = {
732
+ root,
733
+ lazy: true,
734
+ numListenersRecursive: 0
735
+ };
736
+ if (valueIsFunction) {
737
+ node = Object.assign(() => {
738
+ }, node);
739
+ node.lazyFn = value;
740
+ }
741
+ const prim = makePrimitive || isActualPrimitive(value);
742
+ const obs = prim ? new createPrimitive(node) : createObject(node);
743
+ if (valueIsPromise) {
744
+ setNodeValue(node, void 0);
745
+ extractPromise2(node, value);
746
+ }
747
+ return obs;
753
748
  }
754
749
 
750
+ // src/onChange.ts
755
751
  function onChange(node, callback, options = {}, fromLinks) {
756
- var _a;
757
- const { initial, immediate, noArgs } = options;
758
- const { trackingType } = options;
759
- let listeners = immediate ? node.listenersImmediate : node.listeners;
760
- if (!listeners) {
761
- listeners = new Set();
762
- if (immediate) {
763
- node.listenersImmediate = listeners;
764
- }
765
- else {
766
- node.listeners = listeners;
767
- }
768
- }
769
- const listener = {
770
- listener: callback,
771
- track: trackingType,
772
- noArgs,
773
- };
774
- listeners.add(listener);
775
- if (initial) {
776
- const value = getNodeValue(node);
777
- callback({
778
- value,
779
- loading: true,
780
- remote: false,
781
- changes: [
782
- {
783
- path: [],
784
- pathTypes: [],
785
- prevAtPath: value,
786
- valueAtPath: value,
787
- },
788
- ],
789
- getPrevious: () => undefined,
790
- });
791
- }
792
- let extraDisposes;
793
- function addLinkedNodeListeners(childNode, cb = callback, from) {
794
- // Don't add listeners for the same node more than once
795
- if (!(fromLinks === null || fromLinks === void 0 ? void 0 : fromLinks.has(childNode))) {
796
- fromLinks || (fromLinks = new Set());
797
- fromLinks.add(from || node);
798
- cb || (cb = callback);
799
- const childOptions = {
800
- trackingType: true,
801
- ...options,
802
- };
803
- // onChange for the linked node
804
- extraDisposes = [...(extraDisposes || []), onChange(childNode, cb, childOptions, fromLinks)];
805
- }
806
- }
807
- // Add listeners for linked to nodes
808
- if (node.linkedToNode) {
809
- addLinkedNodeListeners(node.linkedToNode);
810
- }
811
- // Add listeners for linked from nodes
812
- (_a = node.linkedFromNodes) === null || _a === void 0 ? void 0 : _a.forEach((linkedFromNode) => addLinkedNodeListeners(linkedFromNode));
813
- // Go up through the parents and add listeners for linked from nodes
814
- node.numListenersRecursive++;
815
- let parent = node.parent;
816
- let pathParent = [node.key];
817
- while (parent) {
818
- if (parent.linkedFromNodes) {
819
- for (const linkedFromNode of parent.linkedFromNodes) {
820
- if (!(fromLinks === null || fromLinks === void 0 ? void 0 : fromLinks.has(linkedFromNode))) {
821
- const cb = createCb(linkedFromNode, pathParent, callback);
822
- addLinkedNodeListeners(linkedFromNode, cb, parent);
823
- }
824
- }
825
- }
826
- parent.numListenersRecursive++;
827
- pathParent = [parent.key, ...pathParent];
828
- parent = parent.parent;
829
- }
830
- return () => {
831
- listeners.delete(listener);
832
- extraDisposes === null || extraDisposes === void 0 ? void 0 : extraDisposes.forEach((fn) => fn());
833
- let parent = node;
834
- while (parent) {
835
- parent.numListenersRecursive--;
836
- parent = parent.parent;
837
- }
838
- };
752
+ var _a;
753
+ const { initial, immediate, noArgs } = options;
754
+ const { trackingType } = options;
755
+ let listeners = immediate ? node.listenersImmediate : node.listeners;
756
+ if (!listeners) {
757
+ listeners = /* @__PURE__ */ new Set();
758
+ if (immediate) {
759
+ node.listenersImmediate = listeners;
760
+ } else {
761
+ node.listeners = listeners;
762
+ }
763
+ }
764
+ const listener = {
765
+ listener: callback,
766
+ track: trackingType,
767
+ noArgs
768
+ };
769
+ listeners.add(listener);
770
+ if (initial) {
771
+ const value = getNodeValue(node);
772
+ callback({
773
+ value,
774
+ loading: true,
775
+ remote: false,
776
+ changes: [
777
+ {
778
+ path: [],
779
+ pathTypes: [],
780
+ prevAtPath: value,
781
+ valueAtPath: value
782
+ }
783
+ ],
784
+ getPrevious: () => void 0
785
+ });
786
+ }
787
+ let extraDisposes;
788
+ function addLinkedNodeListeners(childNode, cb = callback, from) {
789
+ if (!(fromLinks == null ? void 0 : fromLinks.has(childNode))) {
790
+ fromLinks || (fromLinks = /* @__PURE__ */ new Set());
791
+ fromLinks.add(from || node);
792
+ cb || (cb = callback);
793
+ const childOptions = {
794
+ trackingType: true,
795
+ ...options
796
+ };
797
+ extraDisposes = [...extraDisposes || [], onChange(childNode, cb, childOptions, fromLinks)];
798
+ }
799
+ }
800
+ if (node.linkedToNode) {
801
+ addLinkedNodeListeners(node.linkedToNode);
802
+ }
803
+ (_a = node.linkedFromNodes) == null ? void 0 : _a.forEach((linkedFromNode) => addLinkedNodeListeners(linkedFromNode));
804
+ node.numListenersRecursive++;
805
+ let parent = node.parent;
806
+ let pathParent = [node.key];
807
+ while (parent) {
808
+ if (parent.linkedFromNodes) {
809
+ for (const linkedFromNode of parent.linkedFromNodes) {
810
+ if (!(fromLinks == null ? void 0 : fromLinks.has(linkedFromNode))) {
811
+ const cb = createCb(linkedFromNode, pathParent, callback);
812
+ addLinkedNodeListeners(linkedFromNode, cb, parent);
813
+ }
814
+ }
815
+ }
816
+ parent.numListenersRecursive++;
817
+ pathParent = [parent.key, ...pathParent];
818
+ parent = parent.parent;
819
+ }
820
+ return () => {
821
+ listeners.delete(listener);
822
+ extraDisposes == null ? void 0 : extraDisposes.forEach((fn) => fn());
823
+ let parent2 = node;
824
+ while (parent2) {
825
+ parent2.numListenersRecursive--;
826
+ parent2 = parent2.parent;
827
+ }
828
+ };
839
829
  }
840
830
  function createCb(linkedFromNode, path, callback) {
841
- // Create a callback for a path that calls it with the current value at the path
842
- let { valueAtPath: prevAtPath } = getValueAtPath(getNodeValue(linkedFromNode), path);
843
- return function ({ value: valueA, loading, remote }) {
844
- const { valueAtPath } = getValueAtPath(valueA, path);
845
- if (valueAtPath !== prevAtPath) {
846
- callback({
847
- value: valueAtPath,
848
- loading,
849
- remote,
850
- changes: [
851
- {
852
- path: [],
853
- pathTypes: [],
854
- prevAtPath,
855
- valueAtPath,
856
- },
857
- ],
858
- getPrevious: () => prevAtPath,
859
- });
860
- }
861
- prevAtPath = valueAtPath;
862
- };
863
- }
864
- function getValueAtPath(obj, path) {
865
- let o = obj;
866
- const pathTypes = [];
867
- for (let i = 0; o && i < path.length; i++) {
868
- pathTypes.push(isArray(o) ? 'array' : 'object');
869
- const p = path[i];
870
- o = o[p];
871
- }
872
- return { valueAtPath: o, pathTypes };
831
+ let { valueAtPath: prevAtPath } = getValueAtPath2(getNodeValue(linkedFromNode), path);
832
+ return function({ value: valueA, loading, remote }) {
833
+ const { valueAtPath } = getValueAtPath2(valueA, path);
834
+ if (valueAtPath !== prevAtPath) {
835
+ callback({
836
+ value: valueAtPath,
837
+ loading,
838
+ remote,
839
+ changes: [
840
+ {
841
+ path: [],
842
+ pathTypes: [],
843
+ prevAtPath,
844
+ valueAtPath
845
+ }
846
+ ],
847
+ getPrevious: () => prevAtPath
848
+ });
849
+ }
850
+ prevAtPath = valueAtPath;
851
+ };
852
+ }
853
+ function getValueAtPath2(obj, path) {
854
+ let o = obj;
855
+ const pathTypes = [];
856
+ for (let i = 0; o && i < path.length; i++) {
857
+ pathTypes.push(isArray(o) ? "array" : "object");
858
+ const p = path[i];
859
+ o = o[p];
860
+ }
861
+ return { valueAtPath: o, pathTypes };
873
862
  }
874
863
 
864
+ // src/setupTracking.ts
875
865
  function setupTracking(nodes, update, noArgs, immediate) {
876
- let listeners = [];
877
- // Listen to tracked nodes
878
- nodes === null || nodes === void 0 ? void 0 : nodes.forEach((tracked) => {
879
- const { node, track } = tracked;
880
- listeners.push(onChange(node, update, { trackingType: track, immediate, noArgs }));
881
- });
882
- return () => {
883
- if (listeners) {
884
- for (let i = 0; i < listeners.length; i++) {
885
- listeners[i]();
886
- }
887
- listeners = undefined;
888
- }
889
- };
866
+ let listeners = [];
867
+ nodes == null ? void 0 : nodes.forEach((tracked) => {
868
+ const { node, track } = tracked;
869
+ listeners.push(onChange(node, update, { trackingType: track, immediate, noArgs }));
870
+ });
871
+ return () => {
872
+ if (listeners) {
873
+ for (let i = 0; i < listeners.length; i++) {
874
+ listeners[i]();
875
+ }
876
+ listeners = void 0;
877
+ }
878
+ };
890
879
  }
891
880
 
892
- let trackCount = 0;
893
- const trackingQueue = [];
894
- const tracking = {
895
- current: undefined,
881
+ // src/tracking.ts
882
+ var trackCount = 0;
883
+ var trackingQueue = [];
884
+ var tracking = {
885
+ current: void 0
896
886
  };
897
887
  function beginTracking() {
898
- // Keep a copy of the previous tracking context so it can be restored
899
- // when this context is complete
900
- trackingQueue.push(tracking.current);
901
- trackCount++;
902
- tracking.current = {};
888
+ trackingQueue.push(tracking.current);
889
+ trackCount++;
890
+ tracking.current = {};
903
891
  }
904
892
  function endTracking() {
905
- // Restore the previous tracking context
906
- trackCount--;
907
- if (trackCount < 0) {
908
- trackCount = 0;
909
- }
910
- tracking.current = trackingQueue.pop();
893
+ trackCount--;
894
+ if (trackCount < 0) {
895
+ trackCount = 0;
896
+ }
897
+ tracking.current = trackingQueue.pop();
911
898
  }
912
899
  function updateTracking(node, track) {
913
- if (trackCount) {
914
- const tracker = tracking.current;
915
- if (tracker) {
916
- if (!tracker.nodes) {
917
- tracker.nodes = new Map();
918
- }
919
- const existing = tracker.nodes.get(node);
920
- if (existing) {
921
- existing.track = existing.track || track;
922
- existing.num++;
923
- }
924
- else {
925
- tracker.nodes.set(node, { node, track, num: 1 });
926
- }
927
- }
928
- }
900
+ if (trackCount) {
901
+ const tracker = tracking.current;
902
+ if (tracker) {
903
+ if (!tracker.nodes) {
904
+ tracker.nodes = /* @__PURE__ */ new Map();
905
+ }
906
+ const existing = tracker.nodes.get(node);
907
+ if (existing) {
908
+ existing.track = existing.track || track;
909
+ existing.num++;
910
+ } else {
911
+ tracker.nodes.set(node, { node, track, num: 1 });
912
+ }
913
+ }
914
+ }
929
915
  }
930
916
 
917
+ // src/trackSelector.ts
931
918
  function trackSelector(selector, update, observeEvent, observeOptions, createResubscribe) {
932
- var _a;
933
- let dispose;
934
- let resubscribe;
935
- let updateFn = update;
936
- beginTracking();
937
- const value = selector ? computeSelector(selector, observeEvent, observeOptions === null || observeOptions === void 0 ? void 0 : observeOptions.fromComputed) : selector;
938
- const tracker = tracking.current;
939
- const nodes = tracker.nodes;
940
- endTracking();
941
- if ((process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test') && tracker && nodes) {
942
- (_a = tracker.traceListeners) === null || _a === void 0 ? void 0 : _a.call(tracker, nodes);
943
- if (tracker.traceUpdates) {
944
- updateFn = tracker.traceUpdates(update);
945
- }
946
- // Clear tracing so it doesn't leak to other components
947
- tracker.traceListeners = undefined;
948
- tracker.traceUpdates = undefined;
949
- }
950
- if (!(observeEvent === null || observeEvent === void 0 ? void 0 : observeEvent.cancel)) {
951
- // Do tracing if it was requested
952
- // useSyncExternalStore doesn't subscribe until after the component mount.
953
- // We want to subscribe immediately so we don't miss any updates
954
- dispose = setupTracking(nodes, updateFn, false, observeOptions === null || observeOptions === void 0 ? void 0 : observeOptions.immediate);
955
- if (process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test') {
956
- resubscribe = createResubscribe
957
- ? () => {
958
- dispose === null || dispose === void 0 ? void 0 : dispose();
959
- dispose = setupTracking(nodes, updateFn);
960
- return dispose;
961
- }
962
- : undefined;
963
- }
964
- }
965
- return { nodes, value, dispose, resubscribe };
919
+ var _a;
920
+ let dispose;
921
+ let resubscribe;
922
+ let updateFn = update;
923
+ beginTracking();
924
+ const value = selector ? computeSelector(selector, observeEvent, observeOptions == null ? void 0 : observeOptions.fromComputed) : selector;
925
+ const tracker = tracking.current;
926
+ const nodes = tracker.nodes;
927
+ endTracking();
928
+ if ((process.env.NODE_ENV === "development" || process.env.NODE_ENV === "test") && tracker && nodes) {
929
+ (_a = tracker.traceListeners) == null ? void 0 : _a.call(tracker, nodes);
930
+ if (tracker.traceUpdates) {
931
+ updateFn = tracker.traceUpdates(update);
932
+ }
933
+ tracker.traceListeners = void 0;
934
+ tracker.traceUpdates = void 0;
935
+ }
936
+ if (!(observeEvent == null ? void 0 : observeEvent.cancel)) {
937
+ dispose = setupTracking(nodes, updateFn, false, observeOptions == null ? void 0 : observeOptions.immediate);
938
+ if (process.env.NODE_ENV === "development" || process.env.NODE_ENV === "test") {
939
+ resubscribe = createResubscribe ? () => {
940
+ dispose == null ? void 0 : dispose();
941
+ dispose = setupTracking(nodes, updateFn);
942
+ return dispose;
943
+ } : void 0;
944
+ }
945
+ }
946
+ return { nodes, value, dispose, resubscribe };
966
947
  }
967
948
 
949
+ // src/observe.ts
968
950
  function observe(selectorOrRun, reactionOrOptions, options) {
969
- let reaction;
970
- if (isFunction(reactionOrOptions)) {
971
- reaction = reactionOrOptions;
972
- }
973
- else {
974
- options = reactionOrOptions;
975
- }
976
- let dispose;
977
- const e = { num: 0 };
978
- // Wrap it in a function so it doesn't pass all the arguments to run()
979
- const update = function () {
980
- if (e.onCleanup) {
981
- e.onCleanup();
982
- e.onCleanup = undefined;
983
- }
984
- // Run in a batch so changes don't happen until we're done tracking here
985
- beginBatch();
986
- // Run the function/selector
987
- delete e.value;
988
- // Dispose listeners from previous run
989
- dispose === null || dispose === void 0 ? void 0 : dispose();
990
- const { dispose: _dispose, value, nodes } = trackSelector(selectorOrRun, update, e, options);
991
- dispose = _dispose;
992
- e.value = value;
993
- e.nodes = nodes;
994
- e.refresh = update;
995
- if (e.onCleanupReaction) {
996
- e.onCleanupReaction();
997
- e.onCleanupReaction = undefined;
998
- }
999
- endBatch();
1000
- // Call the reaction if there is one and the value changed
1001
- if (reaction &&
1002
- ((options === null || options === void 0 ? void 0 : options.fromComputed) ||
1003
- ((e.num > 0 || !isEvent(selectorOrRun)) &&
1004
- (e.previous !== e.value || typeof e.value === 'object')))) {
1005
- reaction(e);
1006
- }
1007
- // Update the previous value
1008
- e.previous = e.value;
1009
- // Increment the counter
1010
- e.num++;
1011
- };
1012
- update();
1013
- // Return function calling dispose because dispose may be changed in update()
1014
- return () => {
1015
- var _a, _b;
1016
- (_a = e.onCleanup) === null || _a === void 0 ? void 0 : _a.call(e);
1017
- e.onCleanup = undefined;
1018
- (_b = e.onCleanupReaction) === null || _b === void 0 ? void 0 : _b.call(e);
1019
- e.onCleanupReaction = undefined;
1020
- dispose === null || dispose === void 0 ? void 0 : dispose();
1021
- };
951
+ let reaction;
952
+ if (isFunction(reactionOrOptions)) {
953
+ reaction = reactionOrOptions;
954
+ } else {
955
+ options = reactionOrOptions;
956
+ }
957
+ let dispose;
958
+ const e = { num: 0 };
959
+ const update = function() {
960
+ if (e.onCleanup) {
961
+ e.onCleanup();
962
+ e.onCleanup = void 0;
963
+ }
964
+ beginBatch();
965
+ delete e.value;
966
+ dispose == null ? void 0 : dispose();
967
+ const { dispose: _dispose, value, nodes } = trackSelector(selectorOrRun, update, e, options);
968
+ dispose = _dispose;
969
+ e.value = value;
970
+ e.nodes = nodes;
971
+ e.refresh = update;
972
+ if (e.onCleanupReaction) {
973
+ e.onCleanupReaction();
974
+ e.onCleanupReaction = void 0;
975
+ }
976
+ endBatch();
977
+ if (reaction && ((options == null ? void 0 : options.fromComputed) || (e.num > 0 || !isEvent(selectorOrRun)) && (e.previous !== e.value || typeof e.value === "object"))) {
978
+ reaction(e);
979
+ }
980
+ e.previous = e.value;
981
+ e.num++;
982
+ };
983
+ update();
984
+ return () => {
985
+ var _a, _b;
986
+ (_a = e.onCleanup) == null ? void 0 : _a.call(e);
987
+ e.onCleanup = void 0;
988
+ (_b = e.onCleanupReaction) == null ? void 0 : _b.call(e);
989
+ e.onCleanupReaction = void 0;
990
+ dispose == null ? void 0 : dispose();
991
+ };
1022
992
  }
1023
993
 
994
+ // src/when.ts
1024
995
  function _when(predicate, effect, checkReady) {
1025
- // If predicate is a regular Promise skip all the observable stuff
1026
- if (isPromise(predicate)) {
1027
- return effect ? predicate.then(effect) : predicate;
1028
- }
1029
- let value;
1030
- let effectValue;
1031
- // Create a wrapping fn that calls the effect if predicate returns true
1032
- function run(e) {
1033
- const ret = computeSelector(predicate);
1034
- if (isPromise(ret)) {
1035
- value = ret;
1036
- // We want value to be the Promise but return undefined
1037
- // so it doesn't run the effect with the Promise as the value
1038
- return undefined;
1039
- }
1040
- else if (!isPromise(ret) && (checkReady ? isObservableValueReady(ret) : ret)) {
1041
- value = ret;
1042
- // Set cancel so that observe does not track anymore
1043
- e.cancel = true;
1044
- }
1045
- return value;
1046
- }
1047
- function doEffect() {
1048
- // If value is truthy then run the effect
1049
- effectValue = effect === null || effect === void 0 ? void 0 : effect(value);
1050
- }
1051
- // Run in an observe
1052
- observe(run, doEffect);
1053
- // If first run resulted in a truthy value just return it.
1054
- // It will have set e.cancel so no need to dispose
1055
- if (isPromise(value)) {
1056
- return effect ? value.then(effect) : value;
1057
- }
1058
- else if (value !== undefined) {
1059
- return effect ? effectValue : Promise.resolve(value);
1060
- }
1061
- else {
1062
- // Wrap it in a promise
1063
- const promise = new Promise((resolve) => {
1064
- if (effect) {
1065
- const originalEffect = effect;
1066
- effect = ((value) => {
1067
- const effectValue = originalEffect(value);
1068
- resolve(isPromise(effectValue) ? effectValue.then((value) => value) : effectValue);
1069
- });
1070
- }
1071
- else {
1072
- effect = resolve;
1073
- }
1074
- });
1075
- return promise;
996
+ if (isPromise(predicate)) {
997
+ return effect ? predicate.then(effect) : predicate;
998
+ }
999
+ let value;
1000
+ let effectValue;
1001
+ function run(e) {
1002
+ const ret = computeSelector(predicate);
1003
+ if (isPromise(ret)) {
1004
+ value = ret;
1005
+ return void 0;
1006
+ } else if (!isPromise(ret) && (checkReady ? isObservableValueReady(ret) : ret)) {
1007
+ value = ret;
1008
+ e.cancel = true;
1076
1009
  }
1010
+ return value;
1011
+ }
1012
+ function doEffect() {
1013
+ effectValue = effect == null ? void 0 : effect(value);
1014
+ }
1015
+ observe(run, doEffect);
1016
+ if (isPromise(value)) {
1017
+ return effect ? value.then(effect) : value;
1018
+ } else if (value !== void 0) {
1019
+ return effect ? effectValue : Promise.resolve(value);
1020
+ } else {
1021
+ const promise = new Promise((resolve) => {
1022
+ if (effect) {
1023
+ const originalEffect = effect;
1024
+ effect = (value2) => {
1025
+ const effectValue2 = originalEffect(value2);
1026
+ resolve(isPromise(effectValue2) ? effectValue2.then((value3) => value3) : effectValue2);
1027
+ };
1028
+ } else {
1029
+ effect = resolve;
1030
+ }
1031
+ });
1032
+ return promise;
1033
+ }
1077
1034
  }
1078
1035
  function when(predicate, effect) {
1079
- return _when(predicate, effect, false);
1036
+ return _when(predicate, effect, false);
1080
1037
  }
1081
1038
  function whenReady(predicate, effect) {
1082
- return _when(predicate, effect, true);
1039
+ return _when(predicate, effect, true);
1083
1040
  }
1084
1041
 
1085
- const ArrayModifiers = new Set([
1086
- 'copyWithin',
1087
- 'fill',
1088
- 'from',
1089
- 'pop',
1090
- 'push',
1091
- 'reverse',
1092
- 'shift',
1093
- 'sort',
1094
- 'splice',
1095
- 'unshift',
1042
+ // src/ObservableObject.ts
1043
+ var ArrayModifiers = /* @__PURE__ */ new Set([
1044
+ "copyWithin",
1045
+ "fill",
1046
+ "from",
1047
+ "pop",
1048
+ "push",
1049
+ "reverse",
1050
+ "shift",
1051
+ "sort",
1052
+ "splice",
1053
+ "unshift"
1096
1054
  ]);
1097
- const ArrayLoopers = new Set([
1098
- 'every',
1099
- 'filter',
1100
- 'find',
1101
- 'findIndex',
1102
- 'forEach',
1103
- 'join',
1104
- 'map',
1105
- 'reduce',
1106
- 'some',
1055
+ var ArrayLoopers = /* @__PURE__ */ new Set([
1056
+ "every",
1057
+ "filter",
1058
+ "find",
1059
+ "findIndex",
1060
+ "forEach",
1061
+ "join",
1062
+ "map",
1063
+ "reduce",
1064
+ "some"
1107
1065
  ]);
1108
- const ArrayLoopersReturn = new Set(['filter', 'find']);
1109
- const observableProperties = new Map();
1110
- const observableFns = new Map([
1111
- ['get', get],
1112
- ['set', set],
1113
- ['peek', peek],
1114
- ['onChange', onChange],
1115
- ['assign', assign],
1116
- ['delete', deleteFn],
1117
- ['toggle', toggle],
1066
+ var ArrayLoopersReturn = /* @__PURE__ */ new Set(["filter", "find"]);
1067
+ var observableProperties = /* @__PURE__ */ new Map();
1068
+ var observableFns = /* @__PURE__ */ new Map([
1069
+ ["get", get],
1070
+ ["set", set],
1071
+ ["peek", peek],
1072
+ ["onChange", onChange],
1073
+ ["assign", assign],
1074
+ ["delete", deleteFn],
1075
+ ["toggle", toggle]
1118
1076
  ]);
1119
- if (process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test') {
1120
- // eslint-disable-next-line no-var
1121
- var __devUpdateNodes = new Set();
1077
+ if (process.env.NODE_ENV === "development" || process.env.NODE_ENV === "test") {
1078
+ __devUpdateNodes = /* @__PURE__ */ new Set();
1122
1079
  }
1080
+ var __devUpdateNodes;
1123
1081
  function collectionSetter(node, target, prop, ...args) {
1124
- var _a;
1125
- if (prop === 'push' && args.length === 1) {
1126
- // Fast path for push to just append to the end
1127
- setKey(node, target.length + '', args[0]);
1128
- }
1129
- else {
1130
- const prevValue = target.slice();
1131
- const ret = target[prop].apply(target, args);
1132
- if (node) {
1133
- const hasParent = isChildNodeValue(node);
1134
- const key = hasParent ? node.key : '_';
1135
- const parentValue = hasParent ? getNodeValue(node.parent) : node.root;
1136
- // Set the object to the previous value first
1137
- parentValue[key] = prevValue;
1138
- // Then set with the new value so it notifies with the correct prevValue
1139
- setKey((_a = node.parent) !== null && _a !== void 0 ? _a : node, key, target);
1140
- }
1141
- // Return the original value
1142
- return ret;
1082
+ var _a;
1083
+ if (prop === "push" && args.length === 1) {
1084
+ setKey(node, target.length + "", args[0]);
1085
+ } else {
1086
+ const prevValue = target.slice();
1087
+ const ret = target[prop].apply(target, args);
1088
+ if (node) {
1089
+ const hasParent = isChildNodeValue(node);
1090
+ const key = hasParent ? node.key : "_";
1091
+ const parentValue = hasParent ? getNodeValue(node.parent) : node.root;
1092
+ parentValue[key] = prevValue;
1093
+ setKey((_a = node.parent) != null ? _a : node, key, target);
1143
1094
  }
1095
+ return ret;
1096
+ }
1144
1097
  }
1145
- function getKeys(obj, isArr, isMap) {
1146
- return isArr ? undefined : obj ? (isMap ? Array.from(obj.keys()) : Object.keys(obj)) : [];
1098
+ function getKeys(obj, isArr, isMap2) {
1099
+ return isArr ? void 0 : obj ? isMap2 ? Array.from(obj.keys()) : Object.keys(obj) : [];
1147
1100
  }
1148
1101
  function updateNodes(parent, obj, prevValue) {
1149
- var _a, _b, _c;
1150
- if ((process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test') &&
1151
- typeof __devUpdateNodes !== 'undefined' &&
1152
- isObject(obj)) {
1153
- if (__devUpdateNodes.has(obj)) {
1154
- console.error('[legend-state] Circular reference detected in object. You may want to use opaqueObject to stop traversing child nodes.', obj);
1155
- return false;
1156
- }
1157
- __devUpdateNodes.add(obj);
1158
- }
1159
- if ((isObject(obj) && obj[symbolOpaque]) ||
1160
- (isObject(prevValue) && prevValue[symbolOpaque])) {
1161
- const isDiff = obj !== prevValue;
1162
- if (isDiff) {
1163
- if (parent.listeners || parent.listenersImmediate) {
1164
- notify(parent, obj, prevValue, 0);
1165
- }
1166
- }
1167
- if ((process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test') &&
1168
- typeof __devUpdateNodes !== 'undefined' &&
1169
- obj !== undefined) {
1170
- __devUpdateNodes.delete(obj);
1171
- }
1172
- return isDiff;
1173
- }
1174
- const isArr = isArray(obj);
1175
- let prevChildrenById;
1176
- let moved;
1177
- const isCurMap = isMap(obj);
1178
- const isPrevMap = isMap(prevValue);
1179
- const keys = getKeys(obj, isArr, isCurMap);
1180
- const keysPrev = getKeys(prevValue, isArr, isPrevMap);
1181
- const length = ((_a = (keys || obj)) === null || _a === void 0 ? void 0 : _a.length) || 0;
1182
- const lengthPrev = ((_b = (keysPrev || prevValue)) === null || _b === void 0 ? void 0 : _b.length) || 0;
1183
- let idField;
1184
- let isIdFieldFunction;
1185
- let hasADiff = false;
1186
- let retValue;
1187
- if (isArr && isArray(prevValue)) {
1188
- // Construct a map of previous indices for computing move
1189
- if (prevValue.length > 0) {
1190
- const firstPrevValue = prevValue[0];
1191
- if (firstPrevValue !== undefined) {
1192
- idField = findIDKey(firstPrevValue, parent);
1193
- if (idField) {
1194
- isIdFieldFunction = isFunction(idField);
1195
- prevChildrenById = new Map();
1196
- moved = [];
1197
- }
1198
- const keysSeen = process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test'
1199
- ? new Set()
1200
- : undefined;
1201
- if (parent.children) {
1202
- for (let i = 0; i < prevValue.length; i++) {
1203
- const p = prevValue[i];
1204
- if (p) {
1205
- const child = parent.children.get(i + '');
1206
- if (child) {
1207
- if (!obj[i]) {
1208
- // If the previous value is not in the new array and it
1209
- // is an activated, disable its listeners
1210
- handleDeletedChild(child, p);
1211
- }
1212
- if (idField) {
1213
- const key = isIdFieldFunction
1214
- ? idField(p)
1215
- : p[idField];
1216
- if (process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test') {
1217
- if (keysSeen.has(key)) {
1218
- console.warn(`[legend-state] Warning: Multiple elements in array have the same ID. Key field: ${idField}, Array:`, prevValue);
1219
- }
1220
- keysSeen.add(key);
1221
- }
1222
- prevChildrenById.set(key, child);
1223
- }
1224
- }
1225
- }
1226
- }
1227
- }
1228
- }
1229
- }
1230
- }
1231
- else if (prevValue && (!obj || isObject(obj))) {
1232
- // For keys that have been removed from object, notify and update children recursively
1233
- const lengthPrev = keysPrev.length;
1234
- for (let i = 0; i < lengthPrev; i++) {
1235
- const key = keysPrev[i];
1236
- if (!keys.includes(key)) {
1237
- hasADiff = true;
1238
- const child = getChildNode(parent, key);
1239
- const prev = isPrevMap ? prevValue.get(key) : prevValue[key];
1240
- if (prev !== undefined) {
1241
- handleDeletedChild(child, prev);
1242
- }
1243
- }
1244
- }
1245
- }
1246
- if (obj && !isPrimitive(obj)) {
1247
- hasADiff = hasADiff || length !== lengthPrev;
1248
- const isArrDiff = hasADiff;
1249
- let didMove = false;
1250
- for (let i = 0; i < length; i++) {
1251
- const key = isArr ? i + '' : keys[i];
1252
- let value = isCurMap ? obj.get(key) : obj[key];
1253
- const prev = isPrevMap ? prevValue === null || prevValue === void 0 ? void 0 : prevValue.get(key) : prevValue === null || prevValue === void 0 ? void 0 : prevValue[key];
1254
- let isDiff = !equals(value, prev);
1255
- if (isDiff) {
1256
- const id = idField && value
1257
- ? isIdFieldFunction
1258
- ? idField(value)
1259
- : value[idField]
1260
- : undefined;
1261
- const existingChild = (_c = parent.children) === null || _c === void 0 ? void 0 : _c.get(key);
1262
- if (isObservable(value)) {
1263
- const valueNode = getNode(value);
1264
- if ((existingChild === null || existingChild === void 0 ? void 0 : existingChild.linkedToNode) === valueNode) {
1265
- const targetValue = getNodeValue(valueNode);
1266
- isCurMap ? obj.set(key, targetValue) : (obj[key] = targetValue);
1267
- continue;
1268
- }
1269
- const obs = value;
1270
- value = () => obs;
1271
- }
1272
- let child = getChildNode(parent, key, value);
1273
- if (!child.lazy && (isFunction(value) || isObservable(value))) {
1274
- reactivateNode(child, value);
1275
- peekInternal(child);
1276
- }
1277
- // Detect moves within an array. Need to move the original proxy to the new position to keep
1278
- // the proxy stable, so that listeners to this node will be unaffected by the array shift.
1279
- if (isArr && id !== undefined) {
1280
- // Find the previous position of this element in the array
1281
- const prevChild = id !== undefined ? prevChildrenById === null || prevChildrenById === void 0 ? void 0 : prevChildrenById.get(id) : undefined;
1282
- if (!prevChild) {
1283
- // This id was not in the array before so it does not need to notify children
1284
- // It does need to notify itself so isDiff should remain.
1285
- hasADiff = true;
1286
- }
1287
- else if (prevChild !== undefined && prevChild.key !== key) {
1288
- const valuePrevChild = prevValue[prevChild.key];
1289
- // If array length changed then move the original node to the current position.
1290
- // That should be faster than notifying every single element that
1291
- // it's in a new position.
1292
- if (isArrDiff) {
1293
- child = prevChild;
1294
- parent.children.delete(child.key);
1295
- child.key = key;
1296
- moved.push([key, child]);
1297
- }
1298
- didMove = true;
1299
- // And check for diff against the previous value in the previous position
1300
- isDiff = valuePrevChild !== value;
1301
- }
1102
+ var _a, _b, _c;
1103
+ if ((process.env.NODE_ENV === "development" || process.env.NODE_ENV === "test") && typeof __devUpdateNodes !== "undefined" && isObject(obj)) {
1104
+ if (__devUpdateNodes.has(obj)) {
1105
+ console.error(
1106
+ "[legend-state] Circular reference detected in object. You may want to use opaqueObject to stop traversing child nodes.",
1107
+ obj
1108
+ );
1109
+ return false;
1110
+ }
1111
+ __devUpdateNodes.add(obj);
1112
+ }
1113
+ if (isObject(obj) && obj[symbolOpaque] || isObject(prevValue) && prevValue[symbolOpaque]) {
1114
+ const isDiff = obj !== prevValue;
1115
+ if (isDiff) {
1116
+ if (parent.listeners || parent.listenersImmediate) {
1117
+ notify(parent, obj, prevValue, 0);
1118
+ }
1119
+ }
1120
+ if ((process.env.NODE_ENV === "development" || process.env.NODE_ENV === "test") && typeof __devUpdateNodes !== "undefined" && obj !== void 0) {
1121
+ __devUpdateNodes.delete(obj);
1122
+ }
1123
+ return isDiff;
1124
+ }
1125
+ const isArr = isArray(obj);
1126
+ let prevChildrenById;
1127
+ let moved;
1128
+ const isCurMap = isMap(obj);
1129
+ const isPrevMap = isMap(prevValue);
1130
+ const keys = getKeys(obj, isArr, isCurMap);
1131
+ const keysPrev = getKeys(prevValue, isArr, isPrevMap);
1132
+ const length = ((_a = keys || obj) == null ? void 0 : _a.length) || 0;
1133
+ const lengthPrev = ((_b = keysPrev || prevValue) == null ? void 0 : _b.length) || 0;
1134
+ let idField;
1135
+ let isIdFieldFunction;
1136
+ let hasADiff = false;
1137
+ let retValue;
1138
+ if (isArr && isArray(prevValue)) {
1139
+ if (prevValue.length > 0) {
1140
+ const firstPrevValue = prevValue[0];
1141
+ if (firstPrevValue !== void 0) {
1142
+ idField = findIDKey(firstPrevValue, parent);
1143
+ if (idField) {
1144
+ isIdFieldFunction = isFunction(idField);
1145
+ prevChildrenById = /* @__PURE__ */ new Map();
1146
+ moved = [];
1147
+ }
1148
+ const keysSeen = process.env.NODE_ENV === "development" || process.env.NODE_ENV === "test" ? /* @__PURE__ */ new Set() : void 0;
1149
+ if (parent.children) {
1150
+ for (let i = 0; i < prevValue.length; i++) {
1151
+ const p = prevValue[i];
1152
+ if (p) {
1153
+ const child = parent.children.get(i + "");
1154
+ if (child) {
1155
+ if (!obj[i]) {
1156
+ handleDeletedChild(child, p);
1302
1157
  }
1303
- if (isDiff) {
1304
- // Array has a new / modified element
1305
- // If object iterate through its children
1306
- if (isFunction(value) || isObservable(value)) {
1307
- extractFunctionOrComputed(parent, key, value);
1308
- }
1309
- else if (isPrimitive(value)) {
1310
- hasADiff = true;
1311
- }
1312
- else {
1313
- // Always need to updateNodes so we notify through all children
1314
- const updatedNodes = updateNodes(child, value, prev);
1315
- hasADiff = hasADiff || updatedNodes;
1316
- isDiff = updatedNodes;
1317
- }
1318
- }
1319
- if (isDiff || (isArr && !isArrDiff)) {
1320
- // Notify for this child if this element is different and it has listeners
1321
- // Or if the position changed in an array whose length did not change
1322
- // But do not notify child if the parent is an array with changing length -
1323
- // the array's listener will cover it
1324
- if (child.listeners || child.listenersImmediate) {
1325
- notify(child, value, prev, 0, !isArrDiff);
1158
+ if (idField) {
1159
+ const key = isIdFieldFunction ? idField(p) : p[idField];
1160
+ if (process.env.NODE_ENV === "development" || process.env.NODE_ENV === "test") {
1161
+ if (keysSeen.has(key)) {
1162
+ console.warn(
1163
+ `[legend-state] Warning: Multiple elements in array have the same ID. Key field: ${idField}, Array:`,
1164
+ prevValue
1165
+ );
1326
1166
  }
1167
+ keysSeen.add(key);
1168
+ }
1169
+ prevChildrenById.set(key, child);
1327
1170
  }
1171
+ }
1328
1172
  }
1329
- }
1330
- if (moved) {
1331
- for (let i = 0; i < moved.length; i++) {
1332
- const [key, child] = moved[i];
1333
- parent.children.set(key, child);
1173
+ }
1174
+ }
1175
+ }
1176
+ }
1177
+ } else if (prevValue && (!obj || isObject(obj))) {
1178
+ const lengthPrev2 = keysPrev.length;
1179
+ for (let i = 0; i < lengthPrev2; i++) {
1180
+ const key = keysPrev[i];
1181
+ if (!keys.includes(key)) {
1182
+ hasADiff = true;
1183
+ const child = getChildNode(parent, key);
1184
+ const prev = isPrevMap ? prevValue.get(key) : prevValue[key];
1185
+ if (prev !== void 0) {
1186
+ handleDeletedChild(child, prev);
1187
+ }
1188
+ }
1189
+ }
1190
+ }
1191
+ if (obj && !isPrimitive(obj)) {
1192
+ hasADiff = hasADiff || length !== lengthPrev;
1193
+ const isArrDiff = hasADiff;
1194
+ let didMove = false;
1195
+ for (let i = 0; i < length; i++) {
1196
+ const key = isArr ? i + "" : keys[i];
1197
+ let value = isCurMap ? obj.get(key) : obj[key];
1198
+ const prev = isPrevMap ? prevValue == null ? void 0 : prevValue.get(key) : prevValue == null ? void 0 : prevValue[key];
1199
+ let isDiff = !equals(value, prev);
1200
+ if (isDiff) {
1201
+ const id = idField && value ? isIdFieldFunction ? idField(value) : value[idField] : void 0;
1202
+ const existingChild = (_c = parent.children) == null ? void 0 : _c.get(key);
1203
+ if (isObservable(value)) {
1204
+ const valueNode = getNode(value);
1205
+ if ((existingChild == null ? void 0 : existingChild.linkedToNode) === valueNode) {
1206
+ const targetValue = getNodeValue(valueNode);
1207
+ isCurMap ? obj.set(key, targetValue) : obj[key] = targetValue;
1208
+ continue;
1209
+ }
1210
+ const obs = value;
1211
+ value = () => obs;
1212
+ }
1213
+ let child = getChildNode(parent, key, value);
1214
+ if (!child.lazy && (isFunction(value) || isObservable(value))) {
1215
+ reactivateNode(child, value);
1216
+ peekInternal(child);
1217
+ }
1218
+ if (isArr && id !== void 0) {
1219
+ const prevChild = id !== void 0 ? prevChildrenById == null ? void 0 : prevChildrenById.get(id) : void 0;
1220
+ if (!prevChild) {
1221
+ hasADiff = true;
1222
+ } else if (prevChild !== void 0 && prevChild.key !== key) {
1223
+ const valuePrevChild = prevValue[prevChild.key];
1224
+ if (isArrDiff) {
1225
+ child = prevChild;
1226
+ parent.children.delete(child.key);
1227
+ child.key = key;
1228
+ moved.push([key, child]);
1334
1229
  }
1230
+ didMove = true;
1231
+ isDiff = valuePrevChild !== value;
1232
+ }
1335
1233
  }
1336
- // The full array does not need to re-render if the length is the same
1337
- // So don't notify shallow listeners
1338
- retValue = hasADiff || didMove;
1339
- }
1340
- else if (prevValue !== undefined) {
1341
- // If value got set to undefined, it has a diff
1342
- retValue = true;
1343
- }
1344
- if ((process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test') &&
1345
- typeof __devUpdateNodes !== 'undefined' &&
1346
- obj !== undefined) {
1347
- __devUpdateNodes.delete(obj);
1348
- }
1349
- return retValue !== null && retValue !== void 0 ? retValue : false;
1234
+ if (isDiff) {
1235
+ if (isFunction(value) || isObservable(value)) {
1236
+ extractFunctionOrComputed(parent, key, value);
1237
+ } else if (isPrimitive(value)) {
1238
+ hasADiff = true;
1239
+ } else {
1240
+ const updatedNodes = updateNodes(child, value, prev);
1241
+ hasADiff = hasADiff || updatedNodes;
1242
+ isDiff = updatedNodes;
1243
+ }
1244
+ }
1245
+ if (isDiff || isArr && !isArrDiff) {
1246
+ if (child.listeners || child.listenersImmediate) {
1247
+ notify(child, value, prev, 0, !isArrDiff);
1248
+ }
1249
+ }
1250
+ }
1251
+ }
1252
+ if (moved) {
1253
+ for (let i = 0; i < moved.length; i++) {
1254
+ const [key, child] = moved[i];
1255
+ parent.children.set(key, child);
1256
+ }
1257
+ }
1258
+ retValue = hasADiff || didMove;
1259
+ } else if (prevValue !== void 0) {
1260
+ retValue = true;
1261
+ }
1262
+ if ((process.env.NODE_ENV === "development" || process.env.NODE_ENV === "test") && typeof __devUpdateNodes !== "undefined" && obj !== void 0) {
1263
+ __devUpdateNodes.delete(obj);
1264
+ }
1265
+ return retValue != null ? retValue : false;
1350
1266
  }
1351
1267
  function handleDeletedChild(child, p) {
1352
- var _a, _b;
1353
- // If the previous value is not in the new array and it
1354
- // is an activated, disable its listeners
1355
- (_a = child.linkedToNodeDispose) === null || _a === void 0 ? void 0 : _a.call(child);
1356
- (_b = child.activatedObserveDispose) === null || _b === void 0 ? void 0 : _b.call(child);
1357
- if (!isPrimitive(p)) {
1358
- updateNodes(child, undefined, p);
1359
- }
1360
- if (child.listeners || child.listenersImmediate) {
1361
- notify(child, undefined, p, 0);
1362
- }
1268
+ var _a, _b;
1269
+ (_a = child.linkedToNodeDispose) == null ? void 0 : _a.call(child);
1270
+ (_b = child.activatedObserveDispose) == null ? void 0 : _b.call(child);
1271
+ if (!isPrimitive(p)) {
1272
+ updateNodes(child, void 0, p);
1273
+ }
1274
+ if (child.listeners || child.listenersImmediate) {
1275
+ notify(child, void 0, p, 0);
1276
+ }
1363
1277
  }
1364
1278
  function getProxy(node, p, asFunction) {
1365
- // Get the child node if p prop
1366
- if (p !== undefined)
1367
- node = getChildNode(node, p, asFunction);
1368
- // Create a proxy if not already cached and return it
1369
- return (node.proxy || (node.proxy = new Proxy(node, proxyHandler)));
1279
+ if (p !== void 0)
1280
+ node = getChildNode(node, p, asFunction);
1281
+ return node.proxy || (node.proxy = new Proxy(node, proxyHandler));
1370
1282
  }
1371
1283
  function flushPending() {
1372
- // Need to short circuit the computed batching because the user called get() or peek()
1373
- // in which case the set needs to run immediately so that the values are up to date.
1374
- if (globalState.pendingNodes.size > 0) {
1375
- const nodes = Array.from(globalState.pendingNodes.values());
1376
- globalState.pendingNodes.clear();
1377
- nodes.forEach((fn) => fn());
1378
- }
1379
- }
1380
- const proxyHandler = {
1381
- get(node, p, receiver) {
1382
- var _a, _b;
1383
- if (p === symbolToPrimitive) {
1384
- throw new Error(process.env.NODE_ENV === 'development'
1385
- ? '[legend-state] observable should not be used as a primitive. You may have forgotten to use .get() or .peek() to get the value of the observable.'
1386
- : '[legend-state] observable is not a primitive.');
1387
- }
1388
- if (p === symbolGetNode) {
1389
- return node;
1390
- }
1391
- if (p === 'apply') {
1392
- const nodeValue = getNodeValue(node);
1393
- if (isFunction(nodeValue)) {
1394
- return nodeValue.apply;
1395
- }
1396
- }
1397
- let value = peekInternal(node, /*activateRecursive*/ p === 'get' || p === 'peek');
1398
- // If this node is linked to another observable then forward to the target's handler.
1399
- // The exception is onChange because it needs to listen to this node for changes.
1400
- // This needs to be below peek because it activates there.
1401
- const targetNode = node.linkedToNode || (value === null || value === void 0 ? void 0 : value[symbolGetNode]);
1402
- if (targetNode && p !== 'onChange') {
1403
- return proxyHandler.get(targetNode, p, receiver);
1404
- }
1405
- if (isMap(value) || value instanceof WeakMap || value instanceof Set || value instanceof WeakSet) {
1406
- const ret = handlerMapSet(node, p, value);
1407
- if (ret !== undefined) {
1408
- return ret;
1409
- }
1410
- }
1411
- const fn = observableFns.get(p);
1412
- // If this is an observable function, call it
1413
- if (fn) {
1414
- if (p === 'get' || p === 'peek') {
1415
- flushPending();
1416
- }
1417
- return function (a, b, c) {
1418
- const l = arguments.length;
1419
- // Array call and apply are slow so micro-optimize this hot path.
1420
- // The observable functions depends on the number of arguments so we have to
1421
- // call it with the correct arguments, not just undefined
1422
- switch (l) {
1423
- case 0:
1424
- return fn(node);
1425
- case 1:
1426
- return fn(node, a);
1427
- case 2:
1428
- return fn(node, a, b);
1429
- default:
1430
- return fn(node, a, b, c);
1431
- }
1284
+ if (globalState.pendingNodes.size > 0) {
1285
+ const nodes = Array.from(globalState.pendingNodes.values());
1286
+ globalState.pendingNodes.clear();
1287
+ nodes.forEach((fn) => fn());
1288
+ }
1289
+ }
1290
+ var proxyHandler = {
1291
+ get(node, p, receiver) {
1292
+ var _a, _b;
1293
+ if (p === symbolToPrimitive) {
1294
+ throw new Error(
1295
+ process.env.NODE_ENV === "development" ? "[legend-state] observable should not be used as a primitive. You may have forgotten to use .get() or .peek() to get the value of the observable." : "[legend-state] observable is not a primitive."
1296
+ );
1297
+ }
1298
+ if (p === symbolGetNode) {
1299
+ return node;
1300
+ }
1301
+ if (p === "apply") {
1302
+ const nodeValue = getNodeValue(node);
1303
+ if (isFunction(nodeValue)) {
1304
+ return nodeValue.apply;
1305
+ }
1306
+ }
1307
+ let value = peekInternal(
1308
+ node,
1309
+ /*activateRecursive*/
1310
+ p === "get" || p === "peek"
1311
+ );
1312
+ const targetNode = node.linkedToNode || (value == null ? void 0 : value[symbolGetNode]);
1313
+ if (targetNode && p !== "onChange") {
1314
+ return proxyHandler.get(targetNode, p, receiver);
1315
+ }
1316
+ if (isMap(value) || value instanceof WeakMap || value instanceof Set || value instanceof WeakSet) {
1317
+ const ret = handlerMapSet(node, p, value);
1318
+ if (ret !== void 0) {
1319
+ return ret;
1320
+ }
1321
+ }
1322
+ const fn = observableFns.get(p);
1323
+ if (fn) {
1324
+ if (p === "get" || p === "peek") {
1325
+ flushPending();
1326
+ }
1327
+ return function(a, b, c) {
1328
+ const l = arguments.length;
1329
+ switch (l) {
1330
+ case 0:
1331
+ return fn(node);
1332
+ case 1:
1333
+ return fn(node, a);
1334
+ case 2:
1335
+ return fn(node, a, b);
1336
+ default:
1337
+ return fn(node, a, b, c);
1338
+ }
1339
+ };
1340
+ }
1341
+ const property = observableProperties.get(p);
1342
+ if (property) {
1343
+ return property.get(node);
1344
+ }
1345
+ let vProp = value == null ? void 0 : value[p];
1346
+ if (isObject(value) && value[symbolOpaque]) {
1347
+ return vProp;
1348
+ }
1349
+ const fnOrComputed = (_a = node.functions) == null ? void 0 : _a.get(p);
1350
+ if (fnOrComputed) {
1351
+ if (isObservable(fnOrComputed)) {
1352
+ return fnOrComputed;
1353
+ } else {
1354
+ return getProxy(node, p, fnOrComputed);
1355
+ }
1356
+ } else {
1357
+ vProp = checkProperty(value, p);
1358
+ }
1359
+ if (isNullOrUndefined(value) && vProp === void 0 && (ArrayModifiers.has(p) || ArrayLoopers.has(p))) {
1360
+ value = [];
1361
+ setNodeValue(node, value);
1362
+ vProp = value[p];
1363
+ }
1364
+ if (isFunction(vProp)) {
1365
+ if (isArray(value)) {
1366
+ if (ArrayModifiers.has(p)) {
1367
+ return (...args) => collectionSetter(node, value, p, ...args);
1368
+ } else if (ArrayLoopers.has(p)) {
1369
+ updateTracking(node, true);
1370
+ return function(cbOrig, thisArg) {
1371
+ const isReduce = p === "reduce";
1372
+ const cbWrapped = isReduce ? (previousValue, currentValue, currentIndex, array) => {
1373
+ return cbOrig(
1374
+ previousValue,
1375
+ getProxy(node, currentIndex + "", currentValue),
1376
+ currentIndex,
1377
+ array
1378
+ );
1379
+ } : (val, index, array) => {
1380
+ return cbOrig(getProxy(node, index + "", val), index, array);
1432
1381
  };
1433
- }
1434
- const property = observableProperties.get(p);
1435
- if (property) {
1436
- return property.get(node);
1437
- }
1438
- let vProp = value === null || value === void 0 ? void 0 : value[p];
1439
- if (isObject(value) && value[symbolOpaque]) {
1440
- return vProp;
1441
- }
1442
- const fnOrComputed = (_a = node.functions) === null || _a === void 0 ? void 0 : _a.get(p);
1443
- if (fnOrComputed) {
1444
- if (isObservable(fnOrComputed)) {
1445
- return fnOrComputed;
1382
+ if (isReduce || !ArrayLoopersReturn.has(p)) {
1383
+ return value[p](cbWrapped, thisArg);
1446
1384
  }
1447
- else {
1448
- return getProxy(node, p, fnOrComputed);
1449
- }
1450
- }
1451
- else {
1452
- vProp = checkProperty(value, p);
1453
- }
1454
- if (isNullOrUndefined(value) && vProp === undefined && (ArrayModifiers.has(p) || ArrayLoopers.has(p))) {
1455
- value = [];
1456
- setNodeValue(node, value);
1457
- vProp = value[p];
1458
- }
1459
- // Handle function calls
1460
- if (isFunction(vProp)) {
1461
- if (isArray(value)) {
1462
- if (ArrayModifiers.has(p)) {
1463
- // Call the wrapped modifier function
1464
- return (...args) => collectionSetter(node, value, p, ...args);
1385
+ const isFind = p === "find";
1386
+ const out = [];
1387
+ for (let i = 0; i < value.length; i++) {
1388
+ if (cbWrapped(value[i], i, value)) {
1389
+ const proxy2 = getProxy(node, i + "");
1390
+ if (isFind) {
1391
+ return proxy2;
1465
1392
  }
1466
- else if (ArrayLoopers.has(p)) {
1467
- // Update that this node was accessed for observers
1468
- updateTracking(node, true);
1469
- return function (cbOrig, thisArg) {
1470
- const isReduce = p === 'reduce';
1471
- // Callbacks are given the Proxy rather than the underlying data
1472
- const cbWrapped = isReduce
1473
- ? (previousValue, currentValue, currentIndex, array) => {
1474
- return cbOrig(previousValue, getProxy(node, currentIndex + '', currentValue), currentIndex, array);
1475
- }
1476
- : (val, index, array) => {
1477
- return cbOrig(getProxy(node, index + '', val), index, array);
1478
- };
1479
- if (isReduce || !ArrayLoopersReturn.has(p)) {
1480
- return value[p](cbWrapped, thisArg);
1481
- }
1482
- const isFind = p === 'find';
1483
- const out = [];
1484
- for (let i = 0; i < value.length; i++) {
1485
- if (cbWrapped(value[i], i, value)) {
1486
- const proxy = getProxy(node, i + '');
1487
- // find returns the first match, otherwise it returns an array
1488
- if (isFind) {
1489
- return proxy;
1490
- }
1491
- out.push(proxy);
1492
- }
1493
- }
1494
- return isFind ? undefined : out;
1495
- };
1496
- }
1497
- }
1498
- extractFunctionOrComputed(node, p, vProp);
1499
- const fnOrComputed2 = (_b = node.functions) === null || _b === void 0 ? void 0 : _b.get(p);
1500
- if (fnOrComputed2) {
1501
- return getProxy(node, p, fnOrComputed2);
1502
- }
1503
- // Return the function bound to the value
1504
- return vProp.bind(value);
1505
- }
1506
- // Accessing primitive returns the raw value
1507
- if (isPrimitive(vProp)) {
1508
- // Update that this primitive node was accessed for observers
1509
- if (isArray(value) && p === 'length') {
1510
- updateTracking(node, true);
1511
- return vProp;
1393
+ out.push(proxy2);
1394
+ }
1512
1395
  }
1513
- }
1514
- // Return an observable proxy to the property
1515
- return getProxy(node, p);
1516
- },
1517
- // Forward all proxy properties to the target's value
1518
- getPrototypeOf(node) {
1519
- const value = getNodeValue(node);
1520
- return value !== null && typeof value === 'object' ? Reflect.getPrototypeOf(value) : null;
1521
- },
1522
- ownKeys(node) {
1523
- // TODO: Temporary workaround to fix a bug - the first peek may not return the correct value
1524
- // if the value is a cached. This fixes the test "cache with initial ownKeys"
1525
- peekInternal(node);
1526
- const value = get(node, true);
1527
- if (isPrimitive(value))
1528
- return [];
1529
- const keys = value ? Reflect.ownKeys(value) : [];
1530
- // This is required to fix this error:
1531
- // TypeError: 'getOwnPropertyDescriptor' on proxy: trap reported non-configurability for
1532
- // property 'length' which is either non-existent or configurable in the proxy node
1533
- if (isArray(value) && keys[keys.length - 1] === 'length') {
1534
- keys.splice(keys.length - 1, 1);
1535
- }
1536
- if (isFunction(node)) {
1537
- const reflectedKeys = Reflect.ownKeys(node);
1538
- ['caller', 'arguments', 'prototype'].forEach((key) => reflectedKeys.includes(key) && keys.push(key));
1539
- }
1540
- return keys;
1541
- },
1542
- getOwnPropertyDescriptor(node, prop) {
1543
- if (prop === 'caller' || prop === 'arguments' || prop === 'prototype') {
1544
- return { configurable: false, enumerable: false };
1545
- }
1546
- const value = getNodeValue(node);
1547
- return isPrimitive(value) ? undefined : Reflect.getOwnPropertyDescriptor(value, prop);
1548
- },
1549
- set(node, prop, value) {
1550
- // If this assignment comes from within an observable function it's allowed
1551
- if (node.isSetting) {
1552
- return Reflect.set(node, prop, value);
1553
- }
1554
- if (node.isAssigning) {
1555
- setKey(node, prop, value);
1556
- return true;
1557
- }
1558
- const property = observableProperties.get(prop);
1559
- if (property) {
1560
- property.set(node, value);
1561
- return true;
1562
- }
1563
- if (process.env.NODE_ENV === 'development') {
1564
- console.warn('[legend-state]: Error: Cannot set a value directly:', prop, value);
1565
- }
1566
- return false;
1567
- },
1568
- deleteProperty(node, prop) {
1569
- // If this delete comes from within an observable function it's allowed
1570
- if (node.isSetting) {
1571
- return Reflect.deleteProperty(node, prop);
1572
- }
1573
- else {
1574
- if (process.env.NODE_ENV === 'development') {
1575
- console.warn('[legend-state]: Error: Cannot delete a value directly:', prop);
1576
- }
1577
- return false;
1578
- }
1579
- },
1580
- has(node, prop) {
1581
- const value = getNodeValue(node);
1582
- return Reflect.has(value, prop);
1583
- },
1584
- apply(target, thisArg, argArray) {
1585
- // If it's a function call it as a function
1586
- if (isObservable(thisArg)) {
1587
- thisArg = thisArg.peek();
1588
- }
1589
- return Reflect.apply(target.lazyFn || target, thisArg, argArray);
1590
- },
1396
+ return isFind ? void 0 : out;
1397
+ };
1398
+ }
1399
+ }
1400
+ extractFunctionOrComputed(node, p, vProp);
1401
+ const fnOrComputed2 = (_b = node.functions) == null ? void 0 : _b.get(p);
1402
+ if (fnOrComputed2) {
1403
+ return getProxy(node, p, fnOrComputed2);
1404
+ }
1405
+ return vProp.bind(value);
1406
+ }
1407
+ if (isPrimitive(vProp)) {
1408
+ if (isArray(value) && p === "length") {
1409
+ updateTracking(node, true);
1410
+ return vProp;
1411
+ }
1412
+ }
1413
+ return getProxy(node, p);
1414
+ },
1415
+ // Forward all proxy properties to the target's value
1416
+ getPrototypeOf(node) {
1417
+ const value = getNodeValue(node);
1418
+ return value !== null && typeof value === "object" ? Reflect.getPrototypeOf(value) : null;
1419
+ },
1420
+ ownKeys(node) {
1421
+ peekInternal(node);
1422
+ const value = get(node, true);
1423
+ if (isPrimitive(value))
1424
+ return [];
1425
+ const keys = value ? Reflect.ownKeys(value) : [];
1426
+ if (isArray(value) && keys[keys.length - 1] === "length") {
1427
+ keys.splice(keys.length - 1, 1);
1428
+ }
1429
+ if (isFunction(node)) {
1430
+ const reflectedKeys = Reflect.ownKeys(node);
1431
+ ["caller", "arguments", "prototype"].forEach((key) => reflectedKeys.includes(key) && keys.push(key));
1432
+ }
1433
+ return keys;
1434
+ },
1435
+ getOwnPropertyDescriptor(node, prop) {
1436
+ if (prop === "caller" || prop === "arguments" || prop === "prototype") {
1437
+ return { configurable: false, enumerable: false };
1438
+ }
1439
+ const value = getNodeValue(node);
1440
+ return isPrimitive(value) ? void 0 : Reflect.getOwnPropertyDescriptor(value, prop);
1441
+ },
1442
+ set(node, prop, value) {
1443
+ if (node.isSetting) {
1444
+ return Reflect.set(node, prop, value);
1445
+ }
1446
+ if (node.isAssigning) {
1447
+ setKey(node, prop, value);
1448
+ return true;
1449
+ }
1450
+ const property = observableProperties.get(prop);
1451
+ if (property) {
1452
+ property.set(node, value);
1453
+ return true;
1454
+ }
1455
+ if (process.env.NODE_ENV === "development") {
1456
+ console.warn("[legend-state]: Error: Cannot set a value directly:", prop, value);
1457
+ }
1458
+ return false;
1459
+ },
1460
+ deleteProperty(node, prop) {
1461
+ if (node.isSetting) {
1462
+ return Reflect.deleteProperty(node, prop);
1463
+ } else {
1464
+ if (process.env.NODE_ENV === "development") {
1465
+ console.warn("[legend-state]: Error: Cannot delete a value directly:", prop);
1466
+ }
1467
+ return false;
1468
+ }
1469
+ },
1470
+ has(node, prop) {
1471
+ const value = getNodeValue(node);
1472
+ return Reflect.has(value, prop);
1473
+ },
1474
+ apply(target, thisArg, argArray) {
1475
+ if (isObservable(thisArg)) {
1476
+ thisArg = thisArg.peek();
1477
+ }
1478
+ return Reflect.apply(target.lazyFn || target, thisArg, argArray);
1479
+ }
1591
1480
  };
1592
1481
  function set(node, newValue) {
1593
- if (node.parent) {
1594
- setKey(node.parent, node.key, newValue);
1595
- }
1596
- else {
1597
- setKey(node, '_', newValue);
1598
- }
1482
+ if (node.parent) {
1483
+ setKey(node.parent, node.key, newValue);
1484
+ } else {
1485
+ setKey(node, "_", newValue);
1486
+ }
1599
1487
  }
1600
1488
  function toggle(node) {
1601
- const value = getNodeValue(node);
1602
- if (value === undefined || value === null || isBoolean(value)) {
1603
- set(node, !value);
1604
- }
1605
- else if (process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test') {
1606
- throw new Error('[legend-state] Cannot toggle a non-boolean value');
1607
- }
1489
+ const value = getNodeValue(node);
1490
+ if (value === void 0 || value === null || isBoolean(value)) {
1491
+ set(node, !value);
1492
+ } else if (process.env.NODE_ENV === "development" || process.env.NODE_ENV === "test") {
1493
+ throw new Error("[legend-state] Cannot toggle a non-boolean value");
1494
+ }
1608
1495
  }
1609
1496
  function setKey(node, key, newValue, level) {
1610
- if (process.env.NODE_ENV === 'development') {
1611
- if (typeof HTMLElement !== 'undefined' && newValue instanceof HTMLElement) {
1612
- console.warn(`[legend-state] Set an HTMLElement into state. You probably don't want to do that.`);
1613
- }
1614
- }
1615
- const isRoot = !node.parent && key === '_';
1616
- if (node.parent && !getNodeValue(node) && !isFunction(newValue)) {
1617
- set(node, { [key]: newValue });
1618
- }
1619
- // Get the child node for updating and notifying
1620
- const childNode = isRoot ? node : getChildNode(node, key, newValue);
1621
- if (isObservable(newValue)) {
1622
- setToObservable(childNode, newValue);
1623
- }
1624
- else {
1625
- // Set the raw value on the parent object
1626
- const { newValue: savedValue, prevValue } = setNodeValue(childNode, newValue);
1627
- const isPrim = isPrimitive(savedValue) || savedValue instanceof Date;
1628
- if (!equals(savedValue, prevValue)) {
1629
- updateNodesAndNotify(node, savedValue, prevValue, childNode, isPrim, isRoot, level);
1630
- }
1631
- if (!isPrim) {
1632
- childNode.needsExtract = true;
1633
- }
1634
- extractFunctionOrComputed(node, key, savedValue);
1635
- }
1497
+ if (process.env.NODE_ENV === "development") {
1498
+ if (typeof HTMLElement !== "undefined" && newValue instanceof HTMLElement) {
1499
+ console.warn(`[legend-state] Set an HTMLElement into state. You probably don't want to do that.`);
1500
+ }
1501
+ }
1502
+ const isRoot = !node.parent && key === "_";
1503
+ if (node.parent && !getNodeValue(node) && !isFunction(newValue)) {
1504
+ set(node, { [key]: newValue });
1505
+ }
1506
+ const childNode = isRoot ? node : getChildNode(node, key, newValue);
1507
+ if (isObservable(newValue)) {
1508
+ setToObservable(childNode, newValue);
1509
+ } else {
1510
+ const { newValue: savedValue, prevValue } = setNodeValue(childNode, newValue);
1511
+ const isPrim = isPrimitive(savedValue) || savedValue instanceof Date;
1512
+ if (!equals(savedValue, prevValue)) {
1513
+ updateNodesAndNotify(node, savedValue, prevValue, childNode, isPrim, isRoot, level);
1514
+ }
1515
+ if (!isPrim) {
1516
+ childNode.needsExtract = true;
1517
+ }
1518
+ extractFunctionOrComputed(node, key, savedValue);
1519
+ }
1636
1520
  }
1637
1521
  function assign(node, value) {
1638
- const proxy = getProxy(node);
1639
- beginBatch();
1640
- if (isPrimitive(node.root._)) {
1641
- node.root._ = {};
1642
- }
1643
- if (isMap(value)) {
1644
- const currentValue = getNodeValue(node);
1645
- if (isMap(currentValue)) {
1646
- value.forEach((value, key) => currentValue.set(key, value));
1647
- }
1648
- }
1649
- else {
1650
- // Set inAssign to allow setting on safe observables
1651
- node.isAssigning = (node.isAssigning || 0) + 1;
1652
- try {
1653
- // TODO: If current value is a Map how to assign into the Map?
1654
- Object.assign(proxy, value);
1655
- }
1656
- finally {
1657
- node.isAssigning--;
1658
- }
1522
+ const proxy2 = getProxy(node);
1523
+ beginBatch();
1524
+ if (isPrimitive(node.root._)) {
1525
+ node.root._ = {};
1526
+ }
1527
+ if (isMap(value)) {
1528
+ const currentValue = getNodeValue(node);
1529
+ if (isMap(currentValue)) {
1530
+ value.forEach((value2, key) => currentValue.set(key, value2));
1531
+ }
1532
+ } else {
1533
+ node.isAssigning = (node.isAssigning || 0) + 1;
1534
+ try {
1535
+ Object.assign(proxy2, value);
1536
+ } finally {
1537
+ node.isAssigning--;
1659
1538
  }
1660
- endBatch();
1661
- return proxy;
1539
+ }
1540
+ endBatch();
1541
+ return proxy2;
1662
1542
  }
1663
1543
  function deleteFn(node, key) {
1664
- // If called without a key, delete by key from the parent node
1665
- if (key === undefined && isChildNodeValue(node)) {
1666
- key = node.key;
1667
- node = node.parent;
1668
- }
1669
- const value = getNodeValue(node);
1670
- if (isArray(value)) {
1671
- collectionSetter(node, value, 'splice', key, 1);
1672
- }
1673
- else {
1674
- setKey(node, key !== null && key !== void 0 ? key : '_', symbolDelete, /*level*/ -1);
1675
- }
1544
+ if (key === void 0 && isChildNodeValue(node)) {
1545
+ key = node.key;
1546
+ node = node.parent;
1547
+ }
1548
+ const value = getNodeValue(node);
1549
+ if (isArray(value)) {
1550
+ collectionSetter(node, value, "splice", key, 1);
1551
+ } else {
1552
+ setKey(
1553
+ node,
1554
+ key != null ? key : "_",
1555
+ symbolDelete,
1556
+ /*level*/
1557
+ -1
1558
+ );
1559
+ }
1676
1560
  }
1677
1561
  function handlerMapSet(node, p, value) {
1678
- const vProp = value === null || value === void 0 ? void 0 : value[p];
1679
- if (p === 'size') {
1680
- return getProxy(node, p);
1681
- }
1682
- else if (isFunction(vProp)) {
1683
- return function (a, b, c) {
1684
- const l = arguments.length;
1685
- const valueMap = value;
1686
- if (p === 'get') {
1687
- if (l > 0 && typeof a !== 'boolean' && a !== optimized) {
1688
- return getProxy(node, a);
1689
- }
1690
- }
1691
- else if (p === 'set') {
1692
- if (l === 2) {
1693
- const prev = valueMap.get(a);
1694
- const ret = valueMap.set(a, b);
1695
- if (prev !== b) {
1696
- updateNodesAndNotify(getChildNode(node, a), b, prev);
1697
- }
1698
- return ret;
1699
- }
1700
- else if (l === 1 && isMap(value)) {
1701
- set(node, a);
1702
- }
1703
- }
1704
- else if (p === 'delete') {
1705
- if (l > 0) {
1706
- // Support Set by just returning a if it doesn't have get, meaning it's not a Map
1707
- const prev = value.get ? valueMap.get(a) : a;
1708
- const ret = value.delete(a);
1709
- if (ret) {
1710
- updateNodesAndNotify(getChildNode(node, a), undefined, prev);
1711
- }
1712
- return ret;
1713
- }
1714
- }
1715
- else if (p === 'clear') {
1716
- const prev = new Map(valueMap);
1717
- const size = valueMap.size;
1718
- valueMap.clear();
1719
- if (size) {
1720
- updateNodesAndNotify(node, value, prev);
1721
- }
1722
- return;
1723
- }
1724
- else if (p === 'add') {
1725
- const prev = new Set(value);
1726
- const ret = value.add(a);
1727
- if (!value.has(p)) {
1728
- notify(node, ret, prev, 0);
1729
- }
1730
- return ret;
1731
- }
1732
- // TODO: This is duplicated from proxy handler, how to dedupe with best performance?
1733
- const fn = observableFns.get(p);
1734
- if (fn) {
1735
- // Array call and apply are slow so micro-optimize this hot path.
1736
- // The observable functions depends on the number of arguments so we have to
1737
- // call it with the correct arguments, not just undefined
1738
- switch (l) {
1739
- case 0:
1740
- return fn(node);
1741
- case 1:
1742
- return fn(node, a);
1743
- case 2:
1744
- return fn(node, a, b);
1745
- default:
1746
- return fn(node, a, b, c);
1747
- }
1748
- }
1749
- else {
1750
- return value[p](a, b);
1751
- }
1752
- };
1753
- }
1562
+ const vProp = value == null ? void 0 : value[p];
1563
+ if (p === "size") {
1564
+ return getProxy(node, p);
1565
+ } else if (isFunction(vProp)) {
1566
+ return function(a, b, c) {
1567
+ const l = arguments.length;
1568
+ const valueMap = value;
1569
+ if (p === "get") {
1570
+ if (l > 0 && typeof a !== "boolean" && a !== optimized) {
1571
+ return getProxy(node, a);
1572
+ }
1573
+ } else if (p === "set") {
1574
+ if (l === 2) {
1575
+ const prev = valueMap.get(a);
1576
+ const ret = valueMap.set(a, b);
1577
+ if (prev !== b) {
1578
+ updateNodesAndNotify(getChildNode(node, a), b, prev);
1579
+ }
1580
+ return ret;
1581
+ } else if (l === 1 && isMap(value)) {
1582
+ set(node, a);
1583
+ }
1584
+ } else if (p === "delete") {
1585
+ if (l > 0) {
1586
+ const prev = value.get ? valueMap.get(a) : a;
1587
+ const ret = value.delete(a);
1588
+ if (ret) {
1589
+ updateNodesAndNotify(getChildNode(node, a), void 0, prev);
1590
+ }
1591
+ return ret;
1592
+ }
1593
+ } else if (p === "clear") {
1594
+ const prev = new Map(valueMap);
1595
+ const size = valueMap.size;
1596
+ valueMap.clear();
1597
+ if (size) {
1598
+ updateNodesAndNotify(node, value, prev);
1599
+ }
1600
+ return;
1601
+ } else if (p === "add") {
1602
+ const prev = new Set(value);
1603
+ const ret = value.add(a);
1604
+ if (!value.has(p)) {
1605
+ notify(node, ret, prev, 0);
1606
+ }
1607
+ return ret;
1608
+ }
1609
+ const fn = observableFns.get(p);
1610
+ if (fn) {
1611
+ switch (l) {
1612
+ case 0:
1613
+ return fn(node);
1614
+ case 1:
1615
+ return fn(node, a);
1616
+ case 2:
1617
+ return fn(node, a, b);
1618
+ default:
1619
+ return fn(node, a, b, c);
1620
+ }
1621
+ } else {
1622
+ return value[p](a, b);
1623
+ }
1624
+ };
1625
+ }
1754
1626
  }
1755
1627
  function updateNodesAndNotify(node, newValue, prevValue, childNode, isPrim, isRoot, level) {
1756
- if (!childNode)
1757
- childNode = node;
1758
- // Make sure we don't call too many listeners for every property set
1759
- beginBatch();
1760
- if (isPrim === undefined) {
1761
- isPrim = isPrimitive(newValue);
1762
- }
1763
- let hasADiff = isPrim;
1764
- let whenOptimizedOnlyIf = false;
1765
- // If new value is an object or array update notify down the tree
1766
- if (!isPrim || (prevValue && !isPrimitive(prevValue))) {
1767
- if ((process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test') &&
1768
- typeof __devUpdateNodes !== 'undefined') {
1769
- __devUpdateNodes.clear();
1770
- }
1771
- hasADiff = updateNodes(childNode, newValue, prevValue);
1772
- if (isArray(newValue)) {
1773
- whenOptimizedOnlyIf = (newValue === null || newValue === void 0 ? void 0 : newValue.length) !== (prevValue === null || prevValue === void 0 ? void 0 : prevValue.length);
1774
- }
1775
- }
1776
- if (isPrim || !newValue || (isEmpty(newValue) && !isEmpty(prevValue)) ? newValue !== prevValue : hasADiff) {
1777
- // Notify for this element if something inside it has changed
1778
- notify(isPrim && isRoot ? node : childNode, newValue, prevValue, (level !== null && level !== void 0 ? level : prevValue === undefined) ? -1 : hasADiff ? 0 : 1, whenOptimizedOnlyIf);
1779
- }
1780
- endBatch();
1628
+ if (!childNode)
1629
+ childNode = node;
1630
+ beginBatch();
1631
+ if (isPrim === void 0) {
1632
+ isPrim = isPrimitive(newValue);
1633
+ }
1634
+ let hasADiff = isPrim;
1635
+ let whenOptimizedOnlyIf = false;
1636
+ if (!isPrim || prevValue && !isPrimitive(prevValue)) {
1637
+ if ((process.env.NODE_ENV === "development" || process.env.NODE_ENV === "test") && typeof __devUpdateNodes !== "undefined") {
1638
+ __devUpdateNodes.clear();
1639
+ }
1640
+ hasADiff = updateNodes(childNode, newValue, prevValue);
1641
+ if (isArray(newValue)) {
1642
+ whenOptimizedOnlyIf = (newValue == null ? void 0 : newValue.length) !== (prevValue == null ? void 0 : prevValue.length);
1643
+ }
1644
+ }
1645
+ if (isPrim || !newValue || isEmpty(newValue) && !isEmpty(prevValue) ? newValue !== prevValue : hasADiff) {
1646
+ notify(
1647
+ isPrim && isRoot ? node : childNode,
1648
+ newValue,
1649
+ prevValue,
1650
+ (level != null ? level : prevValue === void 0) ? -1 : hasADiff ? 0 : 1,
1651
+ whenOptimizedOnlyIf
1652
+ );
1653
+ }
1654
+ endBatch();
1781
1655
  }
1782
1656
  function extractPromise(node, value, setter) {
1783
- if (!node.state) {
1784
- node.state = createObservable({
1785
- isLoaded: false,
1786
- }, false, extractPromise, getProxy);
1787
- }
1788
- value
1789
- .then((value) => {
1790
- setter ? setter({ value }) : set(node, value);
1791
- node.state.assign({
1792
- isLoaded: true,
1793
- error: undefined,
1794
- });
1795
- })
1796
- .catch((error) => {
1797
- node.state.error.set(error);
1657
+ if (!node.state) {
1658
+ node.state = createObservable(
1659
+ {
1660
+ isLoaded: false
1661
+ },
1662
+ false,
1663
+ extractPromise,
1664
+ getProxy
1665
+ );
1666
+ }
1667
+ value.then((value2) => {
1668
+ setter ? setter({ value: value2 }) : set(node, value2);
1669
+ node.state.assign({
1670
+ isLoaded: true,
1671
+ error: void 0
1798
1672
  });
1673
+ }).catch((error) => {
1674
+ node.state.error.set(error);
1675
+ });
1799
1676
  }
1800
1677
  function extractFunctionOrComputed(node, k, v) {
1801
- // We want to extract these types of values from the observable's raw value so that
1802
- // the raw value does not contain Promises, Observables or functions
1803
- if (isPromise(v)) {
1804
- const childNode = getChildNode(node, k);
1805
- extractPromise(childNode, v);
1806
- setNodeValue(childNode, undefined);
1807
- return undefined;
1808
- }
1809
- else if (isObservable(v)) {
1810
- const fn = () => v;
1811
- extractFunction(node, k, fn);
1812
- const childNode = getChildNode(node, k, fn);
1813
- const targetNode = getNode(v);
1814
- // Set node to target's value if activating or it's already activated
1815
- const initialValue = peek(targetNode);
1816
- setNodeValue(childNode, initialValue);
1817
- return getNodeValue(childNode);
1818
- }
1819
- else if (typeof v === 'function') {
1820
- extractFunction(node, k, v);
1821
- return k;
1822
- }
1678
+ if (isPromise(v)) {
1679
+ const childNode = getChildNode(node, k);
1680
+ extractPromise(childNode, v);
1681
+ setNodeValue(childNode, void 0);
1682
+ return void 0;
1683
+ } else if (isObservable(v)) {
1684
+ const fn = () => v;
1685
+ extractFunction(node, k, fn);
1686
+ const childNode = getChildNode(node, k, fn);
1687
+ const targetNode = getNode(v);
1688
+ const initialValue = peek(targetNode);
1689
+ setNodeValue(childNode, initialValue);
1690
+ return getNodeValue(childNode);
1691
+ } else if (typeof v === "function") {
1692
+ extractFunction(node, k, v);
1693
+ return k;
1694
+ }
1823
1695
  }
1824
1696
  function get(node, options) {
1825
- const track = options ? (isObject(options) ? options.shallow : options) : undefined;
1826
- // Track by default
1827
- updateTracking(node, track);
1828
- return peek(node);
1697
+ const track = options ? isObject(options) ? options.shallow : options : void 0;
1698
+ updateTracking(node, track);
1699
+ return peek(node);
1829
1700
  }
1830
1701
  function peek(node) {
1831
- return peekInternal(node, true);
1702
+ return peekInternal(node, true);
1832
1703
  }
1833
- let isFlushing = false;
1704
+ var isFlushing = false;
1834
1705
  function peekInternal(node, activateRecursive) {
1835
- var _a;
1836
- isFlushing = true;
1837
- // Need to refresh all dirty children when getting
1838
- if (activateRecursive && ((_a = node.dirtyChildren) === null || _a === void 0 ? void 0 : _a.size)) {
1839
- const dirty = Array.from(node.dirtyChildren);
1840
- node.dirtyChildren.clear();
1841
- dirty.forEach((node) => node.dirtyFn && peekInternal(node));
1842
- }
1843
- if (node.dirtyFn) {
1844
- const dirtyFn = node.dirtyFn;
1845
- node.dirtyFn = undefined;
1846
- globalState.dirtyNodes.delete(node);
1847
- dirtyFn();
1848
- }
1849
- isFlushing = false;
1850
- let value = getNodeValue(node);
1851
- value = checkLazy(node, value, !!activateRecursive);
1852
- return value;
1706
+ var _a;
1707
+ isFlushing = true;
1708
+ if (activateRecursive && ((_a = node.dirtyChildren) == null ? void 0 : _a.size)) {
1709
+ const dirty = Array.from(node.dirtyChildren);
1710
+ node.dirtyChildren.clear();
1711
+ dirty.forEach((node2) => node2.dirtyFn && peekInternal(node2));
1712
+ }
1713
+ if (node.dirtyFn) {
1714
+ const dirtyFn = node.dirtyFn;
1715
+ node.dirtyFn = void 0;
1716
+ globalState.dirtyNodes.delete(node);
1717
+ dirtyFn();
1718
+ }
1719
+ isFlushing = false;
1720
+ let value = getNodeValue(node);
1721
+ value = checkLazy(node, value, !!activateRecursive);
1722
+ return value;
1853
1723
  }
1854
1724
  function checkLazy(node, value, activateRecursive) {
1855
- const origValue = value;
1856
- // If node is not yet lazily computed go do that
1857
- const lazy = node.lazy;
1858
- if (lazy) {
1859
- const lazyFn = node.lazyFn;
1860
- delete node.lazy;
1861
- if (isFunction(lazyFn)) {
1862
- if (lazyFn.length === 1) {
1863
- // This is a lookup function, so return a record object
1864
- value = {};
1865
- }
1866
- else {
1867
- if (node.parent) {
1868
- const parentValue = getNodeValue(node.parent);
1869
- if (parentValue) {
1870
- delete parentValue[node.key];
1871
- }
1872
- else {
1873
- node.root._ = undefined;
1874
- }
1875
- }
1876
- value = activateNodeFunction(node, lazyFn);
1877
- }
1878
- }
1879
- else if (isObservable(value)) {
1880
- value = extractFunctionOrComputed(node.parent, node.key, value);
1881
- }
1882
- }
1883
- if ((lazy || node.needsExtract) && !isObservable(value) && !isPrimitive(value)) {
1884
- // If this is a purposeful get, check descendants for observable or auto activated linked
1885
- if (activateRecursive) {
1886
- recursivelyAutoActivate(value, node);
1887
- }
1888
- // If this is an extractable node, extract it from parent before it's accessed
1725
+ const origValue = value;
1726
+ const lazy = node.lazy;
1727
+ if (lazy) {
1728
+ const lazyFn = node.lazyFn;
1729
+ delete node.lazy;
1730
+ if (isFunction(lazyFn)) {
1731
+ if (lazyFn.length === 1) {
1732
+ value = {};
1733
+ } else {
1889
1734
  if (node.parent) {
1890
- extractFunctionOrComputed(node.parent, node.key, origValue);
1891
- }
1735
+ const parentValue = getNodeValue(node.parent);
1736
+ if (parentValue) {
1737
+ delete parentValue[node.key];
1738
+ } else {
1739
+ node.root._ = void 0;
1740
+ }
1741
+ }
1742
+ value = activateNodeFunction(node, lazyFn);
1743
+ }
1744
+ } else if (isObservable(value)) {
1745
+ value = extractFunctionOrComputed(node.parent, node.key, value);
1746
+ }
1747
+ }
1748
+ if ((lazy || node.needsExtract) && !isObservable(value) && !isPrimitive(value)) {
1749
+ if (activateRecursive) {
1750
+ recursivelyAutoActivate(value, node);
1892
1751
  }
1893
- return value;
1752
+ if (node.parent) {
1753
+ extractFunctionOrComputed(node.parent, node.key, origValue);
1754
+ }
1755
+ }
1756
+ return value;
1894
1757
  }
1895
1758
  function checkProperty(value, key) {
1896
- if (value) {
1897
- const property = Object.getOwnPropertyDescriptor(value, key);
1898
- if (property === null || property === void 0 ? void 0 : property.get) {
1899
- delete value[key];
1900
- value[key] = property.set
1901
- ? linked({
1902
- get: property.get,
1903
- set: ({ value }) => property.set(value),
1904
- })
1905
- : property.get;
1906
- }
1907
- return value[key];
1908
- }
1759
+ if (value) {
1760
+ const property = Object.getOwnPropertyDescriptor(value, key);
1761
+ if (property == null ? void 0 : property.get) {
1762
+ delete value[key];
1763
+ value[key] = property.set ? linked({
1764
+ get: property.get,
1765
+ set: ({ value: value2 }) => property.set(value2)
1766
+ }) : property.get;
1767
+ }
1768
+ return value[key];
1769
+ }
1909
1770
  }
1910
1771
  function reactivateNode(node, lazyFn) {
1911
- var _a, _b;
1912
- (_a = node.activatedObserveDispose) === null || _a === void 0 ? void 0 : _a.call(node);
1913
- (_b = node.linkedToNodeDispose) === null || _b === void 0 ? void 0 : _b.call(node);
1914
- node.activatedObserveDispose = node.linkedToNodeDispose = node.linkedToNode = undefined;
1915
- node.lazyFn = lazyFn;
1916
- node.lazy = true;
1772
+ var _a, _b;
1773
+ (_a = node.activatedObserveDispose) == null ? void 0 : _a.call(node);
1774
+ (_b = node.linkedToNodeDispose) == null ? void 0 : _b.call(node);
1775
+ node.activatedObserveDispose = node.linkedToNodeDispose = node.linkedToNode = void 0;
1776
+ node.lazyFn = lazyFn;
1777
+ node.lazy = true;
1917
1778
  }
1918
1779
  function isObserved(node) {
1919
- var _a, _b;
1920
- let parent = node;
1921
- let hasListeners = node.numListenersRecursive > 0;
1922
- while (parent && !hasListeners) {
1923
- if (!!((_a = parent.listeners) === null || _a === void 0 ? void 0 : _a.size) || !!((_b = parent.listenersImmediate) === null || _b === void 0 ? void 0 : _b.size)) {
1924
- hasListeners = true;
1925
- }
1926
- parent = parent.parent;
1780
+ var _a, _b;
1781
+ let parent = node;
1782
+ let hasListeners = node.numListenersRecursive > 0;
1783
+ while (parent && !hasListeners) {
1784
+ if (!!((_a = parent.listeners) == null ? void 0 : _a.size) || !!((_b = parent.listenersImmediate) == null ? void 0 : _b.size)) {
1785
+ hasListeners = true;
1927
1786
  }
1928
- return hasListeners;
1787
+ parent = parent.parent;
1788
+ }
1789
+ return hasListeners;
1929
1790
  }
1930
1791
  function shouldIgnoreUnobserved(node, refreshFn) {
1931
- if (!isFlushing) {
1932
- const hasListeners = isObserved(node);
1933
- if (!hasListeners) {
1934
- if (refreshFn) {
1935
- node.dirtyFn = refreshFn;
1936
- }
1937
- let parent = node;
1938
- while (parent) {
1939
- if (!parent.dirtyChildren) {
1940
- parent.dirtyChildren = new Set();
1941
- }
1942
- parent.dirtyChildren.add(node);
1943
- parent = parent.parent;
1944
- }
1945
- return true;
1792
+ if (!isFlushing) {
1793
+ const hasListeners = isObserved(node);
1794
+ if (!hasListeners) {
1795
+ if (refreshFn) {
1796
+ node.dirtyFn = refreshFn;
1797
+ }
1798
+ let parent = node;
1799
+ while (parent) {
1800
+ if (!parent.dirtyChildren) {
1801
+ parent.dirtyChildren = /* @__PURE__ */ new Set();
1946
1802
  }
1803
+ parent.dirtyChildren.add(node);
1804
+ parent = parent.parent;
1805
+ }
1806
+ return true;
1947
1807
  }
1808
+ }
1948
1809
  }
1949
1810
  function activateNodeFunction(node, lazyFn) {
1950
- // let prevTarget$: Observable<any>;
1951
- // let curTarget$: Observable<any>;
1952
- let update;
1953
- let wasPromise;
1954
- let ignoreThisUpdate;
1955
- let isFirst = true;
1956
- const activateFn = lazyFn;
1957
- let activatedValue;
1958
- let disposes = [];
1959
- let refreshFn;
1960
- function markDirty() {
1961
- node.dirtyFn = refreshFn;
1962
- globalState.dirtyNodes.add(node);
1963
- }
1964
- node.activatedObserveDispose = observe(() => {
1965
- var _a, _b, _c, _d;
1966
- // Set it to undefined so that the activation function gets undefined
1967
- // if it peeks itself
1968
- if (isFirst) {
1969
- isFirst = false;
1970
- setNodeValue(node, undefined);
1971
- }
1972
- else if (!isFlushing && refreshFn) {
1973
- if (shouldIgnoreUnobserved(node, refreshFn)) {
1974
- ignoreThisUpdate = true;
1975
- return;
1976
- }
1977
- }
1978
- // Run the function at this node
1979
- let value = activateFn();
1980
- let didSetToObs = false;
1981
- // If target is an observable, make this node a link to it
1982
- if (isObservable(value)) {
1983
- didSetToObs = true;
1984
- value = setToObservable(node, value);
1985
- }
1986
- if (isFunction(value)) {
1987
- value = value();
1988
- }
1989
- const activated = !isObservable(value)
1990
- ? value === null || value === void 0 ? void 0 : value[symbolLinked]
1991
- : undefined;
1992
- if (activated) {
1993
- node.activationState = activated;
1994
- value = undefined;
1995
- }
1996
- ignoreThisUpdate = false;
1997
- wasPromise = isPromise(value);
1998
- // Activate this node if not activated already (may be called recursively)
1999
- // TODO: Is calling recursively bad? If so can it be fixed?
2000
- if (!node.activated) {
2001
- node.activated = true;
2002
- let activateNodeFn = activateNodeBase;
2003
- // If this is a Synced then run it through persistence instead of base
2004
- if (activated === null || activated === void 0 ? void 0 : activated.synced) {
2005
- activateNodeFn = globalState.activateSyncedNode;
2006
- ignoreThisUpdate = true;
2007
- }
2008
- const result = activateNodeFn(node, value);
2009
- update = result.update;
2010
- let newValue = result.value;
2011
- if (!didSetToObs && isObservable(newValue)) {
2012
- newValue = setToObservable(node, newValue);
2013
- }
2014
- value = newValue !== null && newValue !== void 0 ? newValue : activated === null || activated === void 0 ? void 0 : activated.initial;
2015
- }
2016
- else if (node.activationState) {
2017
- const activated = node.activationState;
2018
- if ((_b = (_a = node.state) === null || _a === void 0 ? void 0 : _a.peek()) === null || _b === void 0 ? void 0 : _b.sync) {
2019
- node.state.sync();
2020
- ignoreThisUpdate = true;
1811
+ let update;
1812
+ let wasPromise;
1813
+ let ignoreThisUpdate;
1814
+ let isFirst = true;
1815
+ const activateFn = lazyFn;
1816
+ let activatedValue;
1817
+ let disposes = [];
1818
+ let refreshFn;
1819
+ function markDirty() {
1820
+ node.dirtyFn = refreshFn;
1821
+ globalState.dirtyNodes.add(node);
1822
+ }
1823
+ node.activatedObserveDispose = observe(
1824
+ () => {
1825
+ var _a, _b, _c, _d;
1826
+ if (isFirst) {
1827
+ isFirst = false;
1828
+ setNodeValue(node, void 0);
1829
+ } else if (!isFlushing && refreshFn) {
1830
+ if (shouldIgnoreUnobserved(node, refreshFn)) {
1831
+ ignoreThisUpdate = true;
1832
+ return;
1833
+ }
1834
+ }
1835
+ let value = activateFn();
1836
+ let didSetToObs = false;
1837
+ if (isObservable(value)) {
1838
+ didSetToObs = true;
1839
+ value = setToObservable(node, value);
1840
+ }
1841
+ if (isFunction(value)) {
1842
+ value = value();
1843
+ }
1844
+ const activated = !isObservable(value) ? value == null ? void 0 : value[symbolLinked] : void 0;
1845
+ if (activated) {
1846
+ node.activationState = activated;
1847
+ value = void 0;
1848
+ }
1849
+ ignoreThisUpdate = false;
1850
+ wasPromise = isPromise(value);
1851
+ if (!node.activated) {
1852
+ node.activated = true;
1853
+ let activateNodeFn = activateNodeBase;
1854
+ if (activated == null ? void 0 : activated.synced) {
1855
+ activateNodeFn = globalState.activateSyncedNode;
1856
+ ignoreThisUpdate = true;
1857
+ }
1858
+ const result = activateNodeFn(node, value);
1859
+ update = result.update;
1860
+ let newValue = result.value;
1861
+ if (!didSetToObs && isObservable(newValue)) {
1862
+ newValue = setToObservable(node, newValue);
1863
+ }
1864
+ value = newValue != null ? newValue : activated == null ? void 0 : activated.initial;
1865
+ } else if (node.activationState) {
1866
+ const activated2 = node.activationState;
1867
+ if ((_b = (_a = node.state) == null ? void 0 : _a.peek()) == null ? void 0 : _b.sync) {
1868
+ node.state.sync();
1869
+ ignoreThisUpdate = true;
1870
+ } else {
1871
+ value = (_d = (_c = activated2.get) == null ? void 0 : _c.call(activated2)) != null ? _d : activated2.initial;
1872
+ }
1873
+ }
1874
+ wasPromise = wasPromise || isPromise(value);
1875
+ return value;
1876
+ },
1877
+ (e) => {
1878
+ const { value, nodes, refresh } = e;
1879
+ refreshFn = refresh;
1880
+ if (!ignoreThisUpdate) {
1881
+ if (!wasPromise || !globalState.isLoadingRemote) {
1882
+ if (wasPromise) {
1883
+ if (node.activationState) {
1884
+ const { initial } = node.activationState;
1885
+ if (value && isPromise(value)) {
1886
+ extractPromise(node, value, update);
1887
+ }
1888
+ if (isFunction(getNodeValue(node))) {
1889
+ setNodeValue(node, initial != null ? initial : void 0);
1890
+ }
1891
+ } else if (node.activated) {
1892
+ extractPromise(node, value, update);
1893
+ if (isFunction(getNodeValue(node))) {
1894
+ setNodeValue(node, void 0);
1895
+ }
2021
1896
  }
2022
- else {
2023
- value = (_d = (_c = activated.get) === null || _c === void 0 ? void 0 : _c.call(activated)) !== null && _d !== void 0 ? _d : activated.initial;
1897
+ } else {
1898
+ activatedValue = value;
1899
+ if (node.state.isLoaded.peek()) {
1900
+ node.isComputing = true;
1901
+ set(node, value);
1902
+ node.isComputing = false;
1903
+ } else {
1904
+ setNodeValue(node, value);
1905
+ node.state.assign({
1906
+ isLoaded: true,
1907
+ error: void 0
1908
+ });
2024
1909
  }
1910
+ }
2025
1911
  }
2026
- // value is undefined if it's in a persisted retry
2027
- wasPromise = wasPromise || isPromise(value);
2028
- return value;
2029
- }, (e) => {
2030
- const { value, nodes, refresh } = e;
2031
- refreshFn = refresh;
2032
- if (!ignoreThisUpdate) {
2033
- if (!wasPromise || !globalState.isLoadingRemote) {
2034
- if (wasPromise) {
2035
- if (node.activationState) {
2036
- const { initial } = node.activationState;
2037
- if (value && isPromise(value)) {
2038
- // Extract the promise to make it set the value/error when it comes in
2039
- extractPromise(node, value, update);
2040
- }
2041
- // Set this to undefined only if it's replacing the activation function,
2042
- // so we don't overwrite it if it already has real data from either local
2043
- // cache or a previous run
2044
- if (isFunction(getNodeValue(node))) {
2045
- setNodeValue(node, initial !== null && initial !== void 0 ? initial : undefined);
2046
- }
2047
- }
2048
- else if (node.activated) {
2049
- // Extract the promise to make it set the value/error when it comes in
2050
- extractPromise(node, value, update);
2051
- // Set this to undefined only if it's replacing the activation function,
2052
- // so we don't overwrite it if it already has real data from either local
2053
- // cache or a previous run
2054
- if (isFunction(getNodeValue(node))) {
2055
- setNodeValue(node, undefined);
2056
- }
2057
- }
2058
- }
2059
- else {
2060
- activatedValue = value;
2061
- if (node.state.isLoaded.peek()) {
2062
- node.isComputing = true;
2063
- set(node, value);
2064
- node.isComputing = false;
2065
- }
2066
- else {
2067
- setNodeValue(node, value);
2068
- node.state.assign({
2069
- isLoaded: true,
2070
- error: undefined,
2071
- });
2072
- }
2073
- }
2074
- }
2075
- disposes.forEach((fn) => fn());
2076
- disposes = [];
2077
- nodes === null || nodes === void 0 ? void 0 : nodes.forEach(({ node, track }) => {
2078
- disposes.push(onChange(node, markDirty, { immediate: true, trackingType: track }));
2079
- });
2080
- }
2081
- e.cancel = true;
2082
- }, { fromComputed: true });
2083
- return activatedValue;
1912
+ disposes.forEach((fn) => fn());
1913
+ disposes = [];
1914
+ nodes == null ? void 0 : nodes.forEach(({ node: node2, track }) => {
1915
+ disposes.push(onChange(node2, markDirty, { immediate: true, trackingType: track }));
1916
+ });
1917
+ }
1918
+ e.cancel = true;
1919
+ },
1920
+ { fromComputed: true }
1921
+ );
1922
+ return activatedValue;
2084
1923
  }
2085
1924
  function activateNodeBase(node, value) {
2086
- if (!node.state) {
2087
- node.state = createObservable({
2088
- isLoaded: false,
2089
- }, false, extractPromise, getProxy);
2090
- }
2091
- if (node.activationState) {
2092
- const { set: setFn, get: getFn, initial } = node.activationState;
2093
- value = getFn === null || getFn === void 0 ? void 0 : getFn();
2094
- if (value == undefined || value === null) {
2095
- value = initial;
2096
- }
2097
- if (setFn) {
2098
- let allChanges = [];
2099
- let latestValue = undefined;
2100
- let runNumber = 0;
2101
- const runChanges = (listenerParams) => {
2102
- // Don't call the set if this is the first value coming in
2103
- if (allChanges.length > 0) {
2104
- let changes;
2105
- let value;
2106
- let loading = false;
2107
- let remote = false;
2108
- let getPrevious;
2109
- if (listenerParams) {
2110
- changes = listenerParams.changes;
2111
- value = listenerParams.value;
2112
- loading = listenerParams.loading;
2113
- remote = listenerParams.remote;
2114
- getPrevious = listenerParams.getPrevious;
2115
- }
2116
- else {
2117
- // If this is called by flushPending then get the change array
2118
- // that we've been building up.
2119
- changes = allChanges;
2120
- value = latestValue;
2121
- getPrevious = createPreviousHandler(value, changes);
2122
- }
2123
- allChanges = [];
2124
- latestValue = undefined;
2125
- globalState.pendingNodes.delete(node);
2126
- runNumber++;
2127
- const thisRunNumber = runNumber;
2128
- const run = () => {
2129
- if (thisRunNumber !== runNumber) {
2130
- // set may get called multiple times before it loads so ignore any previous runs
2131
- return;
2132
- }
2133
- node.isComputing = true;
2134
- setFn({
2135
- value,
2136
- changes,
2137
- loading,
2138
- remote,
2139
- getPrevious,
2140
- });
2141
- node.isComputing = false;
2142
- };
2143
- whenReady(node.state.isLoaded, run);
2144
- }
2145
- };
2146
- const onChangeImmediate = ({ value, changes }) => {
2147
- if (!node.isComputing) {
2148
- if (changes.length > 1 || !isFunction(changes[0].prevAtPath)) {
2149
- latestValue = value;
2150
- if (allChanges.length > 0) {
2151
- changes = changes.filter((change) => !isArraySubset(allChanges[0].path, change.path));
2152
- }
2153
- allChanges.push(...changes);
2154
- globalState.pendingNodes.set(node, runChanges);
2155
- }
2156
- }
2157
- };
2158
- // Create an immediate listener to mark this node as pending. Then actually run
2159
- // the changes at the end of the batch so everything is properly batched.
2160
- // However, this can be short circuited if the user calls get() or peek()
2161
- // in which case the set needs to run immediately so that the values are up to date.
2162
- onChange(node, onChangeImmediate, { immediate: true });
2163
- onChange(node, runChanges);
2164
- }
2165
- }
2166
- const update = ({ value }) => {
2167
- if (!node.isComputing) {
1925
+ if (!node.state) {
1926
+ node.state = createObservable(
1927
+ {
1928
+ isLoaded: false
1929
+ },
1930
+ false,
1931
+ extractPromise,
1932
+ getProxy
1933
+ );
1934
+ }
1935
+ if (node.activationState) {
1936
+ const { set: setFn, get: getFn, initial } = node.activationState;
1937
+ value = getFn == null ? void 0 : getFn();
1938
+ if (value == void 0 || value === null) {
1939
+ value = initial;
1940
+ }
1941
+ if (setFn) {
1942
+ let allChanges = [];
1943
+ let latestValue = void 0;
1944
+ let runNumber = 0;
1945
+ const runChanges = (listenerParams) => {
1946
+ if (allChanges.length > 0) {
1947
+ let changes;
1948
+ let value2;
1949
+ let loading = false;
1950
+ let remote = false;
1951
+ let getPrevious;
1952
+ if (listenerParams) {
1953
+ changes = listenerParams.changes;
1954
+ value2 = listenerParams.value;
1955
+ loading = listenerParams.loading;
1956
+ remote = listenerParams.remote;
1957
+ getPrevious = listenerParams.getPrevious;
1958
+ } else {
1959
+ changes = allChanges;
1960
+ value2 = latestValue;
1961
+ getPrevious = createPreviousHandler(value2, changes);
1962
+ }
1963
+ allChanges = [];
1964
+ latestValue = void 0;
1965
+ globalState.pendingNodes.delete(node);
1966
+ runNumber++;
1967
+ const thisRunNumber = runNumber;
1968
+ const run = () => {
1969
+ if (thisRunNumber !== runNumber) {
1970
+ return;
1971
+ }
2168
1972
  node.isComputing = true;
2169
- set(node, value);
1973
+ setFn({
1974
+ value: value2,
1975
+ changes,
1976
+ loading,
1977
+ remote,
1978
+ getPrevious
1979
+ });
2170
1980
  node.isComputing = false;
1981
+ };
1982
+ whenReady(node.state.isLoaded, run);
2171
1983
  }
2172
- };
2173
- return { update, value };
1984
+ };
1985
+ const onChangeImmediate = ({ value: value2, changes }) => {
1986
+ if (!node.isComputing) {
1987
+ if (changes.length > 1 || !isFunction(changes[0].prevAtPath)) {
1988
+ latestValue = value2;
1989
+ if (allChanges.length > 0) {
1990
+ changes = changes.filter((change) => !isArraySubset(allChanges[0].path, change.path));
1991
+ }
1992
+ allChanges.push(...changes);
1993
+ globalState.pendingNodes.set(node, runChanges);
1994
+ }
1995
+ }
1996
+ };
1997
+ onChange(node, onChangeImmediate, { immediate: true });
1998
+ onChange(node, runChanges);
1999
+ }
2000
+ }
2001
+ const update = ({ value: value2 }) => {
2002
+ if (!node.isComputing) {
2003
+ node.isComputing = true;
2004
+ set(node, value2);
2005
+ node.isComputing = false;
2006
+ }
2007
+ };
2008
+ return { update, value };
2174
2009
  }
2175
2010
  function setToObservable(node, value) {
2176
- var _a;
2177
- // If the computed is a proxy to another observable
2178
- // link it to the target observable
2179
- const linkedNode = getNode(value);
2180
- if (linkedNode !== node && (linkedNode === null || linkedNode === void 0 ? void 0 : linkedNode.linkedToNode) !== node) {
2181
- node.linkedToNode = linkedNode;
2182
- linkedNode.linkedFromNodes || (linkedNode.linkedFromNodes = new Set());
2183
- linkedNode.linkedFromNodes.add(node);
2184
- (_a = node.linkedToNodeDispose) === null || _a === void 0 ? void 0 : _a.call(node);
2185
- node.linkedToNodeDispose = onChange(linkedNode, () => {
2186
- value = peekInternal(linkedNode);
2187
- set(node, value);
2188
- }, { initial: true }, new Set([node]));
2189
- }
2190
- return value;
2011
+ var _a;
2012
+ const linkedNode = getNode(value);
2013
+ if (linkedNode !== node && (linkedNode == null ? void 0 : linkedNode.linkedToNode) !== node) {
2014
+ node.linkedToNode = linkedNode;
2015
+ linkedNode.linkedFromNodes || (linkedNode.linkedFromNodes = /* @__PURE__ */ new Set());
2016
+ linkedNode.linkedFromNodes.add(node);
2017
+ (_a = node.linkedToNodeDispose) == null ? void 0 : _a.call(node);
2018
+ node.linkedToNodeDispose = onChange(
2019
+ linkedNode,
2020
+ () => {
2021
+ value = peekInternal(linkedNode);
2022
+ set(node, value);
2023
+ },
2024
+ { initial: true },
2025
+ /* @__PURE__ */ new Set([node])
2026
+ );
2027
+ }
2028
+ return value;
2191
2029
  }
2192
2030
  function recursivelyAutoActivate(obj, node) {
2193
- if (isObject(obj) || isArray(obj)) {
2194
- const pathStack = []; // Maintain a stack for path tracking
2195
- const getNodeAtPath = () => {
2196
- var _a;
2197
- let childNode = node;
2198
- for (let i = 0; i < pathStack.length; i++) {
2199
- const { key } = pathStack[i];
2200
- const value = (_a = getNodeValue(childNode)) === null || _a === void 0 ? void 0 : _a[key];
2201
- childNode = getChildNode(childNode, key, isFunction(value) ? value : undefined);
2202
- peekInternal(childNode);
2203
- }
2204
- return childNode;
2205
- };
2206
- recursivelyAutoActivateInner(obj, pathStack, getNodeAtPath);
2207
- }
2208
- }
2209
- function recursivelyAutoActivateInner(obj, pathStack, getNodeAtPath) {
2210
- var _a;
2211
- for (const key in obj) {
2212
- if (hasOwnProperty.call(obj, key)) {
2213
- const value = obj[key];
2214
- if (isObservable(value)) {
2215
- const childNode = getNodeAtPath();
2216
- extractFunctionOrComputed(childNode, key, value);
2217
- delete childNode.lazy;
2218
- }
2219
- else {
2220
- const linkedOptions = isFunction(value) && ((_a = value.prototype) === null || _a === void 0 ? void 0 : _a[symbolLinked]);
2221
- if (linkedOptions) {
2222
- const activate = linkedOptions.activate;
2223
- if (!activate || activate === 'auto') {
2224
- const childNode = getNodeAtPath();
2225
- peek(getChildNode(childNode, key, value));
2226
- }
2227
- }
2228
- }
2229
- if (typeof value === 'object') {
2230
- pathStack.push({ key, value });
2231
- recursivelyAutoActivateInner(value, pathStack, getNodeAtPath); // Recursively traverse
2232
- pathStack.pop();
2233
- }
2234
- }
2235
- }
2031
+ if (isObject(obj) || isArray(obj)) {
2032
+ const pathStack = [];
2033
+ const getNodeAtPath2 = () => {
2034
+ var _a;
2035
+ let childNode = node;
2036
+ for (let i = 0; i < pathStack.length; i++) {
2037
+ const { key } = pathStack[i];
2038
+ const value = (_a = getNodeValue(childNode)) == null ? void 0 : _a[key];
2039
+ childNode = getChildNode(childNode, key, isFunction(value) ? value : void 0);
2040
+ peekInternal(childNode);
2041
+ }
2042
+ return childNode;
2043
+ };
2044
+ recursivelyAutoActivateInner(obj, pathStack, getNodeAtPath2);
2045
+ }
2046
+ }
2047
+ function recursivelyAutoActivateInner(obj, pathStack, getNodeAtPath2) {
2048
+ var _a;
2049
+ for (const key in obj) {
2050
+ if (hasOwnProperty.call(obj, key)) {
2051
+ const value = obj[key];
2052
+ if (isObservable(value)) {
2053
+ const childNode = getNodeAtPath2();
2054
+ extractFunctionOrComputed(childNode, key, value);
2055
+ delete childNode.lazy;
2056
+ } else {
2057
+ const linkedOptions = isFunction(value) && ((_a = value.prototype) == null ? void 0 : _a[symbolLinked]);
2058
+ if (linkedOptions) {
2059
+ const activate = linkedOptions.activate;
2060
+ if (!activate || activate === "auto") {
2061
+ const childNode = getNodeAtPath2();
2062
+ peek(getChildNode(childNode, key, value));
2063
+ }
2064
+ }
2065
+ }
2066
+ if (typeof value === "object") {
2067
+ pathStack.push({ key, value });
2068
+ recursivelyAutoActivateInner(value, pathStack, getNodeAtPath2);
2069
+ pathStack.pop();
2070
+ }
2071
+ }
2072
+ }
2236
2073
  }
2237
2074
 
2238
- const fns = ['get', 'set', 'peek', 'onChange', 'toggle'];
2075
+ // src/ObservablePrimitive.ts
2076
+ var fns = ["get", "set", "peek", "onChange", "toggle"];
2239
2077
  function ObservablePrimitiveClass(node) {
2240
- this._node = node;
2241
- // Bind to this
2242
- for (let i = 0; i < fns.length; i++) {
2243
- const key = fns[i];
2244
- this[key] = this[key].bind(this);
2245
- }
2078
+ this._node = node;
2079
+ for (let i = 0; i < fns.length; i++) {
2080
+ const key = fns[i];
2081
+ this[key] = this[key].bind(this);
2082
+ }
2246
2083
  }
2247
- // Add observable functions to prototype
2248
2084
  function proto(key, fn) {
2249
- ObservablePrimitiveClass.prototype[key] = function (...args) {
2250
- return fn.call(this, this._node, ...args);
2251
- };
2085
+ ObservablePrimitiveClass.prototype[key] = function(...args) {
2086
+ return fn.call(this, this._node, ...args);
2087
+ };
2252
2088
  }
2253
- proto('peek', (node) => {
2254
- flushPending();
2255
- return peek(node);
2089
+ proto("peek", (node) => {
2090
+ flushPending();
2091
+ return peek(node);
2256
2092
  });
2257
- proto('get', (node, options) => {
2258
- flushPending();
2259
- return get(node, options);
2093
+ proto("get", (node, options) => {
2094
+ flushPending();
2095
+ return get(node, options);
2260
2096
  });
2261
- proto('set', set);
2262
- proto('onChange', onChange);
2263
- // Getters
2097
+ proto("set", set);
2098
+ proto("onChange", onChange);
2264
2099
  Object.defineProperty(ObservablePrimitiveClass.prototype, symbolGetNode, {
2265
- configurable: true,
2266
- get() {
2267
- return this._node;
2268
- },
2100
+ configurable: true,
2101
+ get() {
2102
+ return this._node;
2103
+ }
2269
2104
  });
2270
- ObservablePrimitiveClass.prototype.toggle = function () {
2271
- const value = this.peek();
2272
- if (value === undefined || value === null || isBoolean(value)) {
2273
- this.set(!value);
2274
- }
2275
- else if (process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test') {
2276
- throw new Error('[legend-state] Cannot toggle a non-boolean value');
2277
- }
2105
+ ObservablePrimitiveClass.prototype.toggle = function() {
2106
+ const value = this.peek();
2107
+ if (value === void 0 || value === null || isBoolean(value)) {
2108
+ this.set(!value);
2109
+ } else if (process.env.NODE_ENV === "development" || process.env.NODE_ENV === "test") {
2110
+ throw new Error("[legend-state] Cannot toggle a non-boolean value");
2111
+ }
2278
2112
  };
2279
- ObservablePrimitiveClass.prototype.delete = function () {
2280
- this.set(undefined);
2281
- return this;
2113
+ ObservablePrimitiveClass.prototype.delete = function() {
2114
+ this.set(void 0);
2115
+ return this;
2282
2116
  };
2283
2117
 
2118
+ // src/observable.ts
2284
2119
  function observable(value) {
2285
- return createObservable(value, false, extractPromise, getProxy, ObservablePrimitiveClass);
2120
+ return createObservable(value, false, extractPromise, getProxy, ObservablePrimitiveClass);
2286
2121
  }
2287
2122
  function observablePrimitive(value) {
2288
- return createObservable(value, true, extractPromise, getProxy, ObservablePrimitiveClass);
2123
+ return createObservable(value, true, extractPromise, getProxy, ObservablePrimitiveClass);
2289
2124
  }
2290
2125
  function syncState(obs) {
2291
- const node = getNode(obs);
2292
- if (!node.state) {
2293
- peekInternal(node);
2294
- }
2295
- if (!node.state) {
2296
- node.state = observable({});
2297
- }
2298
- return node.state;
2126
+ const node = getNode(obs);
2127
+ if (!node.state) {
2128
+ peekInternal(node);
2129
+ }
2130
+ if (!node.state) {
2131
+ node.state = observable({});
2132
+ }
2133
+ return node.state;
2299
2134
  }
2300
2135
 
2301
- function computed(get, set) {
2302
- return observable(set ? linked({ get: get, set: ({ value }) => set(value) }) : get);
2136
+ // src/computed.ts
2137
+ function computed(get2, set2) {
2138
+ return observable(
2139
+ set2 ? linked({ get: get2, set: ({ value }) => set2(value) }) : get2
2140
+ );
2303
2141
  }
2304
2142
 
2305
- function configureLegendState({ observableFunctions, observableProperties: observableProperties$1, jsonReplacer, jsonReviver, }) {
2306
- if (observableFunctions) {
2307
- for (const key in observableFunctions) {
2308
- const fn = observableFunctions[key];
2309
- observableFns.set(key, fn);
2310
- ObservablePrimitiveClass.prototype[key] = function (...args) {
2311
- return fn.call(this, this._node, ...args);
2312
- };
2313
- }
2314
- }
2315
- if (observableProperties$1) {
2316
- for (const key in observableProperties$1) {
2317
- const fns = observableProperties$1[key];
2318
- observableProperties.set(key, fns);
2319
- Object.defineProperty(ObservablePrimitiveClass.prototype, key, {
2320
- configurable: true,
2321
- get() {
2322
- return fns.get.call(this, this._node);
2323
- },
2324
- set(value) {
2325
- return fns.set.call(this, this._node, value);
2326
- },
2327
- });
2143
+ // src/config.ts
2144
+ function configureLegendState({
2145
+ observableFunctions,
2146
+ observableProperties: observableProperties2,
2147
+ jsonReplacer,
2148
+ jsonReviver
2149
+ }) {
2150
+ if (observableFunctions) {
2151
+ for (const key in observableFunctions) {
2152
+ const fn = observableFunctions[key];
2153
+ observableFns.set(key, fn);
2154
+ ObservablePrimitiveClass.prototype[key] = function(...args) {
2155
+ return fn.call(this, this._node, ...args);
2156
+ };
2157
+ }
2158
+ }
2159
+ if (observableProperties2) {
2160
+ for (const key in observableProperties2) {
2161
+ const fns2 = observableProperties2[key];
2162
+ observableProperties.set(key, fns2);
2163
+ Object.defineProperty(ObservablePrimitiveClass.prototype, key, {
2164
+ configurable: true,
2165
+ get() {
2166
+ return fns2.get.call(this, this._node);
2167
+ },
2168
+ set(value) {
2169
+ return fns2.set.call(this, this._node, value);
2328
2170
  }
2171
+ });
2329
2172
  }
2330
- if (jsonReplacer) {
2331
- globalState.replacer = jsonReplacer;
2332
- }
2333
- if (jsonReviver) {
2334
- globalState.reviver = jsonReviver;
2335
- }
2173
+ }
2174
+ if (jsonReplacer) {
2175
+ globalState.replacer = jsonReplacer;
2176
+ }
2177
+ if (jsonReviver) {
2178
+ globalState.reviver = jsonReviver;
2179
+ }
2336
2180
  }
2337
2181
 
2182
+ // src/event.ts
2338
2183
  function event() {
2339
- // event simply wraps around a number observable
2340
- // which increments its value to dispatch change events
2341
- const obs = observable(0);
2342
- const node = getNode(obs);
2343
- node.isEvent = true;
2344
- return {
2345
- fire: function () {
2346
- // Notify increments the value so that the observable changes
2347
- obs.set((v) => v + 1);
2348
- },
2349
- on: function (cb) {
2350
- return obs.onChange(cb);
2351
- },
2352
- get: function () {
2353
- // Return the value so that when will be truthy
2354
- return obs.get();
2355
- },
2356
- // @ts-expect-error eslint doesn't like adding symbols to the object but this does work
2357
- [symbolGetNode]: node,
2358
- };
2184
+ const obs = observable(0);
2185
+ const node = getNode(obs);
2186
+ node.isEvent = true;
2187
+ return {
2188
+ fire: function() {
2189
+ obs.set((v) => v + 1);
2190
+ },
2191
+ on: function(cb) {
2192
+ return obs.onChange(cb);
2193
+ },
2194
+ get: function() {
2195
+ return obs.get();
2196
+ },
2197
+ // @ts-expect-error eslint doesn't like adding symbols to the object but this does work
2198
+ [symbolGetNode]: node
2199
+ };
2359
2200
  }
2360
2201
 
2361
- function proxy(get, set) {
2362
- return observable((key) => set
2363
- ? linked({
2364
- get: () => get(key),
2365
- set: ({ value }) => set(key, value),
2366
- })
2367
- : get(key));
2202
+ // src/proxy.ts
2203
+ function proxy(get2, set2) {
2204
+ return observable(
2205
+ (key) => set2 ? linked({
2206
+ get: () => get2(key),
2207
+ set: ({ value }) => set2(key, value)
2208
+ }) : get2(key)
2209
+ );
2368
2210
  }
2369
2211
 
2212
+ // src/retry.ts
2370
2213
  function calculateRetryDelay(retryOptions, attemptNum) {
2371
- const { backoff, delay = 1000, infinite, times = 3, maxDelay = 30000 } = retryOptions;
2372
- if (infinite || attemptNum < times) {
2373
- const delayTime = Math.min(delay * (backoff === 'constant' ? 1 : 2 ** attemptNum), maxDelay);
2374
- return delayTime;
2375
- }
2376
- return null;
2214
+ const { backoff, delay = 1e3, infinite, times = 3, maxDelay = 3e4 } = retryOptions;
2215
+ if (infinite || attemptNum < times) {
2216
+ const delayTime = Math.min(delay * (backoff === "constant" ? 1 : 2 ** attemptNum), maxDelay);
2217
+ return delayTime;
2218
+ }
2219
+ return null;
2377
2220
  }
2378
2221
  function createRetryTimeout(retryOptions, attemptNum, fn) {
2379
- const delayTime = calculateRetryDelay(retryOptions, attemptNum);
2380
- if (delayTime) {
2381
- return setTimeout(fn, delayTime);
2382
- }
2222
+ const delayTime = calculateRetryDelay(retryOptions, attemptNum);
2223
+ if (delayTime) {
2224
+ return setTimeout(fn, delayTime);
2225
+ }
2383
2226
  }
2384
2227
  function runWithRetry(node, state, fn) {
2385
- const { waitFor } = node.activationState;
2386
- const { retry } = state;
2387
- const e = { cancel: false };
2388
- let value = undefined;
2389
- if (waitFor) {
2390
- value = whenReady(waitFor, () => {
2391
- node.activationState.waitFor = undefined;
2392
- return fn(e);
2393
- });
2394
- }
2395
- else {
2396
- value = fn(e);
2397
- }
2398
- if (isPromise(value) && retry) {
2399
- let timeoutRetry;
2400
- return new Promise((resolve) => {
2401
- const run = () => {
2402
- value
2403
- .then((val) => {
2404
- node.activationState.persistedRetry = false;
2405
- resolve(val);
2406
- })
2407
- .catch(() => {
2408
- state.attemptNum++;
2409
- if (timeoutRetry) {
2410
- clearTimeout(timeoutRetry);
2411
- }
2412
- if (!e.cancel) {
2413
- timeoutRetry = createRetryTimeout(retry, state.attemptNum, () => {
2414
- value = fn(e);
2415
- run();
2416
- });
2417
- }
2418
- })
2419
- .finally(() => {
2420
- node.activationState.persistedRetry = false;
2421
- });
2422
- };
2423
- run();
2228
+ const { waitFor } = node.activationState;
2229
+ const { retry } = state;
2230
+ const e = { cancel: false };
2231
+ let value = void 0;
2232
+ if (waitFor) {
2233
+ value = whenReady(waitFor, () => {
2234
+ node.activationState.waitFor = void 0;
2235
+ return fn(e);
2236
+ });
2237
+ } else {
2238
+ value = fn(e);
2239
+ }
2240
+ if (isPromise(value) && retry) {
2241
+ let timeoutRetry;
2242
+ return new Promise((resolve) => {
2243
+ const run = () => {
2244
+ value.then((val) => {
2245
+ node.activationState.persistedRetry = false;
2246
+ resolve(val);
2247
+ }).catch(() => {
2248
+ state.attemptNum++;
2249
+ if (timeoutRetry) {
2250
+ clearTimeout(timeoutRetry);
2251
+ }
2252
+ if (!e.cancel) {
2253
+ timeoutRetry = createRetryTimeout(retry, state.attemptNum, () => {
2254
+ value = fn(e);
2255
+ run();
2256
+ });
2257
+ }
2258
+ }).finally(() => {
2259
+ node.activationState.persistedRetry = false;
2424
2260
  });
2425
- }
2426
- return value;
2261
+ };
2262
+ run();
2263
+ });
2264
+ }
2265
+ return value;
2427
2266
  }
2428
2267
 
2429
- const internal = {
2430
- createPreviousHandler,
2431
- clone,
2432
- ensureNodeValue,
2433
- findIDKey,
2434
- get,
2435
- getNode,
2436
- getNodeValue,
2437
- getPathType,
2438
- getProxy,
2439
- getValueAtPath: getValueAtPath$1,
2440
- globalState,
2441
- initializePathType,
2442
- observableFns,
2443
- optimized,
2444
- peek,
2445
- runWithRetry,
2446
- safeParse,
2447
- safeStringify,
2448
- set,
2449
- setAtPath,
2450
- setNodeValue,
2451
- symbolLinked,
2452
- symbolDelete,
2453
- tracking,
2268
+ // index.ts
2269
+ var internal = {
2270
+ createPreviousHandler,
2271
+ clone,
2272
+ ensureNodeValue,
2273
+ findIDKey,
2274
+ get,
2275
+ getNode,
2276
+ getNodeValue,
2277
+ getPathType,
2278
+ getProxy,
2279
+ getValueAtPath,
2280
+ globalState,
2281
+ initializePathType,
2282
+ observableFns,
2283
+ optimized,
2284
+ peek,
2285
+ runWithRetry,
2286
+ safeParse,
2287
+ safeStringify,
2288
+ set,
2289
+ setAtPath,
2290
+ setNodeValue,
2291
+ symbolLinked,
2292
+ symbolDelete,
2293
+ tracking
2454
2294
  };
2455
2295
 
2456
2296
  exports.ObservablePrimitiveClass = ObservablePrimitiveClass;
@@ -2509,4 +2349,3 @@ exports.tracking = tracking;
2509
2349
  exports.updateTracking = updateTracking;
2510
2350
  exports.when = when;
2511
2351
  exports.whenReady = whenReady;
2512
- //# sourceMappingURL=index.js.map