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

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 +2015 -2166
  104. package/index.mjs +2015 -2166
  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 +910 -964
  169. package/sync.mjs +920 -974
  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,2306 @@
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;
387
- }
388
- 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;
337
+ beginBatch();
338
+ globalState.isMerging = true;
339
+ for (let i = 0; i < sources.length; i++) {
340
+ target = _mergeIntoObservable(
341
+ target,
342
+ sources[i],
343
+ /*assign*/
344
+ i < sources.length - 1
345
+ );
346
+ }
347
+ globalState.isMerging = false;
348
+ endBatch();
349
+ return target;
350
+ }
351
+ function _mergeIntoObservable(target, source, assign2) {
352
+ var _a;
353
+ if (isObservable(source)) {
354
+ source = source.peek();
355
+ }
356
+ const needsSet = isObservable(target);
357
+ const targetValue = needsSet ? target.peek() : target;
358
+ const isTargetArr = isArray(targetValue);
359
+ const isTargetObj = !isTargetArr && isObject(targetValue);
360
+ if (isTargetObj && isObject(source) && !isEmpty(targetValue) || isTargetArr && targetValue.length > 0) {
361
+ const keys = Object.keys(source);
362
+ for (let i = 0; i < keys.length; i++) {
363
+ const key = keys[i];
364
+ const sourceValue = source[key];
365
+ if (sourceValue === symbolDelete) {
366
+ needsSet && ((_a = target[key]) == null ? void 0 : _a.delete) ? target[key].delete() : delete target[key];
367
+ } else {
368
+ const isObj = isObject(sourceValue);
369
+ const isArr = !isObj && isArray(sourceValue);
370
+ const targetChild = target[key];
371
+ if ((isObj || isArr) && targetChild && (needsSet || !isEmpty(targetChild))) {
372
+ if (!needsSet && (!targetChild || (isObj ? !isObject(targetChild) : !isArray(targetChild)))) {
373
+ target[key] = assign2 ? isArr ? [...sourceValue] : { ...sourceValue } : sourceValue;
374
+ } else {
375
+ _mergeIntoObservable(targetChild, sourceValue);
376
+ }
377
+ } else {
378
+ if (needsSet) {
379
+ targetChild.set(sourceValue);
380
+ } else {
381
+ const toSet = isObject(sourceValue) ? { ...sourceValue } : isArray(sourceValue) ? [...sourceValue] : sourceValue;
382
+ target[key] = toSet;
383
+ }
384
+ }
385
+ }
386
+ }
387
+ } else if (source !== void 0) {
388
+ needsSet ? target.set(source) : target = assign2 ? isArray(source) ? [...source] : { ...source } : source;
389
+ }
390
+ return target;
431
391
  }
432
392
  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;
393
+ let out;
394
+ if (path.length > 0) {
395
+ let o = out = {};
396
+ for (let i = 0; i < path.length; i++) {
397
+ const p = path[i];
398
+ o[p] = i === path.length - 1 ? value : initializePathType(pathTypes[i]);
399
+ o = o[p];
444
400
  }
445
- return out;
401
+ } else {
402
+ out = value;
403
+ }
404
+ return out;
446
405
  }
447
406
  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;
407
+ let o = value;
408
+ for (let i = 0; i < path.length; i++) {
409
+ const p = path[i];
410
+ o = o ? o[p] : initializePathType(pathTypes[i]);
411
+ }
412
+ return o;
454
413
  }
455
414
  function isObservableValueReady(value) {
456
- return !!value && ((!isObject(value) && !isArray(value)) || !isEmpty(value));
415
+ return !!value && (!isObject(value) && !isArray(value) || !isEmpty(value));
457
416
  }
458
417
  function setSilently(value$, newValue) {
459
- const node = getNode(value$);
460
- return setNodeValue(node, newValue).newValue;
418
+ const node = getNode(value$);
419
+ return setNodeValue(node, newValue).newValue;
461
420
  }
462
421
  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
- }
422
+ switch (pathType) {
423
+ case "array":
424
+ return [];
425
+ case "object":
426
+ return {};
427
+ case "map":
428
+ return /* @__PURE__ */ new Map();
429
+ case "set":
430
+ return /* @__PURE__ */ new Set();
431
+ }
473
432
  }
474
433
  function applyChange(value, change, applyPrevious) {
475
- const { path, valueAtPath, prevAtPath, pathTypes } = change;
476
- return setAtPath(value, path, pathTypes, applyPrevious ? prevAtPath : valueAtPath);
434
+ const { path, valueAtPath, prevAtPath, pathTypes } = change;
435
+ return setAtPath(value, path, pathTypes, applyPrevious ? prevAtPath : valueAtPath);
477
436
  }
478
437
  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;
438
+ for (let i = 0; i < changes.length; i++) {
439
+ value = applyChange(value, changes[i], applyPrevious);
440
+ }
441
+ return value;
483
442
  }
484
443
 
485
- let timeout;
486
- let numInBatch = 0;
487
- let isRunningBatch = false;
488
- let didDelayEndBatch = false;
489
- let _batchMap = new Map();
444
+ // src/batching.ts
445
+ var timeout;
446
+ var numInBatch = 0;
447
+ var isRunningBatch = false;
448
+ var didDelayEndBatch = false;
449
+ var _batchMap = /* @__PURE__ */ new Map();
490
450
  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
- }
451
+ if (_batchMap.size > 0) {
452
+ if (process.env.NODE_ENV === "development") {
453
+ console.error(
454
+ "Forcibly completing observableBatcher because end() was never called. This may be due to an uncaught error between begin() and end()."
455
+ );
456
+ }
457
+ endBatch(
458
+ /*force*/
459
+ true
460
+ );
461
+ }
497
462
  }
498
463
  function isArraySubset(mainArr, subsetArr) {
499
- for (let i = 0; i < mainArr.length; i++) {
500
- if (mainArr[i] !== subsetArr[i]) {
501
- return false;
502
- }
464
+ for (let i = 0; i < mainArr.length; i++) {
465
+ if (mainArr[i] !== subsetArr[i]) {
466
+ return false;
503
467
  }
504
- return true;
468
+ }
469
+ return true;
505
470
  }
506
471
  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
- }
472
+ try {
473
+ return applyChanges(value ? clone(value) : {}, changes, true);
474
+ } catch (e) {
475
+ return void 0;
476
+ }
514
477
  }
515
478
  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
- };
479
+ return function() {
480
+ return createPreviousHandlerInner(value, changes);
481
+ };
522
482
  }
523
483
  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
- }
484
+ const changesInBatch = /* @__PURE__ */ new Map();
485
+ computeChangesRecursive(
486
+ changesInBatch,
487
+ node,
488
+ /*loading*/
489
+ globalState.isLoadingLocal,
490
+ /*remote*/
491
+ globalState.isLoadingRemote,
492
+ value,
493
+ [],
494
+ [],
495
+ value,
496
+ prev,
497
+ /*immediate*/
498
+ true,
499
+ level,
500
+ whenOptimizedOnlyIf
501
+ );
502
+ if (changesInBatch.size) {
503
+ batchNotifyChanges(
504
+ changesInBatch,
505
+ /*immediate*/
506
+ true
507
+ );
508
+ }
509
+ const existing = _batchMap.get(node);
510
+ if (existing) {
511
+ existing.value = value;
512
+ } else {
513
+ _batchMap.set(node, {
514
+ value,
515
+ prev,
516
+ level,
517
+ whenOptimizedOnlyIf,
518
+ remote: globalState.isLoadingRemote,
519
+ loading: globalState.isLoadingLocal
520
+ });
521
+ }
522
+ if (numInBatch <= 0) {
523
+ runBatch();
524
+ }
553
525
  }
554
526
  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
- }
527
+ if (immediate ? node.listenersImmediate : node.listeners) {
528
+ const change = {
529
+ path,
530
+ pathTypes,
531
+ valueAtPath,
532
+ prevAtPath
533
+ };
534
+ const changeInBatch = changesInBatch.get(node);
535
+ if (changeInBatch && path.length > 0) {
536
+ const { changes } = changeInBatch;
537
+ if (!isArraySubset(changes[0].path, change.path)) {
538
+ changes.push(change);
539
+ }
540
+ } else {
541
+ changesInBatch.set(node, {
542
+ level,
543
+ value,
544
+ remote,
545
+ loading,
546
+ whenOptimizedOnlyIf,
547
+ changes: [change]
548
+ });
549
+ }
550
+ }
582
551
  }
583
552
  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
- }
553
+ computeChangesAtNode(
554
+ changesInBatch,
555
+ node,
556
+ loading,
557
+ remote,
558
+ value,
559
+ path,
560
+ pathTypes,
561
+ valueAtPath,
562
+ prevAtPath,
563
+ immediate,
564
+ level,
565
+ whenOptimizedOnlyIf
566
+ );
567
+ if (node.linkedFromNodes) {
568
+ for (const linkedFromNode of node.linkedFromNodes) {
569
+ const childNode = getNodeAtPath(linkedFromNode, path);
570
+ computeChangesRecursive(
571
+ changesInBatch,
572
+ childNode,
573
+ loading,
574
+ remote,
575
+ valueAtPath,
576
+ [],
577
+ [],
578
+ valueAtPath,
579
+ prevAtPath,
580
+ immediate,
581
+ 0,
582
+ whenOptimizedOnlyIf
583
+ );
584
+ }
585
+ }
586
+ if (node.parent) {
587
+ const parent = node.parent;
588
+ if (parent) {
589
+ const parentValue = getNodeValue(parent);
590
+ computeChangesRecursive(
591
+ changesInBatch,
592
+ parent,
593
+ loading,
594
+ remote,
595
+ parentValue,
596
+ [node.key].concat(path),
597
+ [getPathType(value)].concat(pathTypes),
598
+ valueAtPath,
599
+ prevAtPath,
600
+ immediate,
601
+ level + 1,
602
+ whenOptimizedOnlyIf
603
+ );
604
+ }
605
+ }
600
606
  }
