tsdf 8.0.0-beta.1 → 8.0.0-beta.11

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 (57) hide show
  1. package/dist/main.cjs +1860 -0
  2. package/dist/main.d.ts +291 -0
  3. package/dist/main.js +1825 -0
  4. package/package.json +6 -2
  5. package/.eslintignore +0 -3
  6. package/.eslintrc.cjs +0 -119
  7. package/.gitattributes +0 -22
  8. package/.prettierrc +0 -6
  9. package/.vscode/settings.json +0 -3
  10. package/.vscode/tasks.json +0 -35
  11. package/fetch-orquestrator-scenarios.excalidraw +0 -10115
  12. package/scripts/check-if-is-sync.sh +0 -6
  13. package/src/collectionFetchOrquestrator.ts +0 -23
  14. package/src/collectionStore.ts +0 -608
  15. package/src/documentStore.ts +0 -272
  16. package/src/fetchOrquestrator.ts +0 -335
  17. package/src/listQueryStore.ts +0 -1190
  18. package/src/main.ts +0 -22
  19. package/src/storeShared.ts +0 -5
  20. package/src/useEnsureIsLoaded.ts +0 -50
  21. package/src/utils/filterAndMap.ts +0 -20
  22. package/src/utils/getCacheId.ts +0 -19
  23. package/src/utils/hooks.ts +0 -110
  24. package/src/utils/isObject.ts +0 -3
  25. package/src/utils/math.ts +0 -7
  26. package/src/utils/serializableClone.ts +0 -3
  27. package/src/utils/useLatestValue.ts +0 -16
  28. package/test/__snapshots__/listQueryStore.test.ts.snap +0 -146
  29. package/test/__snapshots__/listQueryStoreHooks.test.ts.snap +0 -9
  30. package/test/collectionStore.test.ts +0 -523
  31. package/test/collectionStoreHooks.test.tsx +0 -651
  32. package/test/documentStore.test.ts +0 -183
  33. package/test/documentStoreHooks.test.tsx +0 -857
  34. package/test/fetchOrquestrator.test.ts +0 -913
  35. package/test/listQueryStore.test.ts +0 -1158
  36. package/test/listQueryStoreHooks.test.tsx +0 -662
  37. package/test/listQueryStoreHooks2.test.tsx +0 -483
  38. package/test/listQueryStoreHooksMutations.test.tsx +0 -764
  39. package/test/mocks/fetchMock.ts +0 -296
  40. package/test/mocks/fetchOrquestratorEnv.ts +0 -370
  41. package/test/setup/setup.ts +0 -109
  42. package/test/testHelpers.test.ts +0 -88
  43. package/test/utils/RenderObjValues.tsx +0 -23
  44. package/test/utils/arrayUtils.ts +0 -13
  45. package/test/utils/createDefaultListQueryStore.ts +0 -275
  46. package/test/utils/createOrVariations.ts +0 -48
  47. package/test/utils/dedent.ts +0 -50
  48. package/test/utils/delayCall.ts +0 -25
  49. package/test/utils/math.ts +0 -3
  50. package/test/utils/objectUtils.ts +0 -18
  51. package/test/utils/range.ts +0 -19
  52. package/test/utils/sleep.ts +0 -3
  53. package/test/utils/storeUtils.ts +0 -460
  54. package/tsconfig.json +0 -24
  55. package/tsconfig.prod.json +0 -9
  56. package/tsup.config.ts +0 -12
  57. package/vitest.config.ts +0 -10