601
607
  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
- }
608
+ const listenersNotified = /* @__PURE__ */ new Set();
609
+ changesInBatch.forEach(({ changes, level, value, loading, remote, whenOptimizedOnlyIf }, node) => {
610
+ const listeners = immediate ? node.listenersImmediate : node.listeners;
611
+ if (listeners) {
612
+ let listenerParams;
613
+ const arr = Array.from(listeners);
614
+ for (let i = 0; i < arr.length; i++) {
615
+ const listenerFn = arr[i];
616
+ const { track, noArgs, listener } = listenerFn;
617
+ if (!listenersNotified.has(listener)) {
618
+ const ok = track === true ? level <= 0 : track === optimized ? whenOptimizedOnlyIf && level <= 0 : true;
619
+ if (ok) {
620
+ if (!noArgs && !listenerParams) {
621
+ listenerParams = {
622
+ value,
623
+ loading,
624
+ remote,
625
+ getPrevious: createPreviousHandler(value, changes),
626
+ changes
627
+ };
633
628
  }
629
+ if (!track) {
630
+ listenersNotified.add(listener);
631
+ }
632
+ listener(listenerParams);
633
+ }
634
634
  }
635
- });
635
+ }
636
+ }
637
+ });
636
638
  }
637
639
  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
- }
640
+ const dirtyNodes = Array.from(globalState.dirtyNodes);
641
+ globalState.dirtyNodes.clear();
642
+ dirtyNodes.forEach((node) => {
643
+ const dirtyFn = node.dirtyFn;
644
+ if (dirtyFn) {
645
+ node.dirtyFn = void 0;
646
+ dirtyFn();
647
+ }
648
+ });
649
+ const map = _batchMap;
650
+ _batchMap = /* @__PURE__ */ new Map();
651
+ const changesInBatch = /* @__PURE__ */ new Map();
652
+ map.forEach(({ value, prev, level, loading, remote, whenOptimizedOnlyIf }, node) => {
653
+ computeChangesRecursive(
654
+ changesInBatch,
655
+ node,
656
+ loading,
657
+ remote,
658
+ value,
659
+ [],
660
+ [],
661
+ value,
662
+ prev,
663
+ false,
664
+ level,
665
+ whenOptimizedOnlyIf
666
+ );
667
+ });
668
+ if (changesInBatch.size) {
669
+ batchNotifyChanges(changesInBatch, false);
670
+ }
662
671
  }
663
672
  function batch(fn) {
664
- beginBatch();
665
- try {
666
- fn();
667
- }
668
- finally {
669
- endBatch();
670
- }
673
+ beginBatch();
674
+ try {
675
+ fn();
676
+ } finally {
677
+ endBatch();
678
+ }
671
679
  }
672
680
  function beginBatch() {
673
- numInBatch++;
674
- if (!timeout) {
675
- timeout = setTimeout(onActionTimeout, 0);
676
- }
681
+ numInBatch++;
682
+ if (!timeout) {
683
+ timeout = setTimeout(onActionTimeout, 0);
684
+ }
677
685
  }
678
686
  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
- }
687
+ numInBatch--;
688
+ if (numInBatch <= 0 || force) {
689
+ if (isRunningBatch) {
690
+ didDelayEndBatch = true;
691
+ } else {
692
+ if (timeout) {
693
+ clearTimeout(timeout);
694
+ timeout = void 0;
695
+ }
696
+ numInBatch = 0;
697
+ isRunningBatch = true;
698
+ runBatch();
699
+ isRunningBatch = false;
700
+ if (didDelayEndBatch) {
701
+ didDelayEndBatch = false;
702
+ endBatch(true);
703
+ }
704
+ }
705
+ }
702
706
  }
703
707
  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;
708
+ let o = obj;
709
+ for (let i = 0; i < path.length; i++) {
710
+ const p = path[i];
711
+ o = getChildNode(o, p);
712
+ }
713
+ return o;
710
714
  }
711
715
 
716
+ // src/linked.ts
712
717
  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;
718
+ if (isFunction(params)) {
719
+ params = { get: params };
720
+ }
721
+ if (options) {
722
+ params = { ...params, ...options };
723
+ }
724
+ const ret = function() {
725
+ return { [symbolLinked]: params };
726
+ };
727
+ ret.prototype[symbolLinked] = params;
728
+ return ret;
724
729
  }
725
730
 
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;
731
+ // src/createObservable.ts
732
+ function createObservable(value, makePrimitive, extractPromise2, createObject, createPrimitive) {
733
+ if (isObservable(value)) {
734
+ return value;
735
+ }
736
+ const valueIsPromise = isPromise(value);
737
+ const valueIsFunction = isFunction(value);
738
+ const root = {
739
+ _: value
740
+ };
741
+ let node = {
742
+ root,
743
+ lazy: true,
744
+ numListenersRecursive: 0
745
+ };
746
+ if (valueIsFunction) {
747
+ node = Object.assign(() => {
748
+ }, node);
749
+ node.lazyFn = value;
750
+ }
751
+ const prim = makePrimitive || isActualPrimitive(value);
752
+ const obs = prim ? new createPrimitive(node) : createObject(node);
753
+ if (valueIsPromise) {
754
+ setNodeValue(node, void 0);
755
+ extractPromise2(node, value);
756
+ }
757
+ return obs;
753
758
  }
754
759
 
760
+ // src/onChange.ts
755
761
  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
- };
762
+ var _a;
763
+ const { initial, immediate, noArgs } = options;
764
+ const { trackingType } = options;
765
+ let listeners = immediate ? node.listenersImmediate : node.listeners;
766
+ if (!listeners) {
767
+ listeners = /* @__PURE__ */ new Set();
768
+ if (immediate) {
769
+ node.listenersImmediate = listeners;
770
+ } else {
771
+ node.listeners = listeners;
772
+ }
773
+ }
774
+ const listener = {
775
+ listener: callback,
776
+ track: trackingType,
777
+ noArgs
778
+ };
779
+ listeners.add(listener);
780
+ if (initial) {
781
+ const value = getNodeValue(node);
782
+ callback({
783
+ value,
784
+ loading: true,
785
+ remote: false,
786
+ changes: [
787
+ {
788
+ path: [],
789
+ pathTypes: [],
790
+ prevAtPath: value,
791
+ valueAtPath: value
792
+ }
793
+ ],
794
+ getPrevious: () => void 0
795
+ });
796
+ }
797
+ let extraDisposes;
798
+ function addLinkedNodeListeners(childNode, cb = callback, from) {
799
+ if (!(fromLinks == null ? void 0 : fromLinks.has(childNode))) {
800
+ fromLinks || (fromLinks = /* @__PURE__ */ new Set());
801
+ fromLinks.add(from || node);
802
+ cb || (cb = callback);
803
+ const childOptions = {
804
+ trackingType: true,
805
+ ...options
806
+ };
807
+ extraDisposes = [...extraDisposes || [], onChange(childNode, cb, childOptions, fromLinks)];
808
+ }
809
+ }
810
+ if (node.linkedToNode) {
811
+ addLinkedNodeListeners(node.linkedToNode);
812
+ }
813
+ (_a = node.linkedFromNodes) == null ? void 0 : _a.forEach((linkedFromNode) => addLinkedNodeListeners(linkedFromNode));
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 ? 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 ? void 0 : extraDisposes.forEach((fn) => fn());
833
+ let parent2 = node;
834
+ while (parent2) {
835
+ parent2.numListenersRecursive--;
836
+ parent2 = parent2.parent;
837
+ }
838
+ };
839
839
  }
840
840
  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 };
841
+ let { valueAtPath: prevAtPath } = getValueAtPath2(getNodeValue(linkedFromNode), path);
842
+ return function({ value: valueA, loading, remote }) {
843
+ const { valueAtPath } = getValueAtPath2(valueA, path);
844
+ if (valueAtPath !== prevAtPath) {
845
+ callback({
846
+ value: valueAtPath,
847
+ loading,
848
+ remote,
849
+ changes: [
850
+ {
851
+ path: [],
852
+ pathTypes: [],
853
+ prevAtPath,
854
+ valueAtPath
855
+ }
856
+ ],
857
+ getPrevious: () => prevAtPath
858
+ });
859
+ }
860
+ prevAtPath = valueAtPath;
861
+ };
862
+ }
863
+ function getValueAtPath2(obj, path) {
864
+ let o = obj;
865
+ const pathTypes = [];
866
+ for (let i = 0; o && i < path.length; i++) {
867
+ pathTypes.push(isArray(o) ? "array" : "object");
868
+ const p = path[i];
869
+ o = o[p];
870
+ }
871
+ return { valueAtPath: o, pathTypes };
873
872
  }
874
873
 
874
+ // src/setupTracking.ts
875
875
  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
- };
876
+ let listeners = [];
877
+ nodes == null ? void 0 : nodes.forEach((tracked) => {
878
+ const { node, track } = tracked;
879
+ listeners.push(onChange(node, update, { trackingType: track, immediate, noArgs }));
880
+ });
881
+ return () => {
882
+ if (listeners) {
883
+ for (let i = 0; i < listeners.length; i++) {
884
+ listeners[i]();
885
+ }
886
+ listeners = void 0;
887
+ }
888
+ };
890
889
  }
891
890
 
892
- let trackCount = 0;
893
- const trackingQueue = [];
894
- const tracking = {
895
- current: undefined,
891
+ // src/tracking.ts
892
+ var trackCount = 0;
893
+ var trackingQueue = [];
894
+ var tracking = {
895
+ current: void 0
896
896
  };
897
897
  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 = {};
898
+ trackingQueue.push(tracking.current);
899
+ trackCount++;
900
+ tracking.current = {};
903
901
  }
904
902
  function endTracking() {
905
- // Restore the previous tracking context
906
- trackCount--;
907
- if (trackCount < 0) {
908
- trackCount = 0;
909
- }
910
- tracking.current = trackingQueue.pop();
903
+ trackCount--;
904
+ if (trackCount < 0) {
905
+ trackCount = 0;
906
+ }
907
+ tracking.current = trackingQueue.pop();
911
908
  }
912
909
  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
- }
910
+ if (trackCount) {
911
+ const tracker = tracking.current;
912
+ if (tracker) {
913
+ if (!tracker.nodes) {
914
+ tracker.nodes = /* @__PURE__ */ new Map();
915
+ }
916
+ const existing = tracker.nodes.get(node);
917
+ if (existing) {
918
+ existing.track = existing.track || track;
919
+ existing.num++;
920
+ } else {
921
+ tracker.nodes.set(node, { node, track, num: 1 });
922
+ }
923
+ }
924
+ }
929
925
  }
930
926
 
927
+ // src/trackSelector.ts
931
928
  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 };
929
+ var _a;
930
+ let dispose;
931
+ let resubscribe;
932
+ let updateFn = update;
933
+ beginTracking();
934
+ const value = selector ? computeSelector(selector, observeEvent, observeOptions == null ? void 0 : observeOptions.fromComputed) : selector;
935
+ const tracker = tracking.current;
936
+ const nodes = tracker.nodes;
937
+ endTracking();
938
+ if ((process.env.NODE_ENV === "development" || process.env.NODE_ENV === "test") && tracker && nodes) {
939
+ (_a = tracker.traceListeners) == null ? void 0 : _a.call(tracker, nodes);
940
+ if (tracker.traceUpdates) {
941
+ updateFn = tracker.traceUpdates(update);
942
+ }
943
+ tracker.traceListeners = void 0;
944
+ tracker.traceUpdates = void 0;
945
+ }
946
+ if (!(observeEvent == null ? void 0 : observeEvent.cancel)) {
947
+ dispose = setupTracking(nodes, updateFn, false, observeOptions == null ? void 0 : observeOptions.immediate);
948
+ if (process.env.NODE_ENV === "development" || process.env.NODE_ENV === "test") {
949
+ resubscribe = createResubscribe ? () => {
950
+ dispose == null ? void 0 : dispose();
951
+ dispose = setupTracking(nodes, updateFn);
952
+ return dispose;
953
+ } : void 0;
954
+ }
955
+ }
956
+ return { nodes, value, dispose, resubscribe };
966
957
  }
967
958
 
959
+ // src/observe.ts
968
960
  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
- };
961
+ let reaction;
962
+ if (isFunction(reactionOrOptions)) {
963
+ reaction = reactionOrOptions;
964
+ } else {
965
+ options = reactionOrOptions;
966
+ }
967
+ let dispose;
968
+ const e = { num: 0 };
969
+ const update = function() {
970
+ if (e.onCleanup) {
971
+ e.onCleanup();
972
+ e.onCleanup = void 0;
973
+ }
974
+ beginBatch();
975
+ delete e.value;
976
+ dispose == null ? void 0 : dispose();
977
+ const { dispose: _dispose, value, nodes } = trackSelector(selectorOrRun, update, e, options);
978
+ dispose = _dispose;
979
+ e.value = value;
980
+ e.nodes = nodes;
981
+ e.refresh = update;
982
+ if (e.onCleanupReaction) {
983
+ e.onCleanupReaction();
984
+ e.onCleanupReaction = void 0;
985
+ }
986
+ endBatch();
987
+ if (reaction && ((options == null ? void 0 : options.fromComputed) || (e.num > 0 || !isEvent(selectorOrRun)) && (e.previous !== e.value || typeof e.value === "object"))) {
988
+ reaction(e);
989
+ }
990
+ e.previous = e.value;
991
+ e.num++;
992
+ };
993
+ update();
994
+ return () => {
995
+ var _a, _b;
996
+ (_a = e.onCleanup) == null ? void 0 : _a.call(e);
997
+ e.onCleanup = void 0;
998
+ (_b = e.onCleanupReaction) == null ? void 0 : _b.call(e);
999
+ e.onCleanupReaction = void 0;
1000
+ dispose == null ? void 0 : dispose();
1001
+ };
1022
1002
  }
1023
1003
 
1004
+ // src/when.ts
1024
1005
  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;
1006
+ if (isPromise(predicate)) {
1007
+ return effect ? predicate.then(effect) : predicate;
1008
+ }
1009
+ let value;
1010
+ let effectValue;
1011
+ function run(e) {
1012
+ const ret = computeSelector(predicate);
1013
+ if (isPromise(ret)) {
1014
+ value = ret;
1015
+ return void 0;
1016
+ } else if (!isPromise(ret) && (checkReady ? isObservableValueReady(ret) : ret)) {
1017
+ value = ret;
1018
+ e.cancel = true;
1076
1019
  }
1020
+ return value;
1021
+ }
1022
+ function doEffect() {
1023
+ effectValue = effect == null ? void 0 : effect(value);
1024
+ }
1025
+ observe(run, doEffect);
1026
+ if (isPromise(value)) {
1027
+ return effect ? value.then(effect) : value;
1028
+ } else if (value !== void 0) {
1029
+ return effect ? effectValue : Promise.resolve(value);
1030
+ } else {
1031
+ const promise = new Promise((resolve) => {
1032
+ if (effect) {
1033
+ const originalEffect = effect;
1034
+ effect = (value2) => {
1035
+ const effectValue2 = originalEffect(value2);
1036
+ resolve(isPromise(effectValue2) ? effectValue2.then((value3) => value3) : effectValue2);
1037
+ };
1038
+ } else {
1039
+ effect = resolve;
1040
+ }
1041
+ });
1042
+ return promise;
1043
+ }
1077
1044
  }
1078
1045
  function when(predicate, effect) {
1079
- return _when(predicate, effect, false);
1046
+ return _when(predicate, effect, false);
1080
1047
  }
1081
1048
  function whenReady(predicate, effect) {
1082
- return _when(predicate, effect, true);
1049
+ return _when(predicate, effect, true);
1083
1050
  }
1084
1051
 
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',
1052
+ // src/ObservableObject.ts
1053
+ var ArrayModifiers = /* @__PURE__ */ new Set([
1054
+ "copyWithin",
1055
+ "fill",
1056
+ "from",
1057
+ "pop",
1058
+ "push",
1059
+ "reverse",
1060
+ "shift",
1061
+ "sort",
1062
+ "splice",
1063
+ "unshift"
1096
1064
  ]);