package/dist/main.js ADDED
@@ -0,0 +1,1825 @@
1
+ // src/documentStore.ts
2
+ import { produce } from "immer";
3
+ import mitt2 from "mitt";
4
+ import { useCallback, useEffect as useEffect2 } from "react";
5
+ import { Store, useSubscribeToStore } from "t-state";
6
+
7
+ // src/fetchOrquestrator.ts
8
+ function createFetchOrquestrator({
9
+ fetchFn,
10
+ on,
11
+ mediumPriorityThrottleMs = 10,
12
+ lowPriorityThrottleMs = 200,
13
+ dynamicRealtimeThrottleMs
14
+ }) {
15
+ const fetchs = {
16
+ a: null,
17
+ c: null,
18
+ b: null
19
+ };
20
+ let lastMutationIdStarted = 0;
21
+ let lastFetchIdStarted = 0;
22
+ let mutationIsInProgress = false;
23
+ let lastFetchStartTime = 0;
24
+ let lastFetchDuration = 0;
25
+ let onMutationEnd = [];
26
+ let lastFetchWasAborted = false;
27
+ let abortFetchsBeforeOrEqual = 0;
28
+ function setLastFetchDurantion(duration) {
29
+ lastFetchDuration = duration;
30
+ }
31
+ function setLastFetchStartTime(startTime) {
32
+ lastFetchStartTime = startTime;
33
+ }
34
+ function flushScheduledFetch() {
35
+ if (fetchs.c) {
36
+ on?.("scheduled-fetch-started");
37
+ const params = fetchs.c.params;
38
+ fetchs.c = null;
39
+ startFetch(params, Date.now());
40
+ }
41
+ }
42
+ function startMutation() {
43
+ mutationIsInProgress = true;
44
+ abortFetchsBeforeOrEqual = lastFetchIdStarted;
45
+ fetchs.a = null;
46
+ const id = getAutoIncrementId();
47
+ lastMutationIdStarted = id;
48
+ return () => endMutation(id);
49
+ }
50
+ function endMutation(id) {
51
+ if (id === lastMutationIdStarted) {
52
+ mutationIsInProgress = false;
53
+ if (onMutationEnd.length > 0) {
54
+ onMutationEnd.forEach((cb) => cb());
55
+ onMutationEnd = [];
56
+ }
57
+ flushScheduledFetch();
58
+ return true;
59
+ }
60
+ return false;
61
+ }
62
+ function getFetchs() {
63
+ return fetchs;
64
+ }
65
+ async function startFetch(params, startTime) {
66
+ if (fetchs.a) {
67
+ throw new Error("[tsdf] Fetch already in progress");
68
+ }
69
+ const id = getAutoIncrementId();
70
+ lastFetchIdStarted = id;
71
+ lastFetchWasAborted = false;
72
+ fetchs.a = { startTime, onEnd: [] };
73
+ const prevFetchStartTime = lastFetchStartTime;
74
+ lastFetchStartTime = startTime;
75
+ function shouldAbort() {
76
+ const abort = id !== lastFetchIdStarted || mutationIsInProgress || id <= abortFetchsBeforeOrEqual;
77
+ lastFetchWasAborted = abort;
78
+ return abort;
79
+ }
80
+ const success = await fetchFn(
81
+ {
82
+ shouldAbort,
83
+ getStartTime: () => startTime
84
+ },
85
+ params
86
+ );
87
+ const currentFetchs = getFetchs();
88
+ if (!currentFetchs.a) {
89
+ lastFetchStartTime = prevFetchStartTime;
90
+ return false;
91
+ }
92
+ if (success) {
93
+ lastFetchDuration = Date.now() - startTime;
94
+ }
95
+ if (currentFetchs.b) {
96
+ clearTimeout(currentFetchs.b.timeoutId);
97
+ fetchs.b = null;
98
+ }
99
+ const onEnd = currentFetchs.a.onEnd;
100
+ currentFetchs.a = null;
101
+ if (onEnd.length > 0) {
102
+ onEnd.forEach((cb) => cb());
103
+ }
104
+ flushScheduledFetch();
105
+ return true;
106
+ }
107
+ function scheduleFetch(fetchType, params) {
108
+ const startTime = Date.now();
109
+ if (dynamicRealtimeThrottleMs && fetchType === "realtimeUpdate") {
110
+ if (scheduleRTU(startTime, params)) {
111
+ return "rt-scheduled";
112
+ }
113
+ }
114
+ if (shouldSkipFetch(fetchType, startTime)) {
115
+ return "skipped";
116
+ }
117
+ if (shouldScheduleFetch(fetchType, params)) {
118
+ return "scheduled";
119
+ }
120
+ startFetch(params, startTime);
121
+ return "started";
122
+ }
123
+ function shouldSkipFetch(fetchType, startTime) {
124
+ if (fetchType === "highPriority") {
125
+ if (fetchs.a) {
126
+ const timeSinceLastFetch = startTime - fetchs.a.startTime;
127
+ if (timeSinceLastFetch < mediumPriorityThrottleMs) {
128
+ return true;
129
+ }
130
+ }
131
+ }
132
+ if (fetchType === "lowPriority") {
133
+ if (fetchs.a || fetchs.c || mutationIsInProgress) {
134
+ return true;
135
+ }
136
+ if (lastFetchStartTime) {
137
+ const timeSinceLastFetch = startTime - lastFetchStartTime;
138
+ if (timeSinceLastFetch < lowPriorityThrottleMs) {
139
+ return true;
140
+ }
141
+ }
142
+ }
143
+ return false;
144
+ }
145
+ function shouldScheduleFetch(priority, params) {
146
+ const shouldSchedule = (() => {
147
+ if (priority === "lowPriority") {
148
+ return false;
149
+ }
150
+ return !!fetchs.a || !!mutationIsInProgress;
151
+ })();
152
+ if (shouldSchedule) {
153
+ fetchs.c = { params };
154
+ }
155
+ return shouldSchedule;
156
+ }
157
+ function addDelayedRTU(startTime, params) {
158
+ if (!dynamicRealtimeThrottleMs)
159
+ return false;
160
+ const timeSinceLastFetch = startTime - (lastFetchStartTime + lastFetchDuration);
161
+ const minimumRealtimeInterval = dynamicRealtimeThrottleMs(lastFetchDuration);
162
+ if (timeSinceLastFetch >= minimumRealtimeInterval)
163
+ return false;
164
+ const delay = minimumRealtimeInterval - timeSinceLastFetch;
165
+ fetchs.b = {
166
+ timeoutId: window.setTimeout(() => {
167
+ fetchs.b = null;
168
+ on?.("scheduled-rt-fetch-started");
169
+ startFetch(params, Date.now());
170
+ }, delay)
171
+ };
172
+ return true;
173
+ }
174
+ function scheduleRTU(startTime, params) {
175
+ if (!lastFetchDuration || !lastFetchStartTime || !dynamicRealtimeThrottleMs) {
176
+ return false;
177
+ }
178
+ if (fetchs.b) {
179
+ return true;
180
+ }
181
+ if (fetchs.a) {
182
+ fetchs.a.onEnd.push(() => {
183
+ addDelayedRTU(Date.now(), params);
184
+ });
185
+ return true;
186
+ } else if (mutationIsInProgress) {
187
+ onMutationEnd.push(() => {
188
+ const added = addDelayedRTU(Date.now(), params);
189
+ if (!added) {
190
+ on?.("scheduled-rt-fetch-started");
191
+ scheduleFetch("highPriority", params);
192
+ }
193
+ });
194
+ return true;
195
+ } else {
196
+ if (!addDelayedRTU(startTime, params)) {
197
+ return false;
198
+ }
199
+ }
200
+ return true;
201
+ }
202
+ function addOnFetchEnd(cb) {
203
+ if (fetchs.a) {
204
+ fetchs.a.onEnd.push(cb);
205
+ }
206
+ }
207
+ async function awaitFetch(params) {
208
+ scheduleFetch("highPriority", params);
209
+ if (fetchs.a) {
210
+ await new Promise((resolve) => {
211
+ addOnFetchEnd(() => resolve(true));
212
+ });
213
+ }
214
+ return lastFetchWasAborted;
215
+ }
216
+ return {
217
+ scheduleFetch,
218
+ awaitFetch,
219
+ startMutation,
220
+ get hasPendingFetch() {
221
+ return !!fetchs.a || !!fetchs.c || !!fetchs.b;
222
+ },
223
+ get fetchIsInProgress() {
224
+ return !!fetchs.a;
225
+ },
226
+ get mutationIsInProgress() {
227
+ return mutationIsInProgress;
228
+ },
229
+ setLastFetchDurantion,
230
+ setLastFetchStartTime
231
+ };
232
+ }
233
+ var autoIncrementId = 0;
234
+ function getAutoIncrementId() {
235
+ return ++autoIncrementId;
236
+ }
237
+
238
+ // src/useEnsureIsLoaded.ts
239
+ import mitt from "mitt";
240
+ import { useMemo as useMemo2, useState } from "react";
241
+
242
+ // src/utils/hooks.ts
243
+ import { useEffect, useLayoutEffect, useMemo, useRef } from "react";
244
+ import { deepEqual, shallowEqual } from "t-state";
245
+ function useDeepCompareMemoize(value, equalityFn = deepEqual) {
246
+ const ref = useRef();
247
+ const signalRef = useRef(0);
248
+ if (!equalityFn(value, ref.current)) {
249
+ ref.current = value;
250
+ signalRef.current += 1;
251
+ }
252
+ return [signalRef.current];
253
+ }
254
+ function useDeepMemo(callback, deeps) {
255
+ return useMemo(callback, useDeepCompareMemoize(deeps));
256
+ }
257
+ function useLatestValue(value) {
258
+ const ref = useRef({ insideEffect: value, insideMemo: value });
259
+ ref.current.insideMemo = value;
260
+ useLayoutEffect(() => {
261
+ ref.current.insideEffect = value;
262
+ });
263
+ return ref.current;
264
+ }
265
+ function useOnMittEvent(mitt5, event, callback) {
266
+ const latestCallback = useLatestValue(callback);
267
+ useLayoutEffect(() => {
268
+ const cb = (payload) => {
269
+ latestCallback.insideEffect(payload);
270
+ };
271
+ mitt5.on(event, cb);
272
+ return () => {
273
+ mitt5.off(event, cb);
274
+ };
275
+ }, [mitt5, event, latestCallback]);
276
+ }
277
+ function usePrevious(value, initial) {
278
+ const ref = useRef(initial);
279
+ useEffect(() => {
280
+ ref.current = value;
281
+ });
282
+ return ref.current;
283
+ }
284
+ function useOnChange(value, callBack, {
285
+ equalityFn: areEqual = shallowEqual,
286
+ callOnMount,
287
+ layoutEffect
288
+ } = {}) {
289
+ const useEffectFn = layoutEffect ? useLayoutEffect : useEffect;
290
+ const prev = usePrevious(value, !callOnMount ? value : void 0);
291
+ useEffectFn(() => {
292
+ if (!areEqual(value, prev)) {
293
+ return callBack({ prev, current: value });
294
+ }
295
+ });
296
+ }
297
+ function useConst(getValue) {
298
+ const store = useRef();
299
+ if (store.current === void 0) {
300
+ store.current = getValue();
301
+ }
302
+ return store.current;
303
+ }
304
+
305
+ // src/useEnsureIsLoaded.ts
306
+ function useEnsureIsLoaded(ensureIsLoaded, enabled, forceFetch) {
307
+ const isLoadedEvtEmitter = useConst(() => mitt());
308
+ const [isForceLoading, setIsForceLoading] = useState(true);
309
+ useOnChange(
310
+ ensureIsLoaded && isForceLoading && enabled,
311
+ ({ current }) => {
312
+ if (current) {
313
+ forceFetch();
314
+ }
315
+ },
316
+ { callOnMount: true }
317
+ );
318
+ useOnMittEvent(isLoadedEvtEmitter, "isLoaded", (isLoaded) => {
319
+ if (ensureIsLoaded && enabled && isLoaded) {
320
+ setIsForceLoading(false);
321
+ }
322
+ });
323
+ function useModifyResult(result) {
324
+ return useMemo2(() => {
325
+ if (ensureIsLoaded) {
326
+ const newStatus = enabled && isForceLoading ? "loading" : result.status;
327
+ return {
328
+ ...result,
329
+ isLoading: newStatus === "loading",
330
+ status: newStatus
331
+ };
332
+ }
333
+ return result;
334
+ }, [ensureIsLoaded, isForceLoading, result]);
335
+ }
336
+ return [useModifyResult, isLoadedEvtEmitter.emit];
337
+ }
338
+
339
+ // src/utils/reuseRefIfEqual.ts
340
+ import { deepEqual as deepEqual2 } from "t-state";
341
+ function reusePrevIfEqual({
342
+ prev,
343
+ current,
344
+ d: equalityFn_ = deepEqual2
345
+ }) {
346
+ if (prev === void 0)
347
+ return current;
348
+ if (equalityFn_(prev, current)) {
349
+ return prev;
350
+ }
351
+ return current;
352
+ }
353
+
354
+ // src/documentStore.ts
355
+ function newTSDFDocumentStore({
356
+ debugName,
357
+ fetchFn,
358
+ initialData,
359
+ disableRefetchOnWindowFocus,
360
+ disableRefetchOnMount: globalDisableRefetchOnMount,
361
+ lowPriorityThrottleMs,
362
+ mediumPriorityThrottleMs,
363
+ dynamicRealtimeThrottleMs,
364
+ disableInitialDataInvalidation,
365
+ errorNormalizer
366
+ }) {
367
+ const store = new Store({
368
+ debugName,
369
+ state: {
370
+ data: initialData ?? null,
371
+ error: null,
372
+ status: initialData ? "success" : "idle",
373
+ refetchOnMount: !!initialData && !disableInitialDataInvalidation ? "lowPriority" : false
374
+ }
375
+ });
376
+ async function fetch(fetchCtx, _) {
377
+ store.setPartialState(
378
+ {
379
+ status: store.state.status === "success" ? "refetching" : "loading",
380
+ error: null,
381
+ refetchOnMount: false
382
+ },
383
+ {
384
+ action: store.state.status === "success" ? "fetch-start-refetching" : "fetch-start-loading"
385
+ }
386
+ );
387
+ try {
388
+ const data = await fetchFn();
389
+ if (fetchCtx.shouldAbort())
390
+ return false;
391
+ store.setPartialState(
392
+ {
393
+ data: reusePrevIfEqual({ prev: store.state.data, current: data }),
394
+ status: "success"
395
+ },
396
+ { action: "fetch-success" }
397
+ );
398
+ return true;
399
+ } catch (exception) {
400
+ if (fetchCtx.shouldAbort())
401
+ return false;
402
+ store.setPartialState(
403
+ {
404
+ error: errorNormalizer(exception),
405
+ status: "error"
406
+ },
407
+ { action: "fetch-error" }
408
+ );
409
+ return false;
410
+ }
411
+ }
412
+ const fetchOrquestrator = createFetchOrquestrator({
413
+ fetchFn: fetch,
414
+ lowPriorityThrottleMs,
415
+ dynamicRealtimeThrottleMs,
416
+ mediumPriorityThrottleMs
417
+ });
418
+ function scheduleFetch(fetchType) {
419
+ return fetchOrquestrator.scheduleFetch(fetchType, null);
420
+ }
421
+ async function awaitFetch() {
422
+ const wasAborted = await fetchOrquestrator.awaitFetch(null);
423
+ if (wasAborted) {
424
+ return { data: null, error: errorNormalizer(new Error("Aborted")) };
425
+ }
426
+ if (!store.state.data) {
427
+ return { data: null, error: errorNormalizer(new Error("No data")) };
428
+ }
429
+ return store.state.error ? { data: null, error: store.state.error } : { data: store.state.data, error: null };
430
+ }
431
+ const storeEvents = mitt2();
432
+ let invalidationWasTriggered = false;
433
+ function invalidateData(priority = "highPriority") {
434
+ store.setKey("refetchOnMount", priority, { action: "invalidate-data" });
435
+ invalidationWasTriggered = false;
436
+ storeEvents.emit("invalidateData", priority);
437
+ }
438
+ function useDocument({
439
+ selector,
440
+ disabled,
441
+ returnRefetchingStatus,
442
+ disableRefetchOnMount = globalDisableRefetchOnMount,
443
+ returnIdleStatus = !!disabled,
444
+ ensureIsLoaded
445
+ } = {}) {
446
+ const storeStateSelector = useCallback(
447
+ (state) => {
448
+ const { error } = state;
449
+ const data = selector ? selector(state.data) : state.data;
450
+ let status = state.status;
451
+ if (!returnIdleStatus && status === "idle") {
452
+ status = "loading";
453
+ }
454
+ if (!returnRefetchingStatus && status === "refetching") {
455
+ status = "success";
456
+ }
457
+ return {
458
+ data,
459
+ error,
460
+ status,
461
+ isLoading: status === "loading"
462
+ };
463
+ },
464
+ [returnRefetchingStatus, returnIdleStatus, selector]
465
+ );
466
+ const storeState = store.useSelector(storeStateSelector, {
467
+ useExternalDeps: true
468
+ });
469
+ useOnMittEvent(storeEvents, "invalidateData", (priority) => {
470
+ if (!invalidationWasTriggered) {
471
+ scheduleFetch(priority);
472
+ invalidationWasTriggered = true;
473
+ }
474
+ });
475
+ useEffect2(() => {
476
+ if (disabled)
477
+ return;
478
+ if (disableRefetchOnMount) {
479
+ const shouldFetch = store.state.refetchOnMount || store.state.status === "idle";
480
+ if (shouldFetch) {
481
+ scheduleFetch(store.state.refetchOnMount || "lowPriority");
482
+ }
483
+ } else {
484
+ scheduleFetch("lowPriority");
485
+ }
486
+ }, [disableRefetchOnMount, disabled]);
487
+ const [useModifyResult, emitIsLoadedEvt] = useEnsureIsLoaded(
488
+ ensureIsLoaded,
489
+ !disabled,
490
+ () => {
491
+ scheduleFetch("highPriority");
492
+ }
493
+ );
494
+ useSubscribeToStore(store, ({ observe }) => {
495
+ observe.ifSelector((state) => state.status).change.then(({ current }) => {
496
+ if (current === "success" || current === "error") {
497
+ emitIsLoadedEvt("isLoaded", true);
498
+ }
499
+ });
500
+ });
501
+ return useModifyResult(storeState);
502
+ }
503
+ function updateState(produceNewData) {
504
+ store.setKey(
505
+ "data",
506
+ (current) => {
507
+ if (!current)
508
+ return current;
509
+ return produce(current, produceNewData);
510
+ },
511
+ { action: "update-state" }
512
+ );
513
+ }
514
+ if (!disableRefetchOnWindowFocus) {
515
+ let handleFocus2 = function() {
516
+ invalidateData("lowPriority");
517
+ };
518
+ var handleFocus = handleFocus2;
519
+ window.addEventListener("focus", handleFocus2);
520
+ window.addEventListener("visibilitychange", handleFocus2);
521
+ }
522
+ return {
523
+ store,
524
+ awaitFetch,
525
+ scheduleFetch,
526
+ invalidateData,
527
+ useDocument,
528
+ updateState,
529
+ startMutation: fetchOrquestrator.startMutation
530
+ };
531
+ }
532
+
533
+ // src/collectionStore.ts
534
+ import mitt3 from "mitt";
535
+ import { useCallback as useCallback2, useEffect as useEffect3, useMemo as useMemo3 } from "react";
536
+ import { deepEqual as deepEqual3, Store as Store2, useSubscribeToStore as useSubscribeToStore2 } from "t-state";
537
+
538
+ // src/collectionFetchOrquestrator.ts
539
+ function createCollectionFetchOrquestrator(props) {
540
+ const fetchOrquestrators = /* @__PURE__ */ new Map();
541
+ function getFetchOrquestrator(key) {
542
+ if (!fetchOrquestrators.has(key)) {
543
+ fetchOrquestrators.set(key, createFetchOrquestrator(props));
544
+ }
545
+ return fetchOrquestrators.get(key);
546
+ }
547
+ return {
548
+ get: getFetchOrquestrator
549
+ };
550
+ }
551
+
552
+ // src/utils/filterAndMap.ts
553
+ var ignore = Symbol();
554
+ function filterAndMap(arr, fn) {
555
+ const result = [];
556
+ let i = 0;
557
+ for (const item of arr) {
558
+ const mappedItem = fn(item, ignore, i);
559
+ if (mappedItem !== ignore) {
560
+ result.push(mappedItem);
561
+ }
562
+ i++;
563
+ }
564
+ return result;
565
+ }
566
+
567
+ // src/utils/isObject.ts
568
+ function isObject(value) {
569
+ return typeof value === "object" && value !== null && !Array.isArray(value);
570
+ }
571
+
572
+ // src/utils/getCacheId.ts
573
+ function getCacheId(input) {
574
+ return typeof input === "string" || typeof input === "number" ? String(input) : JSON.stringify(input && isObject(input) ? orderedProps(input) : input);
575
+ }
576
+ function orderedProps(obj) {
577
+ return filterAndMap(Object.keys(obj).sort(), (k, ignore2) => {
578
+ const value = obj[k];
579
+ if (value === void 0)
580
+ return ignore2;
581
+ return { [k]: obj[k] };
582
+ });
583
+ }
584
+
585
+ // src/collectionStore.ts
586
+ import { klona } from "klona/json";
587
+ function newTSDFCollectionStore({
588
+ debugName,
589
+ fetchFn,
590
+ disableRefetchOnWindowFocus,
591
+ lowPriorityThrottleMs,
592
+ errorNormalizer,
593
+ disableInitialDataInvalidation,
594
+ mediumPriorityThrottleMs,
595
+ initialStateItems,
596
+ disableRefetchOnMount: globalDisableRefetchOnMount,
597
+ dynamicRealtimeThrottleMs,
598
+ getCollectionItemKey: filterCollectionItemObjKey
599
+ }) {
600
+ const initialState = {};
601
+ if (initialStateItems) {
602
+ for (const item of initialStateItems) {
603
+ const itemKey = getItemKey(item.payload);
604
+ initialState[itemKey] = {
605
+ data: item.data,
606
+ error: null,
607
+ status: "success",
608
+ payload: item.payload,
609
+ refetchOnMount: disableInitialDataInvalidation ? false : "lowPriority",
610
+ wasLoaded: true
611
+ };
612
+ }
613
+ }
614
+ const store = new Store2({
615
+ debugName,
616
+ state: initialState
617
+ });
618
+ function getItemKey(params) {
619
+ return getCacheId(
620
+ filterCollectionItemObjKey ? filterCollectionItemObjKey(params) : params
621
+ );
622
+ }
623
+ async function fetch(fetchCtx, itemPayload) {
624
+ const itemId = getItemKey(itemPayload);
625
+ const payload = klona(itemPayload);
626
+ const itemState = store.state[itemId];
627
+ store.produceState(
628
+ (draft) => {
629
+ const item = draft[itemId];
630
+ if (!item) {
631
+ draft[itemId] = {
632
+ data: null,
633
+ error: null,
634
+ status: "loading",
635
+ payload,
636
+ refetchOnMount: false,
637
+ wasLoaded: false
638
+ };
639
+ return;
640
+ }
641
+ item.status = item.data !== null ? "refetching" : "loading";
642
+ item.payload = payload;
643
+ item.error = null;
644
+ item.refetchOnMount = false;
645
+ },
646
+ {
647
+ equalityCheck: deepEqual3,
648
+ action: {
649
+ type: !itemState?.data ? "fetch-start-loading" : "fetch-start-refetching",
650
+ payload
651
+ }
652
+ }
653
+ );
654
+ try {
655
+ const data = await fetchFn(payload);
656
+ if (fetchCtx.shouldAbort())
657
+ return false;
658
+ store.produceState(
659
+ (draft) => {
660
+ const item = draft[itemId];
661
+ if (!item)
662
+ return;
663
+ item.data = reusePrevIfEqual({ current: data, prev: item.data });
664
+ item.status = "success";
665
+ item.wasLoaded = true;
666
+ },
667
+ { action: { type: "fetch-success", payload } }
668
+ );
669
+ return true;
670
+ } catch (exception) {
671
+ if (fetchCtx.shouldAbort())
672
+ return false;
673
+ const error = errorNormalizer(exception);
674
+ store.produceState(
675
+ (draft) => {
676
+ const item = draft[itemId];
677
+ if (!item)
678
+ return;
679
+ item.error = error;
680
+ item.status = "error";
681
+ },
682
+ { action: { type: "fetch-error", payload, error } }
683
+ );
684
+ return false;
685
+ }
686
+ }
687
+ const fetchOrquestrator = createCollectionFetchOrquestrator({
688
+ fetchFn: fetch,
689
+ lowPriorityThrottleMs,
690
+ dynamicRealtimeThrottleMs,
691
+ mediumPriorityThrottleMs
692
+ });
693
+ function scheduleFetch(fetchType, payload) {
694
+ const multiplePayloads = Array.isArray(payload);
695
+ const payloads = multiplePayloads ? payload : [payload];
696
+ const results = [];
697
+ for (const param of payloads) {
698
+ const itemKey = getItemKey(param);
699
+ results.push(
700
+ fetchOrquestrator.get(itemKey).scheduleFetch(fetchType, param)
701
+ );
702
+ }
703
+ return multiplePayloads ? results : results[0];
704
+ }
705
+ async function awaitFetch(params) {
706
+ const itemId = getItemKey(params);
707
+ const wasAborted = await fetchOrquestrator.get(itemId).awaitFetch(params);
708
+ if (wasAborted) {
709
+ return { data: null, error: errorNormalizer(new Error("Aborted")) };
710
+ }
711
+ const item = store.state[itemId];
712
+ if (!item?.data) {
713
+ return { data: null, error: errorNormalizer(new Error("Not found")) };
714
+ }
715
+ return item.error ? { data: null, error: item.error } : { data: item.data, error: null };
716
+ }
717
+ function getItemsKeyArray(params) {
718
+ const items = store.state;
719
+ if (Array.isArray(params)) {
720
+ return params.map(getItemKey);
721
+ } else if (typeof params === "function") {
722
+ return filterAndMap(Object.entries(items), ([itemKey, item], ignore2) => {
723
+ return item && params(item.payload, item.data) ? itemKey : ignore2;
724
+ });
725
+ } else {
726
+ return [getItemKey(params)];
727
+ }
728
+ }
729
+ const storeEvents = mitt3();
730
+ const invalidationWasTriggered = /* @__PURE__ */ new Set();
731
+ function invalidateItem(itemPayload, priority = "highPriority") {
732
+ const itemsKey = getItemsKeyArray(itemPayload);
733
+ for (const itemKey of itemsKey) {
734
+ store.produceState(
735
+ (draft) => {
736
+ const item = draft[itemKey];
737
+ if (!item)
738
+ return;
739
+ item.refetchOnMount = priority;
740
+ },
741
+ { action: { type: "invalidate-data", itemKey } }
742
+ );
743
+ invalidationWasTriggered.delete(itemKey);
744
+ storeEvents.emit("invalidateData", { priority, itemKey });
745
+ }
746
+ }
747
+ function getItemState(params) {
748
+ if (typeof params === "function" || Array.isArray(params)) {
749
+ const itemsId = getItemsKeyArray(params);
750
+ return filterAndMap(itemsId, (itemId, ignore2) => {
751
+ return store.state[itemId] || ignore2;
752
+ });
753
+ }
754
+ return store.state[getItemKey(params)];
755
+ }
756
+ function useMultipleItems(queries, {
757
+ selector,
758
+ omitPayload,
759
+ returnIdleStatus,
760
+ returnRefetchingStatus,
761
+ disableRefetchOnMount = globalDisableRefetchOnMount
762
+ } = {}) {
763
+ const queriesWithId = useDeepMemo(() => {
764
+ return queries.map((payload) => {
765
+ return { itemKey: getItemKey(payload), payload };
766
+ });
767
+ }, [queries]);
768
+ const dataSelector = useCallback2((itemState) => {
769
+ if (selector)
770
+ return selector(itemState);
771
+ return itemState;
772
+ }, []);
773
+ const resultSelector = useCallback2(
774
+ (state) => {
775
+ return queriesWithId.map(
776
+ ({
777
+ itemKey,
778
+ payload
779
+ }) => {
780
+ const item = state[itemKey];
781
+ if (item === null) {
782
+ return {
783
+ itemStateKey: itemKey,
784
+ status: "deleted",
785
+ data: dataSelector(null),
786
+ error: null,
787
+ payload: omitPayload ? void 0 : payload,
788
+ isLoading: false
789
+ };
790
+ }
791
+ if (!item) {
792
+ return {
793
+ itemStateKey: itemKey,
794
+ status: returnIdleStatus ? "idle" : "loading",
795
+ data: dataSelector(null),
796
+ error: null,
797
+ payload: omitPayload ? void 0 : payload,
798
+ isLoading: returnIdleStatus ? false : true
799
+ };
800
+ }
801
+ let status = item.status;
802
+ if (!returnRefetchingStatus && item.status === "refetching") {
803
+ status = "success";
804
+ }
805
+ return {
806
+ itemStateKey: itemKey,
807
+ status,
808
+ data: dataSelector(item.data),
809
+ error: item.error,
810
+ isLoading: status === "loading",
811
+ payload: omitPayload ? void 0 : item.payload
812
+ };
813
+ }
814
+ );
815
+ },
816
+ [
817
+ dataSelector,
818
+ omitPayload,
819
+ queriesWithId,
820
+ returnIdleStatus,
821
+ returnRefetchingStatus
822
+ ]
823
+ );
824
+ const storeState = store.useSelector(resultSelector, {
825
+ equalityFn: deepEqual3,
826
+ useExternalDeps: true
827
+ });
828
+ useOnMittEvent(storeEvents, "invalidateData", (event) => {
829
+ for (const { itemKey, payload } of queriesWithId) {
830
+ if (itemKey !== event.itemKey)
831
+ continue;
832
+ if (!invalidationWasTriggered.has(itemKey)) {
833
+ scheduleFetch(event.priority, payload);
834
+ invalidationWasTriggered.add(itemKey);
835
+ }
836
+ }
837
+ });
838
+ useEffect3(() => {
839
+ for (const { itemKey: itemId, payload } of queriesWithId) {
840
+ if (itemId) {
841
+ if (disableRefetchOnMount) {
842
+ const itemState = getItemState(payload);
843
+ const shouldFetch = !itemState?.wasLoaded || itemState.refetchOnMount;
844
+ if (shouldFetch) {
845
+ scheduleFetch(
846
+ itemState?.refetchOnMount || "lowPriority",
847
+ payload
848
+ );
849
+ return;
850
+ }
851
+ } else {
852
+ scheduleFetch("lowPriority", payload);
853
+ }
854
+ }
855
+ }
856
+ }, [disableRefetchOnMount, queriesWithId]);
857
+ return storeState;
858
+ }
859
+ function useItem(payload, options = {}) {
860
+ const { selector, ensureIsLoaded } = options;
861
+ const query = useMemo3(
862
+ () => payload === false || payload === null || payload === void 0 ? [] : [payload],
863
+ [payload]
864
+ );
865
+ const item = useMultipleItems(query, options);
866
+ const result = useMemo3(
867
+ () => item[0] ?? {
868
+ payload: void 0,
869
+ data: selector ? selector(null) : null,
870
+ error: null,
871
+ status: "idle",
872
+ itemStateKey: "",
873
+ isLoading: false
874
+ },
875
+ [item]
876
+ );
877
+ const [useModifyResult, emitIsLoadedEvt] = useEnsureIsLoaded(
878
+ ensureIsLoaded,
879
+ !!payload,
880
+ () => {
881
+ if (payload) {
882
+ scheduleFetch("highPriority", payload);
883
+ }
884
+ }
885
+ );
886
+ useSubscribeToStore2(store, ({ observe }) => {
887
+ if (!ensureIsLoaded)
888
+ return;
889
+ observe.ifSelector((state) => state[result.itemStateKey]?.status).change.then(({ current }) => {
890
+ if (current === "success" || current === "error") {
891
+ emitIsLoadedEvt("isLoaded", true);
892
+ }
893
+ });
894
+ });
895
+ return useModifyResult(result);
896
+ }
897
+ function startMutation(fetchParams) {
898
+ const itemKeys = getItemsKeyArray(fetchParams);
899
+ const endMutations = [];
900
+ for (const itemKey of itemKeys) {
901
+ endMutations.push(fetchOrquestrator.get(itemKey).startMutation());
902
+ }
903
+ return () => {
904
+ for (const endMutation of endMutations) {
905
+ endMutation();
906
+ }
907
+ };
908
+ }
909
+ function addItemToState(fetchParams, data) {
910
+ const itemKey = getItemKey(fetchParams);
911
+ store.produceState(
912
+ (draftState) => {
913
+ draftState[itemKey] = {
914
+ data,
915
+ status: "success",
916
+ wasLoaded: true,
917
+ refetchOnMount: false,
918
+ error: null,
919
+ payload: klona(fetchParams)
920
+ };
921
+ },
922
+ { action: { type: "create-item-state", payload: fetchParams } }
923
+ );
924
+ }
925
+ function deleteItemState(fetchParams) {
926
+ const itemKeys = getItemsKeyArray(fetchParams);
927
+ store.produceState(
928
+ (draftState) => {
929
+ for (const itemKey of itemKeys) {
930
+ draftState[itemKey] = null;
931
+ }
932
+ },
933
+ { action: { type: "delete-item-state", payload: fetchParams } }
934
+ );
935
+ }
936
+ function updateItemState(fetchParams, produceNewData, ifNothingWasUpdated) {
937
+ const itemKeys = getItemsKeyArray(fetchParams);
938
+ let someItemWasUpdated = false;
939
+ store.batch(
940
+ () => {
941
+ store.produceState((draftState) => {
942
+ for (const itemKey of itemKeys) {
943
+ const item = draftState[itemKey];
944
+ if (!item)
945
+ continue;
946
+ if (item.data) {
947
+ someItemWasUpdated = true;
948
+ const newData = produceNewData(item.data, item);
949
+ if (newData) {
950
+ item.data = newData;
951
+ }
952
+ }
953
+ }
954
+ });
955
+ if (ifNothingWasUpdated && !someItemWasUpdated) {
956
+ ifNothingWasUpdated();
957
+ }
958
+ },
959
+ { type: "update-item-state", item: itemKeys }
960
+ );
961
+ return someItemWasUpdated;
962
+ }
963
+ if (!disableRefetchOnWindowFocus) {
964
+ let handleFocus2 = function() {
965
+ invalidateItem(() => true, "lowPriority");
966
+ };
967
+ var handleFocus = handleFocus2;
968
+ window.addEventListener("focus", handleFocus2);
969
+ window.addEventListener("visibilitychange", handleFocus2);
970
+ }
971
+ return {
972
+ store,
973
+ scheduleFetch,
974
+ awaitFetch,
975
+ useMultipleItems,
976
+ useItem,
977
+ getItemKey,
978
+ getItemState,
979
+ startMutation,
980
+ invalidateItem,
981
+ updateItemState,
982
+ addItemToState,
983
+ deleteItemState
984
+ };
985
+ }
986
+
987
+ // src/listQueryStore.ts
988
+ import mitt4 from "mitt";
989
+ import { useCallback as useCallback3, useEffect as useEffect4, useMemo as useMemo4 } from "react";
990
+ import { deepEqual as deepEqual4, Store as Store3, useSubscribeToStore as useSubscribeToStore3 } from "t-state";
991
+ import { klona as klona2 } from "klona/json";
992
+ var noFetchFnError = "No fetchItemFn was provided";
993
+ function newTSDFListQueryStore({
994
+ debugName,
995
+ fetchListFn,
996
+ fetchItemFn,
997
+ errorNormalizer,
998
+ defaultQuerySize = 50,
999
+ initialData,
1000
+ disableRefetchOnWindowFocus,
1001
+ disableRefetchOnMount: globalDisableRefetchOnMount,
1002
+ lowPriorityThrottleMs,
1003
+ disableInitialDataInvalidation,
1004
+ mediumPriorityThrottleMs,
1005
+ dynamicRealtimeThrottleMs,
1006
+ syncMutationsAndInvalidations
1007
+ }) {
1008
+ const initialState = { items: {}, queries: {}, itemQueries: {} };
1009
+ if (initialData) {
1010
+ for (const { payload, data } of initialData.items) {
1011
+ const itemKey = getItemKey(payload);
1012
+ initialState.items[itemKey] = data;
1013
+ initialState.itemQueries[itemKey] = {
1014
+ error: null,
1015
+ status: "success",
1016
+ refetchOnMount: disableInitialDataInvalidation ? false : "lowPriority",
1017
+ wasLoaded: true,
1018
+ payload
1019
+ };
1020
+ }
1021
+ for (const { payload, items, hasMore } of initialData.queries) {
1022
+ const queryKey = getQueryKey(payload);
1023
+ initialState.queries[queryKey] = {
1024
+ error: null,
1025
+ status: "success",
1026
+ refetchOnMount: disableInitialDataInvalidation ? false : "lowPriority",
1027
+ wasLoaded: true,
1028
+ payload,
1029
+ items: items.map(getItemKey),
1030
+ hasMore
1031
+ };
1032
+ }
1033
+ }
1034
+ const store = new Store3({
1035
+ debugName,
1036
+ state: initialState
1037
+ });
1038
+ function getQueryKey(params) {
1039
+ return getCacheId(params);
1040
+ }
1041
+ function getItemKey(params) {
1042
+ return getCacheId(params);
1043
+ }
1044
+ async function fetchQuery(fetchCtx, [fetchType, queryPayload, size = defaultQuerySize]) {
1045
+ const payload = klona2(queryPayload);
1046
+ const queryKey = getQueryKey(payload);
1047
+ const queryState = store.state.queries[queryKey];
1048
+ const isLoading = !queryState?.wasLoaded;
1049
+ store.produceState(
1050
+ (draft) => {
1051
+ const query = draft.queries[queryKey];
1052
+ if (!query) {
1053
+ draft.queries[queryKey] = {
1054
+ error: null,
1055
+ status: "loading",
1056
+ wasLoaded: false,
1057
+ payload,
1058
+ refetchOnMount: false,
1059
+ hasMore: false,
1060
+ items: []
1061
+ };
1062
+ return;
1063
+ }
1064
+ query.status = query.wasLoaded ? fetchType === "loadMore" ? "loadingMore" : "refetching" : "loading";
1065
+ query.error = null;
1066
+ query.refetchOnMount = false;
1067
+ },
1068
+ {
1069
+ equalityCheck: deepEqual4,
1070
+ action: {
1071
+ type: isLoading ? "fetch-query-start-loading" : fetchType === "loadMore" ? "fetch-query-loading-more" : "refetching-query-start",
1072
+ payload
1073
+ }
1074
+ }
1075
+ );
1076
+ const currentQuerySize = queryState?.items.length ?? 0;
1077
+ const querySize = (() => {
1078
+ if (fetchType === "loadMore") {
1079
+ return currentQuerySize + size;
1080
+ }
1081
+ if (isLoading)
1082
+ return size;
1083
+ return Math.max(currentQuerySize, size);
1084
+ })();
1085
+ try {
1086
+ const { items, hasMore } = await fetchListFn(payload, querySize);
1087
+ if (fetchCtx.shouldAbort())
1088
+ return false;
1089
+ store.produceState(
1090
+ (draft) => {
1091
+ const query = draft.queries[queryKey];
1092
+ if (!query)
1093
+ return;
1094
+ query.status = "success";
1095
+ query.wasLoaded = true;
1096
+ query.hasMore = hasMore;
1097
+ query.items = [];
1098
+ for (const { data, itemPayload } of items) {
1099
+ const itemKey = getItemKey(itemPayload);
1100
+ draft.items[itemKey] = reusePrevIfEqual({
1101
+ current: data,
1102
+ prev: draft.items[itemKey] ?? void 0
1103
+ });
1104
+ query.items.push(String(itemKey));
1105
+ const itemQuery = draft.itemQueries[itemKey];
1106
+ if (!itemQuery || itemQuery.status !== "loading" && itemQuery.status !== "refetching") {
1107
+ draft.itemQueries[itemKey] = {
1108
+ error: null,
1109
+ refetchOnMount: false,
1110
+ status: "success",
1111
+ wasLoaded: true,
1112
+ payload: itemPayload
1113
+ };
1114
+ }
1115
+ }
1116
+ },
1117
+ {
1118
+ action: { type: "fetch-query-success", payload }
1119
+ }
1120
+ );
1121
+ for (const { itemPayload: id } of items) {
1122
+ const itemFetchOrquestrator = fetchItemOrquestrator?.get(String(id));
1123
+ if (itemFetchOrquestrator) {
1124
+ itemFetchOrquestrator.setLastFetchStartTime(fetchCtx.getStartTime());
1125
+ }
1126
+ }
1127
+ return true;
1128
+ } catch (exception) {
1129
+ if (fetchCtx.shouldAbort())
1130
+ return false;
1131
+ const error = errorNormalizer(exception);
1132
+ store.produceState(
1133
+ (draft) => {
1134
+ const query = draft.queries[queryKey];
1135
+ if (!query)
1136
+ return;
1137
+ query.status = "error";
1138
+ query.error = error;
1139
+ },
1140
+ {
1141
+ action: { type: "fetch-query-error", payload, error }
1142
+ }
1143
+ );
1144
+ return false;
1145
+ }
1146
+ }
1147
+ function getQueryState(params) {
1148
+ return store.state.queries[getQueryKey(params)];
1149
+ }
1150
+ function getItemState(itemPayload) {
1151
+ if (typeof itemPayload === "function" || Array.isArray(itemPayload)) {
1152
+ const itemsId = getItemsKeyArray(itemPayload);
1153
+ return filterAndMap(itemsId, ({ itemKey }, ignore2) => {
1154
+ const item = store.state.items[itemKey];
1155
+ const payload = store.state.itemQueries[itemKey]?.payload;
1156
+ return !item || !payload ? ignore2 : { payload, data: item };
1157
+ });
1158
+ }
1159
+ return store.state.items[getItemKey(itemPayload)];
1160
+ }
1161
+ const fetchQueryOrquestrator = createCollectionFetchOrquestrator({
1162
+ fetchFn: fetchQuery,
1163
+ lowPriorityThrottleMs,
1164
+ dynamicRealtimeThrottleMs,
1165
+ mediumPriorityThrottleMs
1166
+ });
1167
+ function scheduleListQueryFetch(fetchType, payload, size) {
1168
+ const multiplePayloads = Array.isArray(payload);
1169
+ const payloads = multiplePayloads ? payload : [payload];
1170
+ const results = payloads.map((param) => {
1171
+ return fetchQueryOrquestrator.get(getQueryKey(param)).scheduleFetch(fetchType, ["load", param, size]);
1172
+ });
1173
+ return multiplePayloads ? results : results[0];
1174
+ }
1175
+ function loadMore(params, size) {
1176
+ const queryState = getQueryState(params);
1177
+ if (!queryState || !queryState.hasMore)
1178
+ return "skipped";
1179
+ return fetchQueryOrquestrator.get(getQueryKey(params)).scheduleFetch("highPriority", ["loadMore", params, size]);
1180
+ }
1181
+ function getQueryItems(query, itemDataSelector) {
1182
+ return filterAndMap(query.items, (itemKey, ignore2) => {
1183
+ const item = store.state.items[itemKey];
1184
+ return item ? itemDataSelector(item, itemKey) : ignore2;
1185
+ });
1186
+ }
1187
+ async function awaitListQueryFetch(params, size = defaultQuerySize) {
1188
+ const queryKey = getQueryKey(params);
1189
+ const wasAborted = await fetchQueryOrquestrator.get(queryKey).awaitFetch(["load", params, size]);
1190
+ if (wasAborted) {
1191
+ return {
1192
+ items: [],
1193
+ error: errorNormalizer(new Error("Aborted")),
1194
+ hasMore: false
1195
+ };
1196
+ }
1197
+ const query = store.state.queries[queryKey];
1198
+ if (!query) {
1199
+ return {
1200
+ items: [],
1201
+ error: errorNormalizer(new Error("Not found")),
1202
+ hasMore: false
1203
+ };
1204
+ }
1205
+ return query.error ? { items: [], error: query.error, hasMore: query.hasMore } : {
1206
+ items: getQueryItems(query, (data, itemKey) => ({ data, itemKey })),
1207
+ error: null,
1208
+ hasMore: query.hasMore
1209
+ };
1210
+ }
1211
+ async function awaitItemFetch(itemPayload) {
1212
+ if (!fetchItemOrquestrator)
1213
+ throw new Error(noFetchFnError);
1214
+ const itemKey = getItemKey(itemPayload);
1215
+ const wasAborted = await fetchItemOrquestrator.get(itemKey).awaitFetch(itemPayload);
1216
+ if (wasAborted) {
1217
+ return { data: null, error: errorNormalizer(new Error("Aborted")) };
1218
+ }
1219
+ const item = store.state.items[itemKey];
1220
+ const itemQuery = store.state.itemQueries[itemKey];
1221
+ if (!itemQuery || !item) {
1222
+ return { data: null, error: errorNormalizer(new Error("Not found")) };
1223
+ }
1224
+ return itemQuery.error ? { data: null, error: itemQuery.error } : { data: item, error: null };
1225
+ }
1226
+ function getQueriesKeyArray(payloads) {
1227
+ if (Array.isArray(payloads)) {
1228
+ return payloads.map((payload) => ({
1229
+ key: getQueryKey(payload),
1230
+ payload
1231
+ }));
1232
+ } else if (typeof payloads === "function") {
1233
+ return filterAndMap(
1234
+ Object.entries(store.state.queries),
1235
+ ([queryKey, query], ignore2) => {
1236
+ return payloads(query.payload, query, queryKey) ? {
1237
+ key: queryKey,
1238
+ payload: query.payload
1239
+ } : ignore2;
1240
+ }
1241
+ );
1242
+ } else {
1243
+ return [{ key: getQueryKey(payloads), payload: payloads }];
1244
+ }
1245
+ }
1246
+ const storeEvents = mitt4();
1247
+ const queryInvalidationWasTriggered = /* @__PURE__ */ new Set();
1248
+ function invalidateQuery(queryPayload, priority = "highPriority", ignoreInvalidationSync = false) {
1249
+ const queriesKey = getQueriesKeyArray(queryPayload);
1250
+ for (const { key } of queriesKey) {
1251
+ store.produceState(
1252
+ (draft) => {
1253
+ const query = draft.queries[key];
1254
+ if (!query)
1255
+ return;
1256
+ query.refetchOnMount = priority;
1257
+ },
1258
+ { action: { type: "invalidate-data", key } }
1259
+ );
1260
+ queryInvalidationWasTriggered.delete(key);
1261
+ storeEvents.emit("invalidateQuery", { priority, queryKey: key });
1262
+ }
1263
+ if (syncMutationsAndInvalidations && !ignoreInvalidationSync) {
1264
+ invalidateItem(
1265
+ (itemPayload) => queriesKey.some(({ payload }) => {
1266
+ return syncMutationsAndInvalidations.syncItemAndQuery(
1267
+ itemPayload,
1268
+ payload
1269
+ );
1270
+ }),
1271
+ priority,
1272
+ true
1273
+ );
1274
+ invalidateQuery(
1275
+ (queryToInvalidatePayload, _, queryToInvalidateKey) => queriesKey.some((alreadyInvalidatedQueryPayload) => {
1276
+ return queryToInvalidateKey !== alreadyInvalidatedQueryPayload.key && syncMutationsAndInvalidations.syncQueries(
1277
+ alreadyInvalidatedQueryPayload.payload,
1278
+ queryToInvalidatePayload
1279
+ );
1280
+ }),
1281
+ priority,
1282
+ true
1283
+ );
1284
+ }
1285
+ }
1286
+ function defaultItemSelector(data, id) {
1287
+ return { id, data };
1288
+ }
1289
+ function useMultipleListQueries(queries, {
1290
+ itemSelector = defaultItemSelector,
1291
+ omitPayload,
1292
+ returnIdleStatus,
1293
+ returnRefetchingStatus,
1294
+ loadSize,
1295
+ disableRefetchOnMount = globalDisableRefetchOnMount
1296
+ } = {}) {
1297
+ const queriesWithId = useDeepMemo(() => {
1298
+ return queries.map((payload) => {
1299
+ return {
1300
+ key: getQueryKey(payload),
1301
+ payload
1302
+ };
1303
+ });
1304
+ }, [queries]);
1305
+ const dataSelector = useCallback3(itemSelector, []);
1306
+ const resultSelector = useCallback3(
1307
+ (state) => {
1308
+ return queriesWithId.map(
1309
+ ({
1310
+ key: queryKey,
1311
+ payload
1312
+ }) => {
1313
+ const query = state.queries[queryKey];
1314
+ if (!query) {
1315
+ return {
1316
+ queryKey,
1317
+ status: returnIdleStatus ? "idle" : "loading",
1318
+ items: [],
1319
+ error: null,
1320
+ hasMore: false,
1321
+ payload: omitPayload ? void 0 : payload,
1322
+ isLoading: returnIdleStatus ? false : true
1323
+ };
1324
+ }
1325
+ let status = query.status;
1326
+ if (!returnRefetchingStatus && query.status === "refetching") {
1327
+ status = "success";
1328
+ }
1329
+ return {
1330
+ queryKey,
1331
+ status,
1332
+ items: getQueryItems(query, dataSelector),
1333
+ error: query.error,
1334
+ hasMore: query.hasMore,
1335
+ isLoading: status === "loading",
1336
+ payload: omitPayload ? void 0 : query.payload
1337
+ };
1338
+ }
1339
+ );
1340
+ },
1341
+ [
1342
+ dataSelector,
1343
+ omitPayload,
1344
+ queriesWithId,
1345
+ returnIdleStatus,
1346
+ returnRefetchingStatus
1347
+ ]
1348
+ );
1349
+ const storeState = store.useSelector(resultSelector, {
1350
+ equalityFn: deepEqual4,
1351
+ useExternalDeps: true
1352
+ });
1353
+ useOnMittEvent(storeEvents, "invalidateQuery", (event) => {
1354
+ for (const { key, payload } of queriesWithId) {
1355
+ if (key !== event.queryKey)
1356
+ continue;
1357
+ if (!queryInvalidationWasTriggered.has(key)) {
1358
+ scheduleListQueryFetch(event.priority, payload);
1359
+ queryInvalidationWasTriggered.add(key);
1360
+ }
1361
+ }
1362
+ });
1363
+ const loadSizeConst = useConst(() => loadSize);
1364
+ useEffect4(() => {
1365
+ for (const { key: itemId, payload: fetchParams } of queriesWithId) {
1366
+ if (itemId) {
1367
+ if (disableRefetchOnMount) {
1368
+ const itemState = getQueryState(fetchParams);
1369
+ const shouldFetch = !itemState || !itemState.wasLoaded || itemState.refetchOnMount;
1370
+ if (shouldFetch) {
1371
+ scheduleListQueryFetch(
1372
+ itemState?.refetchOnMount || "lowPriority",
1373
+ fetchParams,
1374
+ loadSizeConst
1375
+ );
1376
+ return;
1377
+ }
1378
+ } else {
1379
+ scheduleListQueryFetch("lowPriority", fetchParams, loadSizeConst);
1380
+ }
1381
+ }
1382
+ }
1383
+ }, [disableRefetchOnMount, loadSizeConst, queriesWithId]);
1384
+ return storeState;
1385
+ }
1386
+ function useListQuery(payload, options = {}) {
1387
+ const { ensureIsLoaded } = options;
1388
+ const query = useMemo4(
1389
+ () => payload === false || payload === null || payload === void 0 ? [] : [payload],
1390
+ [payload]
1391
+ );
1392
+ const queryResult = useMultipleListQueries(query, options);
1393
+ const result = useMemo4(
1394
+ () => queryResult[0] ?? {
1395
+ payload: void 0,
1396
+ error: null,
1397
+ hasMore: false,
1398
+ isLoading: false,
1399
+ status: "idle",
1400
+ queryKey: "",
1401
+ items: []
1402
+ },
1403
+ [queryResult]
1404
+ );
1405
+ const [useModifyResult, emitIsLoadedEvt] = useEnsureIsLoaded(
1406
+ ensureIsLoaded,
1407
+ !!payload,
1408
+ () => {
1409
+ if (payload) {
1410
+ scheduleListQueryFetch("highPriority", payload);
1411
+ }
1412
+ }
1413
+ );
1414
+ useSubscribeToStore3(store, ({ observe }) => {
1415
+ if (!ensureIsLoaded)
1416
+ return;
1417
+ observe.ifSelector((state) => state.queries[result.queryKey]?.status).change.then(({ current }) => {
1418
+ if (current === "success" || current === "error") {
1419
+ emitIsLoadedEvt("isLoaded", true);
1420
+ }
1421
+ });
1422
+ });
1423
+ return useModifyResult(result);
1424
+ }
1425
+ async function fetchItem(fetchCtx, itemPayload) {
1426
+ if (!fetchItemOrquestrator) {
1427
+ throw new Error(noFetchFnError);
1428
+ }
1429
+ const itemKey = getCacheId(itemPayload);
1430
+ const isLoaded = !store.state.itemQueries[itemKey]?.wasLoaded;
1431
+ store.produceState(
1432
+ (draft) => {
1433
+ const itemQuery = draft.itemQueries[itemKey];
1434
+ if (!itemQuery) {
1435
+ draft.itemQueries[itemKey] = {
1436
+ status: "loading",
1437
+ error: null,
1438
+ wasLoaded: false,
1439
+ refetchOnMount: false,
1440
+ payload: klona2(itemPayload)
1441
+ };
1442
+ return;
1443
+ }
1444
+ itemQuery.status = itemQuery.wasLoaded ? "refetching" : "loading";
1445
+ itemQuery.error = null;
1446
+ itemQuery.refetchOnMount = false;
1447
+ },
1448
+ {
1449
+ action: {
1450
+ type: isLoaded ? "fetch-item-start" : "fetch-item-refetch-start",
1451
+ itemPayload
1452
+ }
1453
+ }
1454
+ );
1455
+ try {
1456
+ const item = await fetchItemFn(itemPayload);
1457
+ if (fetchCtx.shouldAbort())
1458
+ return false;
1459
+ store.produceState(
1460
+ (draft) => {
1461
+ const itemQuery = draft.itemQueries[itemKey];
1462
+ if (!itemQuery)
1463
+ return;
1464
+ itemQuery.status = "success";
1465
+ itemQuery.wasLoaded = true;
1466
+ draft.items[itemKey] = reusePrevIfEqual({
1467
+ current: item,
1468
+ prev: draft.items[itemKey] ?? void 0
1469
+ });
1470
+ },
1471
+ {
1472
+ action: { type: "fetch-item-success", itemPayload }
1473
+ }
1474
+ );
1475
+ return true;
1476
+ } catch (exception) {
1477
+ if (fetchCtx.shouldAbort())
1478
+ return false;
1479
+ const error = errorNormalizer(exception);
1480
+ store.produceState(
1481
+ (draft) => {
1482
+ const itemQuery = draft.itemQueries[itemKey];
1483
+ if (!itemQuery)
1484
+ return;
1485
+ itemQuery.status = "error";
1486
+ itemQuery.error = error;
1487
+ },
1488
+ {
1489
+ action: { type: "fetch-item-error", itemPayload }
1490
+ }
1491
+ );
1492
+ return false;
1493
+ }
1494
+ }
1495
+ const fetchItemOrquestrator = fetchItemFn && createCollectionFetchOrquestrator({
1496
+ fetchFn: fetchItem,
1497
+ lowPriorityThrottleMs,
1498
+ dynamicRealtimeThrottleMs,
1499
+ mediumPriorityThrottleMs
1500
+ });
1501
+ function scheduleItemFetch(fetchType, itemPayload) {
1502
+ if (!fetchItemOrquestrator) {
1503
+ throw new Error(noFetchFnError);
1504
+ }
1505
+ const fetchMultiple = Array.isArray(itemPayload);
1506
+ const itemsId = fetchMultiple ? itemPayload : [itemPayload];
1507
+ const results = itemsId.map((payload) => {
1508
+ const itemKey = getCacheId(payload);
1509
+ return fetchItemOrquestrator.get(itemKey).scheduleFetch(fetchType, payload);
1510
+ });
1511
+ return fetchMultiple ? results : results[0];
1512
+ }
1513
+ function getItemsKeyArray(itemsPayload) {
1514
+ if (Array.isArray(itemsPayload)) {
1515
+ return itemsPayload.map((payload) => ({
1516
+ itemKey: getItemKey(payload),
1517
+ payload
1518
+ }));
1519
+ }
1520
+ if (typeof itemsPayload === "function") {
1521
+ return filterAndMap(
1522
+ Object.entries(store.state.items),
1523
+ ([itemKey, item], ignore2) => {
1524
+ const payload = store.state.itemQueries[itemKey]?.payload;
1525
+ if (item === null || !payload)
1526
+ return ignore2;
1527
+ return itemsPayload(payload, item) ? { itemKey, payload } : ignore2;
1528
+ }
1529
+ );
1530
+ }
1531
+ return [{ payload: itemsPayload, itemKey: getItemKey(itemsPayload) }];
1532
+ }
1533
+ const itemInvalidationWasTriggered = /* @__PURE__ */ new Set();
1534
+ function invalidateItem(itemId, priority = "highPriority", ignoreInvalidationSync = false) {
1535
+ if (!fetchItemOrquestrator) {
1536
+ throw new Error(noFetchFnError);
1537
+ }
1538
+ const itemsKey = getItemsKeyArray(itemId);
1539
+ for (const { itemKey } of itemsKey) {
1540
+ store.produceState(
1541
+ (draft) => {
1542
+ const query = draft.itemQueries[itemKey];
1543
+ if (!query)
1544
+ return;
1545
+ query.refetchOnMount = priority;
1546
+ },
1547
+ { action: { type: "invalidate-item", queryKey: itemKey } }
1548
+ );
1549
+ itemInvalidationWasTriggered.delete(itemKey);
1550
+ storeEvents.emit("invalidateItem", { priority, itemKey });
1551
+ }
1552
+ if (syncMutationsAndInvalidations && !ignoreInvalidationSync) {
1553
+ invalidateQuery(
1554
+ (query) => itemsKey.some(
1555
+ ({ payload }) => syncMutationsAndInvalidations.syncItemAndQuery(payload, query)
1556
+ ),
1557
+ priority,
1558
+ true
1559
+ );
1560
+ }
1561
+ }
1562
+ function startItemMutation(itemId) {
1563
+ if (!fetchItemOrquestrator)
1564
+ throw new Error(noFetchFnError);
1565
+ const itemsKey = getItemsKeyArray(itemId);
1566
+ const endMutations = [];
1567
+ for (const { itemKey, payload } of itemsKey) {
1568
+ endMutations.push(fetchItemOrquestrator.get(itemKey).startMutation());
1569
+ if (syncMutationsAndInvalidations) {
1570
+ for (const [queryKey, query] of Object.entries(store.state.queries)) {
1571
+ if (syncMutationsAndInvalidations.syncItemAndQuery(
1572
+ payload,
1573
+ query.payload
1574
+ )) {
1575
+ endMutations.push(
1576
+ fetchQueryOrquestrator.get(queryKey).startMutation()
1577
+ );
1578
+ }
1579
+ }
1580
+ }
1581
+ }
1582
+ return () => {
1583
+ for (const endMutation of endMutations) {
1584
+ endMutation();
1585
+ }
1586
+ };
1587
+ }
1588
+ function defaultItemDataSelector(data) {
1589
+ return data;
1590
+ }
1591
+ function useMultipleItems(itemsPayload_, {
1592
+ selector = defaultItemDataSelector,
1593
+ returnIdleStatus,
1594
+ returnRefetchingStatus,
1595
+ disableRefetchOnMount
1596
+ } = {}) {
1597
+ const dataSelector = useCallback3(selector, []);
1598
+ const memoizedItemKeys = useDeepMemo(
1599
+ () => itemsPayload_.map(
1600
+ (itemPayload) => ({
1601
+ payload: itemPayload,
1602
+ itemKey: getItemKey(itemPayload)
1603
+ })
1604
+ ),
1605
+ [itemsPayload_]
1606
+ );
1607
+ const resultSelector = useCallback3(
1608
+ (state) => {
1609
+ return memoizedItemKeys.map(
1610
+ ({
1611
+ itemKey,
1612
+ payload
1613
+ }) => {
1614
+ const itemQuery = state.itemQueries[itemKey];
1615
+ const itemState = state.items[itemKey];
1616
+ if (itemQuery === null) {
1617
+ return {
1618
+ status: "deleted",
1619
+ error: null,
1620
+ isLoading: false,
1621
+ payload,
1622
+ data: dataSelector(null, itemKey)
1623
+ };
1624
+ }
1625
+ if (!itemQuery) {
1626
+ return {
1627
+ status: returnIdleStatus ? "idle" : "loading",
1628
+ error: null,
1629
+ isLoading: returnIdleStatus ? false : true,
1630
+ payload,
1631
+ data: dataSelector(null, itemKey)
1632
+ };
1633
+ }
1634
+ let status = itemQuery.status;
1635
+ if (!returnRefetchingStatus && itemQuery.status === "refetching") {
1636
+ status = "success";
1637
+ }
1638
+ return {
1639
+ status,
1640
+ error: itemQuery.error,
1641
+ isLoading: status === "loading",
1642
+ data: dataSelector(itemState ?? null, itemKey),
1643
+ payload
1644
+ };
1645
+ }
1646
+ );
1647
+ },
1648
+ [
1649
+ dataSelector,
1650
+ memoizedItemKeys,
1651
+ returnIdleStatus,
1652
+ returnRefetchingStatus
1653
+ ]
1654
+ );
1655
+ const storeState = store.useSelector(resultSelector, {
1656
+ equalityFn: deepEqual4,
1657
+ useExternalDeps: true
1658
+ });
1659
+ useOnMittEvent(storeEvents, "invalidateItem", (event) => {
1660
+ for (const { payload, itemKey } of memoizedItemKeys) {
1661
+ if (itemKey !== event.itemKey)
1662
+ continue;
1663
+ if (!itemInvalidationWasTriggered.has(itemKey)) {
1664
+ scheduleItemFetch(event.priority, payload);
1665
+ itemInvalidationWasTriggered.add(itemKey);
1666
+ }
1667
+ }
1668
+ });
1669
+ useEffect4(() => {
1670
+ for (const { payload, itemKey } of memoizedItemKeys) {
1671
+ if (itemKey) {
1672
+ if (disableRefetchOnMount) {
1673
+ const itemState = store.state.itemQueries[itemKey];
1674
+ const shouldFetch = !itemState || !itemState.wasLoaded || itemState.refetchOnMount;
1675
+ if (shouldFetch) {
1676
+ scheduleItemFetch(
1677
+ itemState?.refetchOnMount || "lowPriority",
1678
+ payload
1679
+ );
1680
+ return;
1681
+ }
1682
+ } else {
1683
+ scheduleItemFetch("lowPriority", payload);
1684
+ }
1685
+ }
1686
+ }
1687
+ }, [disableRefetchOnMount, memoizedItemKeys]);
1688
+ return storeState;
1689
+ }
1690
+ function useItem(itemPayload, options = {}) {
1691
+ const { ensureIsLoaded } = options;
1692
+ const query = useMemo4(
1693
+ () => itemPayload === false || itemPayload === null || itemPayload === void 0 ? [] : [itemPayload],
1694
+ [itemPayload]
1695
+ );
1696
+ const queryResult = useMultipleItems(query, options);
1697
+ const memoizedSelector = useCallback3(
1698
+ options.selector ?? defaultItemDataSelector,
1699
+ []
1700
+ );
1701
+ const result = useMemo4(
1702
+ () => queryResult[0] ?? {
1703
+ error: null,
1704
+ isLoading: false,
1705
+ status: "idle",
1706
+ data: memoizedSelector(null, ""),
1707
+ payload: itemPayload || null
1708
+ },
1709
+ [itemPayload, memoizedSelector, queryResult]
1710
+ );
1711
+ const [useModifyResult, emitIsLoadedEvt] = useEnsureIsLoaded(
1712
+ ensureIsLoaded,
1713
+ !!itemPayload,
1714
+ () => {
1715
+ if (itemPayload) {
1716
+ scheduleItemFetch("highPriority", itemPayload);
1717
+ }
1718
+ }
1719
+ );
1720
+ useSubscribeToStore3(store, ({ observe }) => {
1721
+ if (!ensureIsLoaded || !itemPayload)
1722
+ return;
1723
+ observe.ifSelector((state) => state.itemQueries[itemPayload]?.status).change.then(({ current }) => {
1724
+ if (current === "success" || current === "error") {
1725
+ emitIsLoadedEvt("isLoaded", true);
1726
+ }
1727
+ });
1728
+ });
1729
+ return useModifyResult(result);
1730
+ }
1731
+ function updateItemState(itemIds, produceNewData, ifNothingWasUpdated) {
1732
+ const itemKeys = getItemsKeyArray(itemIds);
1733
+ let someItemWasUpdated = false;
1734
+ store.batch(
1735
+ () => {
1736
+ store.produceState((draftState) => {
1737
+ for (const { itemKey, payload } of itemKeys) {
1738
+ const item = draftState.items[itemKey];
1739
+ if (!item)
1740
+ continue;
1741
+ someItemWasUpdated = true;
1742
+ const newData = produceNewData(item, payload);
1743
+ if (newData) {
1744
+ draftState.items[itemKey] = newData;
1745
+ }
1746
+ }
1747
+ });
1748
+ if (ifNothingWasUpdated && !someItemWasUpdated) {
1749
+ ifNothingWasUpdated();
1750
+ }
1751
+ },
1752
+ { type: "update-item-state", item: itemKeys }
1753
+ );
1754
+ return someItemWasUpdated;
1755
+ }
1756
+ function addItemToState(itemPayload, data) {
1757
+ const itemKey = getItemKey(itemPayload);
1758
+ store.produceState(
1759
+ (draftState) => {
1760
+ draftState.items[itemKey] = data;
1761
+ draftState.itemQueries[itemKey] = {
1762
+ status: "success",
1763
+ wasLoaded: true,
1764
+ refetchOnMount: false,
1765
+ error: null,
1766
+ payload: klona2(itemPayload)
1767
+ };
1768
+ },
1769
+ { action: { type: "create-item-state", itemPayload } }
1770
+ );
1771
+ }
1772
+ function deleteItemState(itemId) {
1773
+ const itemsId = getItemsKeyArray(itemId);
1774
+ store.produceState(
1775
+ (draftState) => {
1776
+ for (const { itemKey } of itemsId) {
1777
+ draftState.items[itemKey] = null;
1778
+ draftState.itemQueries[itemKey] = null;
1779
+ for (const query of Object.values(draftState.queries)) {
1780
+ if (query.items.includes(itemKey)) {
1781
+ query.items = query.items.filter((i) => i !== itemKey);
1782
+ }
1783
+ }
1784
+ }
1785
+ },
1786
+ { action: { type: "delete-item-state", itemId } }
1787
+ );
1788
+ }
1789
+ if (!disableRefetchOnWindowFocus) {
1790
+ let handleFocus2 = function() {
1791
+ invalidateQuery(() => true, "lowPriority");
1792
+ invalidateItem(() => true, "lowPriority");
1793
+ };
1794
+ var handleFocus = handleFocus2;
1795
+ window.addEventListener("focus", handleFocus2);
1796
+ window.addEventListener("visibilitychange", handleFocus2);
1797
+ }
1798
+ return {
1799
+ store,
1800
+ scheduleListQueryFetch,
1801
+ getQueryState,
1802
+ getQueryKey,
1803
+ deleteItemState,
1804
+ getItemState,
1805
+ loadMore,
1806
+ invalidateQuery,
1807
+ invalidateItem,
1808
+ scheduleItemFetch,
1809
+ awaitItemFetch,
1810
+ awaitListQueryFetch,
1811
+ useMultipleListQueries,
1812
+ useListQuery,
1813
+ getItemKey,
1814
+ useItem,
1815
+ useMultipleItems,
1816
+ addItemToState,
1817
+ updateItemState,
1818
+ startItemMutation
1819
+ };
1820
+ }
1821
+ export {
1822
+ newTSDFCollectionStore,
1823
+ newTSDFDocumentStore,
1824
+ newTSDFListQueryStore
1825
+ };