1097
- const ArrayLoopers = new Set([
1098
- 'every',
1099
- 'filter',
1100
- 'find',
1101
- 'findIndex',
1102
- 'forEach',
1103
- 'join',
1104
- 'map',
1105
- 'reduce',
1106
- 'some',
1065
+ var ArrayLoopers = /* @__PURE__ */ new Set([
1066
+ "every",
1067
+ "filter",
1068
+ "find",
1069
+ "findIndex",
1070
+ "forEach",
1071
+ "join",
1072
+ "map",
1073
+ "reduce",
1074
+ "some"
1107
1075
  ]);
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],
1076
+ var ArrayLoopersReturn = /* @__PURE__ */ new Set(["filter", "find"]);
1077
+ var observableProperties = /* @__PURE__ */ new Map();
1078
+ var observableFns = /* @__PURE__ */ new Map([
1079
+ ["get", get],
1080
+ ["set", set],
1081
+ ["peek", peek],
1082
+ ["onChange", onChange],
1083
+ ["assign", assign],
1084
+ ["delete", deleteFn],
1085
+ ["toggle", toggle]
1118
1086
  ]);
1119
- if (process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test') {
1120
- // eslint-disable-next-line no-var
1121
- var __devUpdateNodes = new Set();
1087
+ if (process.env.NODE_ENV === "development" || process.env.NODE_ENV === "test") {
1088
+ __devUpdateNodes = /* @__PURE__ */ new Set();
1122
1089
  }
1090
+ var __devUpdateNodes;
1123
1091
  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;
1092
+ var _a;
1093
+ if (prop === "push" && args.length === 1) {
1094
+ setKey(node, target.length + "", args[0]);
1095
+ } else {
1096
+ const prevValue = target.slice();
1097
+ const ret = target[prop].apply(target, args);
1098
+ if (node) {
1099
+ const hasParent = isChildNodeValue(node);
1100
+ const key = hasParent ? node.key : "_";
1101
+ const parentValue = hasParent ? getNodeValue(node.parent) : node.root;
1102
+ parentValue[key] = prevValue;
1103
+ setKey((_a = node.parent) != null ? _a : node, key, target);
1143
1104
  }
1105
+ return ret;
1106
+ }
1144
1107
  }
1145
- function getKeys(obj, isArr, isMap) {
1146
- return isArr ? undefined : obj ? (isMap ? Array.from(obj.keys()) : Object.keys(obj)) : [];
1108
+ function getKeys(obj, isArr, isMap2) {
1109
+ return isArr ? void 0 : obj ? isMap2 ? Array.from(obj.keys()) : Object.keys(obj) : [];
1147
1110
  }
1148
1111
  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
- }
1112
+ var _a, _b, _c;
1113
+ if ((process.env.NODE_ENV === "development" || process.env.NODE_ENV === "test") && typeof __devUpdateNodes !== "undefined" && isObject(obj)) {
1114
+ if (__devUpdateNodes.has(obj)) {
1115
+ console.error(
1116
+ "[legend-state] Circular reference detected in object. You may want to use opaqueObject to stop traversing child nodes.",
1117
+ obj
1118
+ );
1119
+ return false;
1120
+ }
1121
+ __devUpdateNodes.add(obj);
1122
+ }
1123
+ if (isObject(obj) && obj[symbolOpaque] || isObject(prevValue) && prevValue[symbolOpaque]) {
1124
+ const isDiff = obj !== prevValue;
1125
+ if (isDiff) {
1126
+ if (parent.listeners || parent.listenersImmediate) {
1127
+ notify(parent, obj, prevValue, 0);
1128
+ }
1129
+ }
1130
+ if ((process.env.NODE_ENV === "development" || process.env.NODE_ENV === "test") && typeof __devUpdateNodes !== "undefined" && obj !== void 0) {
1131
+ __devUpdateNodes.delete(obj);
1132
+ }
1133
+ return isDiff;
1134
+ }
1135
+ const isArr = isArray(obj);
1136
+ let prevChildrenById;
1137
+ let moved;
1138
+ const isCurMap = isMap(obj);
1139
+ const isPrevMap = isMap(prevValue);
1140
+ const keys = getKeys(obj, isArr, isCurMap);
1141
+ const keysPrev = getKeys(prevValue, isArr, isPrevMap);
1142
+ const length = ((_a = keys || obj) == null ? void 0 : _a.length) || 0;
1143
+ const lengthPrev = ((_b = keysPrev || prevValue) == null ? void 0 : _b.length) || 0;
1144
+ let idField;
1145
+ let isIdFieldFunction;
1146
+ let hasADiff = false;
1147
+ let retValue;
1148
+ if (isArr && isArray(prevValue)) {
1149
+ if (prevValue.length > 0) {
1150
+ const firstPrevValue = prevValue[0];
1151
+ if (firstPrevValue !== void 0) {
1152
+ idField = findIDKey(firstPrevValue, parent);
1153
+ if (idField) {
1154
+ isIdFieldFunction = isFunction(idField);
1155
+ prevChildrenById = /* @__PURE__ */ new Map();
1156
+ moved = [];
1157
+ }
1158
+ const keysSeen = process.env.NODE_ENV === "development" || process.env.NODE_ENV === "test" ? /* @__PURE__ */ new Set() : void 0;
1159
+ if (parent.children) {
1160
+ for (let i = 0; i < prevValue.length; i++) {
1161
+ const p = prevValue[i];
1162
+ if (p) {
1163
+ const child = parent.children.get(i + "");
1164
+ if (child) {
1165
+ if (!obj[i]) {
1166
+ handleDeletedChild(child, p);
1302
1167
  }
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);
1168
+ if (idField) {
1169
+ const key = isIdFieldFunction ? idField(p) : p[idField];
1170
+ if (process.env.NODE_ENV === "development" || process.env.NODE_ENV === "test") {
1171
+ if (keysSeen.has(key)) {
1172
+ console.warn(
1173
+ `[legend-state] Warning: Multiple elements in array have the same ID. Key field: ${idField}, Array:`,
1174
+ prevValue
1175
+ );
1326
1176
  }
1177
+ keysSeen.add(key);
1178
+ }
1179
+ prevChildrenById.set(key, child);
1327
1180
  }
1181
+ }
1328
1182
  }
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);
1183
+ }
1184
+ }
1185
+ }
1186
+ }
1187
+ } else if (prevValue && (!obj || isObject(obj))) {
1188
+ const lengthPrev2 = keysPrev.length;
1189
+ for (let i = 0; i < lengthPrev2; i++) {
1190
+ const key = keysPrev[i];
1191
+ if (!keys.includes(key)) {
1192
+ hasADiff = true;
1193
+ const child = getChildNode(parent, key);
1194
+ const prev = isPrevMap ? prevValue.get(key) : prevValue[key];
1195
+ if (prev !== void 0) {
1196
+ handleDeletedChild(child, prev);
1197
+ }
1198
+ }
1199
+ }
1200
+ }
1201
+ if (obj && !isPrimitive(obj)) {
1202
+ hasADiff = hasADiff || length !== lengthPrev;
1203
+ const isArrDiff = hasADiff;
1204
+ let didMove = false;
1205
+ for (let i = 0; i < length; i++) {
1206
+ const key = isArr ? i + "" : keys[i];
1207
+ let value = isCurMap ? obj.get(key) : obj[key];
1208
+ const prev = isPrevMap ? prevValue == null ? void 0 : prevValue.get(key) : prevValue == null ? void 0 : prevValue[key];
1209
+ let isDiff = !equals(value, prev);
1210
+ if (isDiff) {
1211
+ const id = idField && value ? isIdFieldFunction ? idField(value) : value[idField] : void 0;
1212
+ const existingChild = (_c = parent.children) == null ? void 0 : _c.get(key);
1213
+ if (isObservable(value)) {
1214
+ const valueNode = getNode(value);
1215
+ if ((existingChild == null ? void 0 : existingChild.linkedToNode) === valueNode) {
1216
+ const targetValue = getNodeValue(valueNode);
1217
+ isCurMap ? obj.set(key, targetValue) : obj[key] = targetValue;
1218
+ continue;
1219
+ }
1220
+ const obs = value;
1221
+ value = () => obs;
1222
+ }
1223
+ let child = getChildNode(parent, key, value);
1224
+ if (!child.lazy && (isFunction(value) || isObservable(value))) {
1225
+ reactivateNode(child, value);
1226
+ peekInternal(child);
1227
+ }
1228
+ if (isArr && id !== void 0) {
1229
+ const prevChild = id !== void 0 ? prevChildrenById == null ? void 0 : prevChildrenById.get(id) : void 0;
1230
+ if (!prevChild) {
1231
+ hasADiff = true;
1232
+ } else if (prevChild !== void 0 && prevChild.key !== key) {
1233
+ const valuePrevChild = prevValue[prevChild.key];
1234
+ if (isArrDiff) {
1235
+ child = prevChild;
1236
+ parent.children.delete(child.key);
1237
+ child.key = key;
1238
+ moved.push([key, child]);
1334
1239
  }
1240
+ didMove = true;
1241
+ isDiff = valuePrevChild !== value;
1242
+ }
1335
1243
  }
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;
1244
+ if (isDiff) {
1245
+ if (isFunction(value) || isObservable(value)) {
1246
+ extractFunctionOrComputed(parent, key, value);
1247
+ } else if (isPrimitive(value)) {
1248
+ hasADiff = true;
1249
+ } else {
1250
+ const updatedNodes = updateNodes(child, value, prev);
1251
+ hasADiff = hasADiff || updatedNodes;
1252
+ isDiff = updatedNodes;
1253
+ }
1254
+ }
1255
+ if (isDiff || isArr && !isArrDiff) {
1256
+ if (child.listeners || child.listenersImmediate) {
1257
+ notify(child, value, prev, 0, !isArrDiff);
1258
+ }
1259
+ }
1260
+ }
1261
+ }
1262
+ if (moved) {
1263
+ for (let i = 0; i < moved.length; i++) {
1264
+ const [key, child] = moved[i];
1265
+ parent.children.set(key, child);
1266
+ }
1267
+ }
1268
+ retValue = hasADiff || didMove;
1269
+ } else if (prevValue !== void 0) {
1270
+ retValue = true;
1271
+ }
1272
+ if ((process.env.NODE_ENV === "development" || process.env.NODE_ENV === "test") && typeof __devUpdateNodes !== "undefined" && obj !== void 0) {
1273
+ __devUpdateNodes.delete(obj);
1274
+ }
1275
+ return retValue != null ? retValue : false;
1350
1276
  }
1351
1277
  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
- }
1278
+ var _a, _b;
1279
+ (_a = child.linkedToNodeDispose) == null ? void 0 : _a.call(child);
1280
+ (_b = child.activatedObserveDispose) == null ? void 0 : _b.call(child);
1281
+ if (!isPrimitive(p)) {
1282
+ updateNodes(child, void 0, p);
1283
+ }
1284
+ if (child.listeners || child.listenersImmediate) {
1285
+ notify(child, void 0, p, 0);
1286
+ }
1363
1287
  }
1364
1288
  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)));
1289
+ if (p !== void 0)
1290
+ node = getChildNode(node, p, asFunction);
1291
+ return node.proxy || (node.proxy = new Proxy(node, proxyHandler));
1370
1292
  }
1371
1293
  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
- }
1294
+ if (globalState.pendingNodes.size > 0) {
1295
+ const nodes = Array.from(globalState.pendingNodes.values());
1296
+ globalState.pendingNodes.clear();
1297
+ nodes.forEach((fn) => fn());
1298
+ }
1299
+ }
1300
+ var proxyHandler = {
1301
+ get(node, p, receiver) {
1302
+ var _a, _b;
1303
+ if (p === symbolToPrimitive) {
1304
+ throw new Error(
1305
+ 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."
1306
+ );
1307
+ }
1308
+ if (p === symbolGetNode) {
1309
+ return node;
1310
+ }
1311
+ if (p === "apply") {
1312
+ const nodeValue = getNodeValue(node);
1313
+ if (isFunction(nodeValue)) {
1314
+ return nodeValue.apply;
1315
+ }
1316
+ }
1317
+ let value = peekInternal(
1318
+ node,
1319
+ /*activateRecursive*/
1320
+ p === "get" || p === "peek"
1321
+ );
1322
+ const targetNode = node.linkedToNode || (value == null ? void 0 : value[symbolGetNode]);
1323
+ if (targetNode && p !== "onChange") {
1324
+ return proxyHandler.get(targetNode, p, receiver);
1325
+ }
1326
+ if (isMap(value) || value instanceof WeakMap || value instanceof Set || value instanceof WeakSet) {
1327
+ const ret = handlerMapSet(node, p, value);
1328
+ if (ret !== void 0) {
1329
+ return ret;
1330
+ }
1331
+ }
1332
+ const fn = observableFns.get(p);
1333
+ if (fn) {
1334
+ if (p === "get" || p === "peek") {
1335
+ flushPending();
1336
+ }
1337
+ return function(a, b, c) {
1338
+ const l = arguments.length;
1339
+ switch (l) {
1340
+ case 0:
1341
+ return fn(node);
1342
+ case 1:
1343
+ return fn(node, a);
1344
+ case 2:
1345
+ return fn(node, a, b);
1346
+ default:
1347
+ return fn(node, a, b, c);
1348
+ }
1349
+ };
1350
+ }
1351
+ const property = observableProperties.get(p);
1352
+ if (property) {
1353
+ return property.get(node);
1354
+ }
1355
+ let vProp = value == null ? void 0 : value[p];
1356
+ if (isObject(value) && value[symbolOpaque]) {
1357
+ return vProp;
1358
+ }
1359
+ const fnOrComputed = (_a = node.functions) == null ? void 0 : _a.get(p);
1360
+ if (fnOrComputed) {
1361
+ if (isObservable(fnOrComputed)) {
1362
+ return fnOrComputed;
1363
+ } else {
1364
+ return getProxy(node, p, fnOrComputed);
1365
+ }
1366
+ } else {
1367
+ vProp = checkProperty(value, p);
1368
+ }
1369
+ if (isNullOrUndefined(value) && vProp === void 0 && (ArrayModifiers.has(p) || ArrayLoopers.has(p))) {
1370
+ value = [];
1371
+ setNodeValue(node, value);
1372
+ vProp = value[p];
1373
+ }
1374
+ if (isFunction(vProp)) {
1375
+ if (isArray(value)) {
1376
+ if (ArrayModifiers.has(p)) {
1377
+ return (...args) => collectionSetter(node, value, p, ...args);
1378
+ } else if (ArrayLoopers.has(p)) {
1379
+ updateTracking(node, true);
1380
+ return function(cbOrig, thisArg) {
1381
+ const isReduce = p === "reduce";
1382
+ const cbWrapped = isReduce ? (previousValue, currentValue, currentIndex, array) => {
1383
+ return cbOrig(
1384
+ previousValue,
1385
+ getProxy(node, currentIndex + "", currentValue),
1386
+ currentIndex,
1387
+ array
1388
+ );
1389
+ } : (val, index, array) => {
1390
+ return cbOrig(getProxy(node, index + "", val), index, array);
1432
1391
  };
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;
1392
+ if (isReduce || !ArrayLoopersReturn.has(p)) {
1393
+ return value[p](cbWrapped, thisArg);
1446
1394
  }
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);
1395
+ const isFind = p === "find";
1396
+ const out = [];
1397
+ for (let i = 0; i < value.length; i++) {
1398
+ if (cbWrapped(value[i], i, value)) {
1399
+ const proxy2 = getProxy(node, i + "");
1400
+ if (isFind) {
1401
+ return proxy2;
1465
1402
  }
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;
1403
+ out.push(proxy2);
1404
+ }
1512
1405
  }
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
- },
1406
+ return isFind ? void 0 : out;
1407
+ };
1408
+ }
1409
+ }
1410
+ extractFunctionOrComputed(node, p, vProp);
1411
+ const fnOrComputed2 = (_b = node.functions) == null ? void 0 : _b.get(p);
1412
+ if (fnOrComputed2) {
1413
+ return getProxy(node, p, fnOrComputed2);
1414
+ }
1415
+ return vProp.bind(value);
1416
+ }
1417
+ if (isPrimitive(vProp)) {
1418
+ if (isArray(value) && p === "length") {
1419
+ updateTracking(node, true);
1420
+ return vProp;
1421
+ }
1422
+ }
1423
+ return getProxy(node, p);
1424
+ },
1425
+ // Forward all proxy properties to the target's value
1426
+ getPrototypeOf(node) {
1427
+ const value = getNodeValue(node);
1428
+ return value !== null && typeof value === "object" ? Reflect.getPrototypeOf(value) : null;
1429
+ },
1430
+ ownKeys(node) {
1431
+ peekInternal(node);
1432
+ const value = get(node, true);
1433
+ if (isPrimitive(value))
1434
+ return [];
1435
+ const keys = value ? Reflect.ownKeys(value) : [];
1436
+ if (isArray(value) && keys[keys.length - 1] === "length") {
1437
+ keys.splice(keys.length - 1, 1);
1438
+ }
1439
+ if (isFunction(node)) {
1440
+ const reflectedKeys = Reflect.ownKeys(node);
1441
+ ["caller", "arguments", "prototype"].forEach((key) => reflectedKeys.includes(key) && keys.push(key));
1442
+ }
1443
+ return keys;
1444
+ },
1445
+ getOwnPropertyDescriptor(node, prop) {
1446
+ if (prop === "caller" || prop === "arguments" || prop === "prototype") {
1447
+ return { configurable: false, enumerable: false };
1448
+ }
1449
+ const value = getNodeValue(node);
1450
+ return isPrimitive(value) ? void 0 : Reflect.getOwnPropertyDescriptor(value, prop);
1451
+ },
1452
+ set(node, prop, value) {
1453
+ if (node.isSetting) {
1454
+ return Reflect.set(node, prop, value);
1455
+ }
1456
+ if (node.isAssigning) {
1457
+ setKey(node, prop, value);
1458
+ return true;
1459
+ }
1460
+ const property = observableProperties.get(prop);
1461
+ if (property) {
1462
+ property.set(node, value);
1463
+ return true;
1464
+ }
1465
+ if (process.env.NODE_ENV === "development") {
1466
+ console.warn("[legend-state]: Error: Cannot set a value directly:", prop, value);
1467
+ }
1468
+ return false;
1469
+ },
1470
+ deleteProperty(node, prop) {
1471
+ if (node.isSetting) {
1472
+ return Reflect.deleteProperty(node, prop);
1473
+ } else {
1474
+ if (process.env.NODE_ENV === "development") {
1475
+ console.warn("[legend-state]: Error: Cannot delete a value directly:", prop);
1476
+ }
1477
+ return false;
1478
+ }
1479
+ },
1480
+ has(node, prop) {
1481
+ const value = getNodeValue(node);
1482
+ return Reflect.has(value, prop);
1483
+ },
1484
+ apply(target, thisArg, argArray) {
1485
+ if (isObservable(thisArg)) {
1486
+ thisArg = thisArg.peek();
1487
+ }
1488
+ return Reflect.apply(target.lazyFn || target, thisArg, argArray);
1489
+ }
1591
1490
  };
1592
1491
  function set(node, newValue) {
1593
- if (node.parent) {
1594
- setKey(node.parent, node.key, newValue);
1595
- }
1596
- else {
1597
- setKey(node, '_', newValue);
1598
- }
1492
+ if (node.parent) {
1493
+ setKey(node.parent, node.key, newValue);
1494
+ } else {
1495
+ setKey(node, "_", newValue);
1496
+ }
1599
1497
  }
1600
1498
  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
- }
1499
+ const value = getNodeValue(node);
1500
+ if (value === void 0 || value === null || isBoolean(value)) {
1501
+ set(node, !value);
1502
+ } else if (process.env.NODE_ENV === "development" || process.env.NODE_ENV === "test") {
1503
+ throw new Error("[legend-state] Cannot toggle a non-boolean value");
1504
+ }
1608
1505
  }
1609
1506
  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
- }
1507
+ if (process.env.NODE_ENV === "development") {
1508
+ if (typeof HTMLElement !== "undefined" && newValue instanceof HTMLElement) {
1509
+ console.warn(`[legend-state] Set an HTMLElement into state. You probably don't want to do that.`);
1510
+ }
1511
+ }
1512
+ const isRoot = !node.parent && key === "_";
1513
+ if (node.parent && !getNodeValue(node) && !isFunction(newValue)) {
1514
+ set(node, { [key]: newValue });
1515
+ }
1516
+ const childNode = isRoot ? node : getChildNode(node, key, newValue);
1517
+ if (isObservable(newValue)) {
1518
+ setToObservable(childNode, newValue);
1519
+ } else {
1520
+ const { newValue: savedValue, prevValue } = setNodeValue(childNode, newValue);
1521
+ const isPrim = isPrimitive(savedValue) || savedValue instanceof Date;
1522
+ if (!equals(savedValue, prevValue)) {
1523
+ updateNodesAndNotify(node, savedValue, prevValue, childNode, isPrim, isRoot, level);
1524
+ }
1525
+ if (!isPrim) {
1526
+ childNode.needsExtract = true;
1527
+ }
1528
+ extractFunctionOrComputed(node, key, savedValue);
1529
+ }
1636
1530
  }
1637
1531
  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
- }
1532
+ const proxy2 = getProxy(node);
1533
+ beginBatch();
1534
+ if (isPrimitive(node.root._)) {
1535
+ node.root._ = {};
1536
+ }
1537
+ if (isMap(value)) {
1538
+ const currentValue = getNodeValue(node);
1539
+ if (isMap(currentValue)) {
1540
+ value.forEach((value2, key) => currentValue.set(key, value2));
1541
+ }
1542
+ } else {
1543
+ node.isAssigning = (node.isAssigning || 0) + 1;
1544
+ try {
1545
+ Object.assign(proxy2, value);
1546
+ } finally {
1547
+ node.isAssigning--;
1659
1548
  }
1660
- endBatch();
1661
- return proxy;
1549
+ }
1550
+ endBatch();
1551
+ return proxy2;
1662
1552
  }
1663
1553
  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
- }
1554
+ if (key === void 0 && isChildNodeValue(node)) {
1555
+ key = node.key;
1556
+ node = node.parent;
1557
+ }
1558
+ const value = getNodeValue(node);
1559
+ if (isArray(value)) {
1560
+ collectionSetter(node, value, "splice", key, 1);
1561
+ } else {
1562
+ setKey(
1563
+ node,
1564
+ key != null ? key : "_",
1565
+ symbolDelete,
1566
+ /*level*/
1567
+ -1
1568
+ );
1569
+ }
1676
1570
  }
1677
1571
  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
- }
1572
+ const vProp = value == null ? void 0 : value[p];
1573
+ if (p === "size") {
1574
+ return getProxy(node, p);
1575
+ } else if (isFunction(vProp)) {
1576
+ return function(a, b, c) {
1577
+ const l = arguments.length;
1578
+ const valueMap = value;
1579
+ if (p === "get") {
1580
+ if (l > 0 && typeof a !== "boolean" && a !== optimized) {
1581
+ return getProxy(node, a);
1582
+ }
1583
+ } else if (p === "set") {
1584
+ if (l === 2) {
1585
+ const prev = valueMap.get(a);
1586
+ const ret = valueMap.set(a, b);
1587
+ if (prev !== b) {
1588
+ updateNodesAndNotify(getChildNode(node, a), b, prev);
1589
+ }
1590
+ return ret;
1591
+ } else if (l === 1 && isMap(value)) {
1592
+ set(node, a);
1593
+ }
1594
+ } else if (p === "delete") {
1595
+ if (l > 0) {
1596
+ const prev = value.get ? valueMap.get(a) : a;
1597
+ const ret = value.delete(a);
1598
+ if (ret) {
1599
+ updateNodesAndNotify(getChildNode(node, a), void 0, prev);
1600
+ }
1601
+ return ret;
1602
+ }
1603
+ } else if (p === "clear") {
1604
+ const prev = new Map(valueMap);
1605
+ const size = valueMap.size;
1606
+ valueMap.clear();
1607
+ if (size) {
1608
+ updateNodesAndNotify(node, value, prev);
1609
+ }
1610
+ return;
1611
+ } else if (p === "add") {
1612
+ const prev = new Set(value);
1613
+ const ret = value.add(a);
1614
+ if (!value.has(p)) {
1615
+ notify(node, ret, prev, 0);
1616
+ }
1617
+ return ret;
1618
+ }
1619
+ const fn = observableFns.get(p);
1620
+ if (fn) {
1621
+ switch (l) {
1622
+ case 0:
1623
+ return fn(node);
1624
+ case 1:
1625
+ return fn(node, a);
1626
+ case 2:
1627
+ return fn(node, a, b);
1628
+ default:
1629
+ return fn(node, a, b, c);
1630
+ }
1631
+ } else {
1632
+ return value[p](a, b);
1633
+ }
1634
+ };
1635
+ }
1754
1636
  }
1755
1637
  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();
1638
+ if (!childNode)
1639
+ childNode = node;
1640
+ beginBatch();
1641
+ if (isPrim === void 0) {
1642
+ isPrim = isPrimitive(newValue);
1643
+ }
1644
+ let hasADiff = isPrim;
1645
+ let whenOptimizedOnlyIf = false;
1646
+ if (!isPrim || prevValue && !isPrimitive(prevValue)) {
1647
+ if ((process.env.NODE_ENV === "development" || process.env.NODE_ENV === "test") && typeof __devUpdateNodes !== "undefined") {
1648
+ __devUpdateNodes.clear();
1649
+ }
1650
+ hasADiff = updateNodes(childNode, newValue, prevValue);
1651
+ if (isArray(newValue)) {
1652
+ whenOptimizedOnlyIf = (newValue == null ? void 0 : newValue.length) !== (prevValue == null ? void 0 : prevValue.length);
1653
+ }
1654
+ }
1655
+ if (isPrim || !newValue || isEmpty(newValue) && !isEmpty(prevValue) ? newValue !== prevValue : hasADiff) {
1656
+ notify(
1657
+ isPrim && isRoot ? node : childNode,
1658
+ newValue,
1659
+ prevValue,
1660
+ (level != null ? level : prevValue === void 0) ? -1 : hasADiff ? 0 : 1,
1661
+ whenOptimizedOnlyIf
1662
+ );
1663
+ }
1664
+ endBatch();
1781
1665
  }
1782
1666
  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);
1667
+ if (!node.state) {
1668
+ node.state = createObservable(
1669
+ {
1670
+ isLoaded: false
1671
+ },
1672
+ false,
1673
+ extractPromise,
1674
+ getProxy
1675
+ );
1676
+ }
1677
+ value.then((value2) => {
1678
+ setter ? setter({ value: value2 }) : set(node, value2);
1679
+ node.state.assign({
1680
+ isLoaded: true,
1681
+ error: void 0
1798
1682
  });
1683
+ }).catch((error) => {
1684
+ node.state.error.set(error);
1685
+ });
1799
1686
  }
1800
1687
  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
- }
1688
+ if (isPromise(v)) {
1689
+ const childNode = getChildNode(node, k);
1690
+ extractPromise(childNode, v);
1691
+ setNodeValue(childNode, void 0);
1692
+ return void 0;
1693
+ } else if (isObservable(v)) {
1694
+ const fn = () => v;
1695
+ extractFunction(node, k, fn);
1696
+ const childNode = getChildNode(node, k, fn);
1697
+ const targetNode = getNode(v);
1698
+ const initialValue = peek(targetNode);
1699
+ setNodeValue(childNode, initialValue);
1700
+ return getNodeValue(childNode);
1701
+ } else if (typeof v === "function") {
1702
+ extractFunction(node, k, v);
1703
+ return k;
1704
+ }
1823
1705
  }
1824
1706
  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);
1707
+ const track = options ? isObject(options) ? options.shallow : options : void 0;
1708
+ updateTracking(node, track);
1709
+ return peek(node);
1829
1710
  }
1830
1711
  function peek(node) {
1831
- return peekInternal(node, true);
1712
+ return peekInternal(node, true);
1832
1713
  }
1833
- let isFlushing = false;
1714
+ var isFlushing = false;
1834
1715
  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;
1716
+ var _a;
1717
+ isFlushing = true;
1718
+ if (activateRecursive && ((_a = node.dirtyChildren) == null ? void 0 : _a.size)) {
1719
+ const dirty = Array.from(node.dirtyChildren);
1720
+ node.dirtyChildren.clear();
1721
+ dirty.forEach((node2) => node2.dirtyFn && peekInternal(node2));
1722
+ }
1723
+ if (node.dirtyFn) {
1724
+ const dirtyFn = node.dirtyFn;
1725
+ node.dirtyFn = void 0;
1726
+ globalState.dirtyNodes.delete(node);
1727
+ dirtyFn();
1728
+ }
1729
+ isFlushing = false;
1730
+ let value = getNodeValue(node);
1731
+ value = checkLazy(node, value, !!activateRecursive);
1732
+ return value;
1853
1733
  }
1854
1734
  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
1735
+ const origValue = value;
1736
+ const lazy = node.lazy;
1737
+ if (lazy) {
1738
+ const lazyFn = node.lazyFn;
1739
+ delete node.lazy;
1740
+ if (isFunction(lazyFn)) {
1741
+ if (lazyFn.length === 1) {
1742
+ value = {};
1743
+ } else {
1889
1744
  if (node.parent) {
1890
- extractFunctionOrComputed(node.parent, node.key, origValue);
1891
- }
1745
+ const parentValue = getNodeValue(node.parent);
1746
+ if (parentValue) {
1747
+ delete parentValue[node.key];
1748
+ } else {
1749
+ node.root._ = void 0;
1750
+ }
1751
+ }
1752
+ value = activateNodeFunction(node, lazyFn);
1753
+ }
1754
+ } else if (isObservable(value)) {
1755
+ value = extractFunctionOrComputed(node.parent, node.key, value);
1756
+ }
1757
+ }
1758
+ if ((lazy || node.needsExtract) && !isObservable(value) && !isPrimitive(value)) {
1759
+ if (activateRecursive) {
1760
+ recursivelyAutoActivate(value, node);
1892
1761
  }
1893
- return value;
1762
+ if (node.parent) {
1763
+ extractFunctionOrComputed(node.parent, node.key, origValue);
1764
+ }
1765
+ }
1766
+ return value;
1894
1767
  }
1895
1768
  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
- }
1769
+ if (value) {
1770
+ const property = Object.getOwnPropertyDescriptor(value, key);
1771
+ if (property == null ? void 0 : property.get) {
1772
+ delete value[key];
1773
+ value[key] = property.set ? linked({
1774
+ get: property.get,
1775
+ set: ({ value: value2 }) => property.set(value2)
1776
+ }) : property.get;
1777
+ }
1778
+ return value[key];
1779
+ }
1909
1780
  }
1910
1781
  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;
1782
+ var _a, _b;
1783
+ (_a = node.activatedObserveDispose) == null ? void 0 : _a.call(node);
1784
+ (_b = node.linkedToNodeDispose) == null ? void 0 : _b.call(node);
1785
+ node.activatedObserveDispose = node.linkedToNodeDispose = node.linkedToNode = void 0;
1786
+ node.lazyFn = lazyFn;
1787
+ node.lazy = true;
1917
1788
  }
1918
1789
  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;
1790
+ var _a, _b;
1791
+ let parent = node;
1792
+ let hasListeners = node.numListenersRecursive > 0;
1793
+ while (parent && !hasListeners) {
1794
+ if (!!((_a = parent.listeners) == null ? void 0 : _a.size) || !!((_b = parent.listenersImmediate) == null ? void 0 : _b.size)) {
1795
+ hasListeners = true;
1927
1796
  }
1928
- return hasListeners;
1797
+ parent = parent.parent;
1798
+ }
1799
+ return hasListeners;
1929
1800
  }
1930
1801
  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;
1802
+ if (!isFlushing) {
1803
+ const hasListeners = isObserved(node);
1804
+ if (!hasListeners) {
1805
+ if (refreshFn) {
1806
+ node.dirtyFn = refreshFn;
1807
+ }
1808
+ let parent = node;
1809
+ while (parent) {
1810
+ if (!parent.dirtyChildren) {
1811
+ parent.dirtyChildren = /* @__PURE__ */ new Set();
1946
1812
  }
1813
+ parent.dirtyChildren.add(node);
1814
+ parent = parent.parent;
1815
+ }
1816
+ return true;
1947
1817
  }
1818
+ }
1948
1819
  }
1949
1820
  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;
1821
+ let update;
1822
+ let wasPromise;
1823
+ let ignoreThisUpdate;
1824
+ let isFirst = true;
1825
+ const activateFn = lazyFn;
1826
+ let activatedValue;
1827
+ let disposes = [];
1828
+ let refreshFn;
1829
+ function markDirty() {
1830
+ node.dirtyFn = refreshFn;
1831
+ globalState.dirtyNodes.add(node);
1832
+ }
1833
+ node.activatedObserveDispose = observe(
1834
+ () => {
1835
+ var _a, _b, _c, _d;
1836
+ if (isFirst) {
1837
+ isFirst = false;
1838
+ setNodeValue(node, void 0);
1839
+ } else if (!isFlushing && refreshFn) {
1840
+ if (shouldIgnoreUnobserved(node, refreshFn)) {
1841
+ ignoreThisUpdate = true;
1842
+ return;
1843
+ }
1844
+ }
1845
+ let value = activateFn();
1846
+ let didSetToObs = false;
1847
+ if (isObservable(value)) {
1848
+ didSetToObs = true;
1849
+ value = setToObservable(node, value);
1850
+ }
1851
+ if (isFunction(value)) {
1852
+ value = value();
1853
+ }
1854
+ const activated = !isObservable(value) ? value == null ? void 0 : value[symbolLinked] : void 0;
1855
+ if (activated) {
1856
+ node.activationState = activated;
1857
+ value = void 0;
1858
+ }
1859
+ ignoreThisUpdate = false;
1860
+ wasPromise = isPromise(value);
1861
+ if (!node.activated) {
1862
+ node.activated = true;
1863
+ let activateNodeFn = activateNodeBase;
1864
+ if (activated == null ? void 0 : activated.synced) {
1865
+ activateNodeFn = globalState.activateSyncedNode;
1866
+ ignoreThisUpdate = true;
1867
+ }
1868
+ const result = activateNodeFn(node, value);
1869
+ update = result.update;
1870
+ let newValue = result.value;
1871
+ if (!didSetToObs && isObservable(newValue)) {
1872
+ newValue = setToObservable(node, newValue);
1873
+ }
1874
+ value = newValue != null ? newValue : activated == null ? void 0 : activated.initial;
1875
+ } else if (node.activationState) {
1876
+ const activated2 = node.activationState;
1877
+ if ((_b = (_a = node.state) == null ? void 0 : _a.peek()) == null ? void 0 : _b.sync) {
1878
+ node.state.sync();
1879
+ ignoreThisUpdate = true;
1880
+ } else {
1881
+ value = (_d = (_c = activated2.get) == null ? void 0 : _c.call(activated2)) != null ? _d : activated2.initial;
1882
+ }
1883
+ }
1884
+ wasPromise = wasPromise || isPromise(value);
1885
+ return value;
1886
+ },
1887
+ (e) => {
1888
+ const { value, nodes, refresh } = e;
1889
+ refreshFn = refresh;
1890
+ if (!ignoreThisUpdate) {
1891
+ if (!wasPromise || !globalState.isLoadingRemote) {
1892
+ if (wasPromise) {
1893
+ if (node.activationState) {
1894
+ const { initial } = node.activationState;
1895
+ if (value && isPromise(value)) {
1896
+ extractPromise(node, value, update);
1897
+ }
1898
+ if (isFunction(getNodeValue(node))) {
1899
+ setNodeValue(node, initial != null ? initial : void 0);
1900
+ }
1901
+ } else if (node.activated) {
1902
+ extractPromise(node, value, update);
1903
+ if (isFunction(getNodeValue(node))) {
1904
+ setNodeValue(node, void 0);
1905
+ }
2021
1906
  }
2022
- else {
2023
- value = (_d = (_c = activated.get) === null || _c === void 0 ? void 0 : _c.call(activated)) !== null && _d !== void 0 ? _d : activated.initial;
1907
+ } else {
1908
+ activatedValue = value;
1909
+ if (node.state.isLoaded.peek()) {
1910
+ node.isComputing = true;
1911
+ set(node, value);
1912
+ node.isComputing = false;
1913
+ } else {
1914
+ setNodeValue(node, value);
1915
+ node.state.assign({
1916
+ isLoaded: true,
1917
+ error: void 0
1918
+ });
2024
1919
  }
1920
+ }
2025
1921
  }
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;
1922
+ disposes.forEach((fn) => fn());
1923
+ disposes = [];
1924
+ nodes == null ? void 0 : nodes.forEach(({ node: node2, track }) => {
1925
+ disposes.push(onChange(node2, markDirty, { immediate: true, trackingType: track }));
1926
+ });
1927
+ }
1928
+ e.cancel = true;
1929
+ },
1930
+ { fromComputed: true }
1931
+ );
1932
+ return activatedValue;
2084
1933
  }
2085
1934
  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) {
1935
+ if (!node.state) {
1936
+ node.state = createObservable(
1937
+ {
1938
+ isLoaded: false
1939
+ },
1940
+ false,
1941
+ extractPromise,
1942
+ getProxy
1943
+ );
1944
+ }
1945
+ if (node.activationState) {
1946
+ const { set: setFn, get: getFn, initial } = node.activationState;
1947
+ value = getFn == null ? void 0 : getFn();
1948
+ if (value == void 0 || value === null) {
1949
+ value = initial;
1950
+ }
1951
+ if (setFn) {
1952
+ let allChanges = [];
1953
+ let latestValue = void 0;
1954
+ let runNumber = 0;
1955
+ const runChanges = (listenerParams) => {
1956
+ if (allChanges.length > 0) {
1957
+ let changes;
1958
+ let value2;
1959
+ let loading = false;
1960
+ let remote = false;
1961
+ let getPrevious;
1962
+ if (listenerParams) {
1963
+ changes = listenerParams.changes;
1964
+ value2 = listenerParams.value;
1965
+ loading = listenerParams.loading;
1966
+ remote = listenerParams.remote;
1967
+ getPrevious = listenerParams.getPrevious;
1968
+ } else {
1969
+ changes = allChanges;
1970
+ value2 = latestValue;
1971
+ getPrevious = createPreviousHandler(value2, changes);
1972
+ }
1973
+ allChanges = [];
1974
+ latestValue = void 0;
1975
+ globalState.pendingNodes.delete(node);
1976
+ runNumber++;
1977
+ const thisRunNumber = runNumber;
1978
+ const run = () => {
1979
+ if (thisRunNumber !== runNumber) {
1980
+ return;
1981
+ }
2168
1982
  node.isComputing = true;
2169
- set(node, value);
1983
+ setFn({
1984
+ value: value2,
1985
+ changes,
1986
+ loading,
1987
+ remote,
1988
+ getPrevious
1989
+ });
2170
1990
  node.isComputing = false;
1991
+ };
1992
+ whenReady(node.state.isLoaded, run);
2171
1993
  }
2172
- };
2173
- return { update, value };
1994
+ };
1995
+ const onChangeImmediate = ({ value: value2, changes }) => {
1996
+ if (!node.isComputing) {
1997
+ if (changes.length > 1 || !isFunction(changes[0].prevAtPath)) {
1998
+ latestValue = value2;
1999
+ if (allChanges.length > 0) {
2000
+ changes = changes.filter((change) => !isArraySubset(allChanges[0].path, change.path));
2001
+ }
2002
+ allChanges.push(...changes);
2003
+ globalState.pendingNodes.set(node, runChanges);
2004
+ }
2005
+ }
2006
+ };
2007
+ onChange(node, onChangeImmediate, { immediate: true });
2008
+ onChange(node, runChanges);
2009
+ }
2010
+ }
2011
+ const update = ({ value: value2 }) => {
2012
+ if (!node.isComputing) {
2013
+ node.isComputing = true;
2014
+ set(node, value2);
2015
+ node.isComputing = false;
2016
+ }
2017
+ };
2018
+ return { update, value };
2174
2019
  }
2175
2020
  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;
2021
+ var _a;
2022
+ const linkedNode = getNode(value);
2023
+ if (linkedNode !== node && (linkedNode == null ? void 0 : linkedNode.linkedToNode) !== node) {
2024
+ node.linkedToNode = linkedNode;
2025
+ linkedNode.linkedFromNodes || (linkedNode.linkedFromNodes = /* @__PURE__ */ new Set());
2026
+ linkedNode.linkedFromNodes.add(node);
2027
+ (_a = node.linkedToNodeDispose) == null ? void 0 : _a.call(node);
2028
+ node.linkedToNodeDispose = onChange(
2029
+ linkedNode,
2030
+ () => {
2031
+ value = peekInternal(linkedNode);
2032
+ set(node, value);
2033
+ },
2034
+ { initial: true },
2035
+ /* @__PURE__ */ new Set([node])
2036
+ );
2037
+ }
2038
+ return value;
2191
2039
  }
2192
2040
  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
- }
2041
+ if (isObject(obj) || isArray(obj)) {
2042
+ const pathStack = [];
2043
+ const getNodeAtPath2 = () => {
2044
+ var _a;
2045
+ let childNode = node;
2046
+ for (let i = 0; i < pathStack.length; i++) {
2047
+ const { key } = pathStack[i];
2048
+ const value = (_a = getNodeValue(childNode)) == null ? void 0 : _a[key];
2049
+ childNode = getChildNode(childNode, key, isFunction(value) ? value : void 0);
2050
+ peekInternal(childNode);
2051
+ }
2052
+ return childNode;
2053
+ };
2054
+ recursivelyAutoActivateInner(obj, pathStack, getNodeAtPath2);
2055
+ }
2056
+ }
2057
+ function recursivelyAutoActivateInner(obj, pathStack, getNodeAtPath2) {
2058
+ var _a;
2059
+ for (const key in obj) {
2060
+ if (hasOwnProperty.call(obj, key)) {
2061
+ const value = obj[key];
2062
+ if (isObservable(value)) {
2063
+ const childNode = getNodeAtPath2();
2064
+ extractFunctionOrComputed(childNode, key, value);
2065
+ delete childNode.lazy;
2066
+ } else {
2067
+ const linkedOptions = isFunction(value) && ((_a = value.prototype) == null ? void 0 : _a[symbolLinked]);
2068
+ if (linkedOptions) {
2069
+ const activate = linkedOptions.activate;
2070
+ if (!activate || activate === "auto") {
2071
+ const childNode = getNodeAtPath2();
2072
+ peek(getChildNode(childNode, key, value));
2073
+ }
2074
+ }
2075
+ }
2076
+ if (typeof value === "object") {
2077
+ pathStack.push({ key, value });
2078
+ recursivelyAutoActivateInner(value, pathStack, getNodeAtPath2);
2079
+ pathStack.pop();
2080
+ }
2081
+ }
2082
+ }
2236
2083
  }
2237
2084
 
2238
- const fns = ['get', 'set', 'peek', 'onChange', 'toggle'];
2085
+ // src/ObservablePrimitive.ts
2086
+ var fns = ["get", "set", "peek", "onChange", "toggle"];
2239
2087
  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
- }
2088
+ this._node = node;
2089
+ for (let i = 0; i < fns.length; i++) {
2090
+ const key = fns[i];
2091
+ this[key] = this[key].bind(this);
2092
+ }
2246
2093
  }
2247
- // Add observable functions to prototype
2248
2094
  function proto(key, fn) {
2249
- ObservablePrimitiveClass.prototype[key] = function (...args) {
2250
- return fn.call(this, this._node, ...args);
2251
- };
2095
+ ObservablePrimitiveClass.prototype[key] = function(...args) {
2096
+ return fn.call(this, this._node, ...args);
2097
+ };
2252
2098
  }
2253
- proto('peek', (node) => {
2254
- flushPending();
2255
- return peek(node);
2099
+ proto("peek", (node) => {
2100
+ flushPending();
2101
+ return peek(node);
2256
2102
  });
2257
- proto('get', (node, options) => {
2258
- flushPending();
2259
- return get(node, options);
2103
+ proto("get", (node, options) => {
2104
+ flushPending();
2105
+ return get(node, options);
2260
2106
  });
2261
- proto('set', set);
2262
- proto('onChange', onChange);
2263
- // Getters
2107
+ proto("set", set);
2108
+ proto("onChange", onChange);
2264
2109
  Object.defineProperty(ObservablePrimitiveClass.prototype, symbolGetNode, {
2265
- configurable: true,
2266
- get() {
2267
- return this._node;
2268
- },
2110
+ configurable: true,
2111
+ get() {
2112
+ return this._node;
2113
+ }
2269
2114
  });
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
- }
2115
+ ObservablePrimitiveClass.prototype.toggle = function() {
2116
+ const value = this.peek();
2117
+ if (value === void 0 || value === null || isBoolean(value)) {
2118
+ this.set(!value);
2119
+ } else if (process.env.NODE_ENV === "development" || process.env.NODE_ENV === "test") {
2120
+ throw new Error("[legend-state] Cannot toggle a non-boolean value");
2121
+ }
2278
2122
  };
2279
- ObservablePrimitiveClass.prototype.delete = function () {
2280
- this.set(undefined);
2281
- return this;
2123
+ ObservablePrimitiveClass.prototype.delete = function() {
2124
+ this.set(void 0);
2125
+ return this;
2282
2126
  };
2283
2127
 
2128
+ // src/observable.ts
2284
2129
  function observable(value) {
2285
- return createObservable(value, false, extractPromise, getProxy, ObservablePrimitiveClass);
2130
+ return createObservable(value, false, extractPromise, getProxy, ObservablePrimitiveClass);
2286
2131
  }
2287
2132
  function observablePrimitive(value) {
2288
- return createObservable(value, true, extractPromise, getProxy, ObservablePrimitiveClass);
2133
+ return createObservable(value, true, extractPromise, getProxy, ObservablePrimitiveClass);
2289
2134
  }
2290
2135
  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;
2136
+ const node = getNode(obs);
2137
+ if (!node.state) {
2138
+ peekInternal(node);
2139
+ }
2140
+ if (!node.state) {
2141
+ node.state = observable({});
2142
+ }
2143
+ return node.state;
2299
2144
  }
2300
2145
 
2301
- function computed(get, set) {
2302
- return observable(set ? linked({ get: get, set: ({ value }) => set(value) }) : get);
2146
+ // src/computed.ts
2147
+ function computed(get2, set2) {
2148
+ return observable(
2149
+ set2 ? linked({ get: get2, set: ({ value }) => set2(value) }) : get2
2150
+ );
2303
2151
  }
2304
2152
 
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
- });
2153
+ // src/config.ts
2154
+ function configureLegendState({
2155
+ observableFunctions,
2156
+ observableProperties: observableProperties2,
2157
+ jsonReplacer,
2158
+ jsonReviver
2159
+ }) {
2160
+ if (observableFunctions) {
2161
+ for (const key in observableFunctions) {
2162
+ const fn = observableFunctions[key];
2163
+ observableFns.set(key, fn);
2164
+ ObservablePrimitiveClass.prototype[key] = function(...args) {
2165
+ return fn.call(this, this._node, ...args);
2166
+ };
2167
+ }
2168
+ }
2169
+ if (observableProperties2) {
2170
+ for (const key in observableProperties2) {
2171
+ const fns2 = observableProperties2[key];
2172
+ observableProperties.set(key, fns2);
2173
+ Object.defineProperty(ObservablePrimitiveClass.prototype, key, {
2174
+ configurable: true,
2175
+ get() {
2176
+ return fns2.get.call(this, this._node);
2177
+ },
2178
+ set(value) {
2179
+ return fns2.set.call(this, this._node, value);
2328
2180
  }
2181
+ });
2329
2182
  }
2330
- if (jsonReplacer) {
2331
- globalState.replacer = jsonReplacer;
2332
- }
2333
- if (jsonReviver) {
2334
- globalState.reviver = jsonReviver;
2335
- }
2183
+ }
2184
+ if (jsonReplacer) {
2185
+ globalState.replacer = jsonReplacer;
2186
+ }
2187
+ if (jsonReviver) {
2188
+ globalState.reviver = jsonReviver;
2189
+ }
2336
2190
  }
2337
2191
 
2192
+ // src/event.ts
2338
2193
  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
- };
2194
+ const obs = observable(0);
2195
+ const node = getNode(obs);
2196
+ node.isEvent = true;
2197
+ return {
2198
+ fire: function() {
2199
+ obs.set((v) => v + 1);
2200
+ },
2201
+ on: function(cb) {
2202
+ return obs.onChange(cb);
2203
+ },
2204
+ get: function() {
2205
+ return obs.get();
2206
+ },
2207
+ // @ts-expect-error eslint doesn't like adding symbols to the object but this does work
2208
+ [symbolGetNode]: node
2209
+ };
2359
2210
  }
2360
2211
 
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));
2212
+ // src/proxy.ts
2213
+ function proxy(get2, set2) {
2214
+ return observable(
2215
+ (key) => set2 ? linked({
2216
+ get: () => get2(key),
2217
+ set: ({ value }) => set2(key, value)
2218
+ }) : get2(key)
2219
+ );
2368
2220
  }
2369
2221
 
2222
+ // src/retry.ts
2370
2223
  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;
2224
+ const { backoff, delay = 1e3, infinite, times = 3, maxDelay = 3e4 } = retryOptions;
2225
+ if (infinite || attemptNum < times) {
2226
+ const delayTime = Math.min(delay * (backoff === "constant" ? 1 : 2 ** attemptNum), maxDelay);
2227
+ return delayTime;
2228
+ }
2229
+ return null;
2377
2230
  }
2378
2231
  function createRetryTimeout(retryOptions, attemptNum, fn) {
2379
- const delayTime = calculateRetryDelay(retryOptions, attemptNum);
2380
- if (delayTime) {
2381
- return setTimeout(fn, delayTime);
2382
- }
2232
+ const delayTime = calculateRetryDelay(retryOptions, attemptNum);
2233
+ if (delayTime) {
2234
+ return setTimeout(fn, delayTime);
2235
+ }
2383
2236
  }
2384
2237
  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();
2238
+ const { waitFor } = node.activationState;
2239
+ const { retry } = state;
2240
+ const e = { cancel: false };
2241
+ let value = void 0;
2242
+ if (waitFor) {
2243
+ value = whenReady(waitFor, () => {
2244
+ node.activationState.waitFor = void 0;
2245
+ return fn(e);
2246
+ });
2247
+ } else {
2248
+ value = fn(e);
2249
+ }
2250
+ if (isPromise(value) && retry) {
2251
+ let timeoutRetry;
2252
+ return new Promise((resolve) => {
2253
+ const run = () => {
2254
+ value.then((val) => {
2255
+ node.activationState.persistedRetry = false;
2256
+ resolve(val);
2257
+ }).catch(() => {
2258
+ state.attemptNum++;
2259
+ if (timeoutRetry) {
2260
+ clearTimeout(timeoutRetry);
2261
+ }
2262
+ if (!e.cancel) {
2263
+ timeoutRetry = createRetryTimeout(retry, state.attemptNum, () => {
2264
+ value = fn(e);
2265
+ run();
2266
+ });
2267
+ }
2268
+ }).finally(() => {
2269
+ node.activationState.persistedRetry = false;
2424
2270
  });
2425
- }
2426
- return value;
2271
+ };
2272
+ run();
2273
+ });
2274
+ }
2275
+ return value;
2427
2276
  }
2428
2277
 
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,
2278
+ // index.ts
2279
+ var internal = {
2280
+ createPreviousHandler,
2281
+ clone,
2282
+ ensureNodeValue,
2283
+ findIDKey,
2284
+ get,
2285
+ getNode,
2286
+ getNodeValue,
2287
+ getPathType,
2288
+ getProxy,
2289
+ getValueAtPath,
2290
+ globalState,
2291
+ initializePathType,
2292
+ observableFns,
2293
+ optimized,
2294
+ peek,
2295
+ runWithRetry,
2296
+ safeParse,
2297
+ safeStringify,
2298
+ set,
2299
+ setAtPath,
2300
+ setNodeValue,
2301
+ symbolLinked,
2302
+ symbolDelete,
2303
+ tracking
2454
2304
  };
2455
2305
 
2456
2306
  exports.ObservablePrimitiveClass = ObservablePrimitiveClass;
@@ -2509,4 +2359,3 @@ exports.tracking = tracking;
2509
2359
  exports.updateTracking = updateTracking;
2510
2360
  exports.when = when;
2511
2361
  exports.whenReady = whenReady;
2512
- //# sourceMappingURL=index.js.map