tsdf 7.1.0 → 8.0.0-beta.10

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.
package/dist/main.js ADDED
@@ -0,0 +1,1811 @@
1
+ // src/documentStore.ts
2
+ import { produce } from "immer";
3
+ import mitt2 from "mitt";
4
+ import { useCallback, useEffect as useEffect2 } from "react";
5
+ import { deepEqual as deepEqual2, 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/documentStore.ts
340
+ function newTSDFDocumentStore({
341
+ debugName,
342
+ fetchFn,
343
+ initialData,
344
+ disableRefetchOnWindowFocus,
345
+ disableRefetchOnMount: globalDisableRefetchOnMount,
346
+ lowPriorityThrottleMs,
347
+ mediumPriorityThrottleMs,
348
+ dynamicRealtimeThrottleMs,
349
+ disableInitialDataInvalidation,
350
+ errorNormalizer
351
+ }) {
352
+ const store = new Store({
353
+ debugName,
354
+ state: {
355
+ data: initialData ?? null,
356
+ error: null,
357
+ status: initialData ? "success" : "idle",
358
+ refetchOnMount: !!initialData && !disableInitialDataInvalidation ? "lowPriority" : false
359
+ }
360
+ });
361
+ async function fetch(fetchCtx, _) {
362
+ store.setPartialState(
363
+ {
364
+ status: store.state.status === "success" ? "refetching" : "loading",
365
+ error: null,
366
+ refetchOnMount: false
367
+ },
368
+ {
369
+ equalityCheck: deepEqual2,
370
+ action: store.state.status === "success" ? "fetch-start-refetching" : "fetch-start-loading"
371
+ }
372
+ );
373
+ try {
374
+ const data = await fetchFn();
375
+ if (fetchCtx.shouldAbort())
376
+ return false;
377
+ store.setPartialState(
378
+ {
379
+ data,
380
+ status: "success"
381
+ },
382
+ { action: "fetch-success", equalityCheck: deepEqual2 }
383
+ );
384
+ return true;
385
+ } catch (exception) {
386
+ if (fetchCtx.shouldAbort())
387
+ return false;
388
+ store.setPartialState(
389
+ {
390
+ error: errorNormalizer(exception),
391
+ status: "error"
392
+ },
393
+ { action: "fetch-error" }
394
+ );
395
+ return false;
396
+ }
397
+ }
398
+ const fetchOrquestrator = createFetchOrquestrator({
399
+ fetchFn: fetch,
400
+ lowPriorityThrottleMs,
401
+ dynamicRealtimeThrottleMs,
402
+ mediumPriorityThrottleMs
403
+ });
404
+ function scheduleFetch(fetchType) {
405
+ return fetchOrquestrator.scheduleFetch(fetchType, null);
406
+ }
407
+ async function awaitFetch() {
408
+ const wasAborted = await fetchOrquestrator.awaitFetch(null);
409
+ if (wasAborted) {
410
+ return { data: null, error: errorNormalizer(new Error("Aborted")) };
411
+ }
412
+ if (!store.state.data) {
413
+ return { data: null, error: errorNormalizer(new Error("No data")) };
414
+ }
415
+ return store.state.error ? { data: null, error: store.state.error } : { data: store.state.data, error: null };
416
+ }
417
+ const storeEvents = mitt2();
418
+ let invalidationWasTriggered = false;
419
+ function invalidateData(priority = "highPriority") {
420
+ store.setKey("refetchOnMount", priority, { action: "invalidate-data" });
421
+ invalidationWasTriggered = false;
422
+ storeEvents.emit("invalidateData", priority);
423
+ }
424
+ function useDocument({
425
+ selector,
426
+ disabled,
427
+ returnRefetchingStatus,
428
+ disableRefetchOnMount = globalDisableRefetchOnMount,
429
+ returnIdleStatus = !!disabled,
430
+ ensureIsLoaded
431
+ } = {}) {
432
+ const storeStateSelector = useCallback(
433
+ (state) => {
434
+ const { error } = state;
435
+ const data = selector ? selector(state.data) : state.data;
436
+ let status = state.status;
437
+ if (!returnIdleStatus && status === "idle") {
438
+ status = "loading";
439
+ }
440
+ if (!returnRefetchingStatus && status === "refetching") {
441
+ status = "success";
442
+ }
443
+ return {
444
+ data,
445
+ error,
446
+ status,
447
+ isLoading: status === "loading"
448
+ };
449
+ },
450
+ [returnRefetchingStatus, returnIdleStatus, selector]
451
+ );
452
+ const storeState = store.useSelector(storeStateSelector, {
453
+ useExternalDeps: true
454
+ });
455
+ useOnMittEvent(storeEvents, "invalidateData", (priority) => {
456
+ if (!invalidationWasTriggered) {
457
+ scheduleFetch(priority);
458
+ invalidationWasTriggered = true;
459
+ }
460
+ });
461
+ useEffect2(() => {
462
+ if (disabled)
463
+ return;
464
+ if (disableRefetchOnMount) {
465
+ const shouldFetch = store.state.refetchOnMount || store.state.status === "idle";
466
+ if (shouldFetch) {
467
+ scheduleFetch(store.state.refetchOnMount || "lowPriority");
468
+ }
469
+ } else {
470
+ scheduleFetch("lowPriority");
471
+ }
472
+ }, [disableRefetchOnMount, disabled]);
473
+ const [useModifyResult, emitIsLoadedEvt] = useEnsureIsLoaded(
474
+ ensureIsLoaded,
475
+ !disabled,
476
+ () => {
477
+ scheduleFetch("highPriority");
478
+ }
479
+ );
480
+ useSubscribeToStore(store, ({ observe }) => {
481
+ observe.ifSelector((state) => state.status).change.then(({ current }) => {
482
+ if (current === "success" || current === "error") {
483
+ emitIsLoadedEvt("isLoaded", true);
484
+ }
485
+ });
486
+ });
487
+ return useModifyResult(storeState);
488
+ }
489
+ function updateState(produceNewData) {
490
+ store.setKey(
491
+ "data",
492
+ (current) => {
493
+ if (!current)
494
+ return current;
495
+ return produce(current, produceNewData);
496
+ },
497
+ { action: "update-state" }
498
+ );
499
+ }
500
+ if (!disableRefetchOnWindowFocus) {
501
+ let handleFocus2 = function() {
502
+ invalidateData("lowPriority");
503
+ };
504
+ var handleFocus = handleFocus2;
505
+ window.addEventListener("focus", handleFocus2);
506
+ window.addEventListener("visibilitychange", handleFocus2);
507
+ }
508
+ return {
509
+ store,
510
+ awaitFetch,
511
+ scheduleFetch,
512
+ invalidateData,
513
+ useDocument,
514
+ updateState,
515
+ startMutation: fetchOrquestrator.startMutation
516
+ };
517
+ }
518
+
519
+ // src/collectionStore.ts
520
+ import mitt3 from "mitt";
521
+ import { useCallback as useCallback2, useEffect as useEffect3, useMemo as useMemo3 } from "react";
522
+ import { deepEqual as deepEqual3, Store as Store2, useSubscribeToStore as useSubscribeToStore2 } from "t-state";
523
+
524
+ // src/collectionFetchOrquestrator.ts
525
+ function createCollectionFetchOrquestrator(props) {
526
+ const fetchOrquestrators = /* @__PURE__ */ new Map();
527
+ function getFetchOrquestrator(key) {
528
+ if (!fetchOrquestrators.has(key)) {
529
+ fetchOrquestrators.set(key, createFetchOrquestrator(props));
530
+ }
531
+ return fetchOrquestrators.get(key);
532
+ }
533
+ return {
534
+ get: getFetchOrquestrator
535
+ };
536
+ }
537
+
538
+ // src/utils/filterAndMap.ts
539
+ var ignore = Symbol();
540
+ function filterAndMap(arr, fn) {
541
+ const result = [];
542
+ let i = 0;
543
+ for (const item of arr) {
544
+ const mappedItem = fn(item, ignore, i);
545
+ if (mappedItem !== ignore) {
546
+ result.push(mappedItem);
547
+ }
548
+ i++;
549
+ }
550
+ return result;
551
+ }
552
+
553
+ // src/utils/isObject.ts
554
+ function isObject(value) {
555
+ return typeof value === "object" && value !== null && !Array.isArray(value);
556
+ }
557
+
558
+ // src/utils/getCacheId.ts
559
+ function getCacheId(input) {
560
+ return typeof input === "string" || typeof input === "number" ? String(input) : JSON.stringify(input && isObject(input) ? orderedProps(input) : input);
561
+ }
562
+ function orderedProps(obj) {
563
+ return filterAndMap(Object.keys(obj).sort(), (k, ignore2) => {
564
+ const value = obj[k];
565
+ if (value === void 0)
566
+ return ignore2;
567
+ return { [k]: obj[k] };
568
+ });
569
+ }
570
+
571
+ // src/collectionStore.ts
572
+ import { klona } from "klona/json";
573
+ function newTSDFCollectionStore({
574
+ debugName,
575
+ fetchFn,
576
+ disableRefetchOnWindowFocus,
577
+ lowPriorityThrottleMs,
578
+ errorNormalizer,
579
+ disableInitialDataInvalidation,
580
+ mediumPriorityThrottleMs,
581
+ initialStateItems,
582
+ disableRefetchOnMount: globalDisableRefetchOnMount,
583
+ dynamicRealtimeThrottleMs,
584
+ getCollectionItemKey: filterCollectionItemObjKey
585
+ }) {
586
+ const initialState = {};
587
+ if (initialStateItems) {
588
+ for (const item of initialStateItems) {
589
+ const itemKey = getItemKey(item.payload);
590
+ initialState[itemKey] = {
591
+ data: item.data,
592
+ error: null,
593
+ status: "success",
594
+ payload: item.payload,
595
+ refetchOnMount: disableInitialDataInvalidation ? false : "lowPriority",
596
+ wasLoaded: true
597
+ };
598
+ }
599
+ }
600
+ const store = new Store2({
601
+ debugName,
602
+ state: initialState
603
+ });
604
+ function getItemKey(params) {
605
+ return getCacheId(
606
+ filterCollectionItemObjKey ? filterCollectionItemObjKey(params) : params
607
+ );
608
+ }
609
+ async function fetch(fetchCtx, itemPayload) {
610
+ const itemId = getItemKey(itemPayload);
611
+ const payload = klona(itemPayload);
612
+ const itemState = store.state[itemId];
613
+ store.produceState(
614
+ (draft) => {
615
+ const item = draft[itemId];
616
+ if (!item) {
617
+ draft[itemId] = {
618
+ data: null,
619
+ error: null,
620
+ status: "loading",
621
+ payload,
622
+ refetchOnMount: false,
623
+ wasLoaded: false
624
+ };
625
+ return;
626
+ }
627
+ item.status = item.data !== null ? "refetching" : "loading";
628
+ item.payload = payload;
629
+ item.error = null;
630
+ item.refetchOnMount = false;
631
+ },
632
+ {
633
+ equalityCheck: deepEqual3,
634
+ action: {
635
+ type: !itemState?.data ? "fetch-start-loading" : "fetch-start-refetching",
636
+ payload
637
+ }
638
+ }
639
+ );
640
+ try {
641
+ const data = await fetchFn(payload);
642
+ if (fetchCtx.shouldAbort())
643
+ return false;
644
+ store.produceState(
645
+ (draft) => {
646
+ const item = draft[itemId];
647
+ if (!item)
648
+ return;
649
+ item.data = data;
650
+ item.status = "success";
651
+ item.wasLoaded = true;
652
+ },
653
+ {
654
+ action: { type: "fetch-success", payload },
655
+ equalityCheck: deepEqual3
656
+ }
657
+ );
658
+ return true;
659
+ } catch (exception) {
660
+ if (fetchCtx.shouldAbort())
661
+ return false;
662
+ const error = errorNormalizer(exception);
663
+ store.produceState(
664
+ (draft) => {
665
+ const item = draft[itemId];
666
+ if (!item)
667
+ return;
668
+ item.error = error;
669
+ item.status = "error";
670
+ },
671
+ { action: { type: "fetch-error", payload, error } }
672
+ );
673
+ return false;
674
+ }
675
+ }
676
+ const fetchOrquestrator = createCollectionFetchOrquestrator({
677
+ fetchFn: fetch,
678
+ lowPriorityThrottleMs,
679
+ dynamicRealtimeThrottleMs,
680
+ mediumPriorityThrottleMs
681
+ });
682
+ function scheduleFetch(fetchType, payload) {
683
+ const multiplePayloads = Array.isArray(payload);
684
+ const payloads = multiplePayloads ? payload : [payload];
685
+ const results = [];
686
+ for (const param of payloads) {
687
+ const itemKey = getItemKey(param);
688
+ results.push(
689
+ fetchOrquestrator.get(itemKey).scheduleFetch(fetchType, param)
690
+ );
691
+ }
692
+ return multiplePayloads ? results : results[0];
693
+ }
694
+ async function awaitFetch(params) {
695
+ const itemId = getItemKey(params);
696
+ const wasAborted = await fetchOrquestrator.get(itemId).awaitFetch(params);
697
+ if (wasAborted) {
698
+ return { data: null, error: errorNormalizer(new Error("Aborted")) };
699
+ }
700
+ const item = store.state[itemId];
701
+ if (!item?.data) {
702
+ return { data: null, error: errorNormalizer(new Error("Not found")) };
703
+ }
704
+ return item.error ? { data: null, error: item.error } : { data: item.data, error: null };
705
+ }
706
+ function getItemsKeyArray(params) {
707
+ const items = store.state;
708
+ if (Array.isArray(params)) {
709
+ return params.map(getItemKey);
710
+ } else if (typeof params === "function") {
711
+ return filterAndMap(Object.entries(items), ([itemKey, item], ignore2) => {
712
+ return item && params(item.payload, item.data) ? itemKey : ignore2;
713
+ });
714
+ } else {
715
+ return [getItemKey(params)];
716
+ }
717
+ }
718
+ const storeEvents = mitt3();
719
+ const invalidationWasTriggered = /* @__PURE__ */ new Set();
720
+ function invalidateItem(itemPayload, priority = "highPriority") {
721
+ const itemsKey = getItemsKeyArray(itemPayload);
722
+ for (const itemKey of itemsKey) {
723
+ store.produceState(
724
+ (draft) => {
725
+ const item = draft[itemKey];
726
+ if (!item)
727
+ return;
728
+ item.refetchOnMount = priority;
729
+ },
730
+ { action: { type: "invalidate-data", itemKey } }
731
+ );
732
+ invalidationWasTriggered.delete(itemKey);
733
+ storeEvents.emit("invalidateData", { priority, itemKey });
734
+ }
735
+ }
736
+ function getItemState(params) {
737
+ if (typeof params === "function" || Array.isArray(params)) {
738
+ const itemsId = getItemsKeyArray(params);
739
+ return filterAndMap(itemsId, (itemId, ignore2) => {
740
+ return store.state[itemId] || ignore2;
741
+ });
742
+ }
743
+ return store.state[getItemKey(params)];
744
+ }
745
+ function useMultipleItems(queries, {
746
+ selector,
747
+ omitPayload,
748
+ returnIdleStatus,
749
+ returnRefetchingStatus,
750
+ disableRefetchOnMount = globalDisableRefetchOnMount
751
+ } = {}) {
752
+ const queriesWithId = useDeepMemo(() => {
753
+ return queries.map((payload) => {
754
+ return { itemKey: getItemKey(payload), payload };
755
+ });
756
+ }, [queries]);
757
+ const dataSelector = useCallback2((itemState) => {
758
+ if (selector)
759
+ return selector(itemState);
760
+ return itemState;
761
+ }, []);
762
+ const resultSelector = useCallback2(
763
+ (state) => {
764
+ return queriesWithId.map(
765
+ ({
766
+ itemKey,
767
+ payload
768
+ }) => {
769
+ const item = state[itemKey];
770
+ if (item === null) {
771
+ return {
772
+ itemStateKey: itemKey,
773
+ status: "deleted",
774
+ data: dataSelector(null),
775
+ error: null,
776
+ payload: omitPayload ? void 0 : payload,
777
+ isLoading: false
778
+ };
779
+ }
780
+ if (!item) {
781
+ return {
782
+ itemStateKey: itemKey,
783
+ status: returnIdleStatus ? "idle" : "loading",
784
+ data: dataSelector(null),
785
+ error: null,
786
+ payload: omitPayload ? void 0 : payload,
787
+ isLoading: returnIdleStatus ? false : true
788
+ };
789
+ }
790
+ let status = item.status;
791
+ if (!returnRefetchingStatus && item.status === "refetching") {
792
+ status = "success";
793
+ }
794
+ return {
795
+ itemStateKey: itemKey,
796
+ status,
797
+ data: dataSelector(item.data),
798
+ error: item.error,
799
+ isLoading: status === "loading",
800
+ payload: omitPayload ? void 0 : item.payload
801
+ };
802
+ }
803
+ );
804
+ },
805
+ [
806
+ dataSelector,
807
+ omitPayload,
808
+ queriesWithId,
809
+ returnIdleStatus,
810
+ returnRefetchingStatus
811
+ ]
812
+ );
813
+ const storeState = store.useSelector(resultSelector, {
814
+ equalityFn: deepEqual3,
815
+ useExternalDeps: true
816
+ });
817
+ useOnMittEvent(storeEvents, "invalidateData", (event) => {
818
+ for (const { itemKey, payload } of queriesWithId) {
819
+ if (itemKey !== event.itemKey)
820
+ continue;
821
+ if (!invalidationWasTriggered.has(itemKey)) {
822
+ scheduleFetch(event.priority, payload);
823
+ invalidationWasTriggered.add(itemKey);
824
+ }
825
+ }
826
+ });
827
+ useEffect3(() => {
828
+ for (const { itemKey: itemId, payload } of queriesWithId) {
829
+ if (itemId) {
830
+ if (disableRefetchOnMount) {
831
+ const itemState = getItemState(payload);
832
+ const shouldFetch = !itemState?.wasLoaded || itemState.refetchOnMount;
833
+ if (shouldFetch) {
834
+ scheduleFetch(
835
+ itemState?.refetchOnMount || "lowPriority",
836
+ payload
837
+ );
838
+ return;
839
+ }
840
+ } else {
841
+ scheduleFetch("lowPriority", payload);
842
+ }
843
+ }
844
+ }
845
+ }, [disableRefetchOnMount, queriesWithId]);
846
+ return storeState;
847
+ }
848
+ function useItem(payload, options = {}) {
849
+ const { selector, ensureIsLoaded } = options;
850
+ const query = useMemo3(
851
+ () => payload === false || payload === null || payload === void 0 ? [] : [payload],
852
+ [payload]
853
+ );
854
+ const item = useMultipleItems(query, options);
855
+ const result = useMemo3(
856
+ () => item[0] ?? {
857
+ payload: void 0,
858
+ data: selector ? selector(null) : null,
859
+ error: null,
860
+ status: "idle",
861
+ itemStateKey: "",
862
+ isLoading: false
863
+ },
864
+ [item]
865
+ );
866
+ const [useModifyResult, emitIsLoadedEvt] = useEnsureIsLoaded(
867
+ ensureIsLoaded,
868
+ !!payload,
869
+ () => {
870
+ if (payload) {
871
+ scheduleFetch("highPriority", payload);
872
+ }
873
+ }
874
+ );
875
+ useSubscribeToStore2(store, ({ observe }) => {
876
+ if (!ensureIsLoaded)
877
+ return;
878
+ observe.ifSelector((state) => state[result.itemStateKey]?.status).change.then(({ current }) => {
879
+ if (current === "success" || current === "error") {
880
+ emitIsLoadedEvt("isLoaded", true);
881
+ }
882
+ });
883
+ });
884
+ return useModifyResult(result);
885
+ }
886
+ function startMutation(fetchParams) {
887
+ const itemKeys = getItemsKeyArray(fetchParams);
888
+ const endMutations = [];
889
+ for (const itemKey of itemKeys) {
890
+ endMutations.push(fetchOrquestrator.get(itemKey).startMutation());
891
+ }
892
+ return () => {
893
+ for (const endMutation of endMutations) {
894
+ endMutation();
895
+ }
896
+ };
897
+ }
898
+ function addItemToState(fetchParams, data) {
899
+ const itemKey = getItemKey(fetchParams);
900
+ store.produceState(
901
+ (draftState) => {
902
+ draftState[itemKey] = {
903
+ data,
904
+ status: "success",
905
+ wasLoaded: true,
906
+ refetchOnMount: false,
907
+ error: null,
908
+ payload: klona(fetchParams)
909
+ };
910
+ },
911
+ { action: { type: "create-item-state", payload: fetchParams } }
912
+ );
913
+ }
914
+ function deleteItemState(fetchParams) {
915
+ const itemKeys = getItemsKeyArray(fetchParams);
916
+ store.produceState(
917
+ (draftState) => {
918
+ for (const itemKey of itemKeys) {
919
+ draftState[itemKey] = null;
920
+ }
921
+ },
922
+ { action: { type: "delete-item-state", payload: fetchParams } }
923
+ );
924
+ }
925
+ function updateItemState(fetchParams, produceNewData, ifNothingWasUpdated) {
926
+ const itemKeys = getItemsKeyArray(fetchParams);
927
+ let someItemWasUpdated = false;
928
+ store.batch(
929
+ () => {
930
+ store.produceState((draftState) => {
931
+ for (const itemKey of itemKeys) {
932
+ const item = draftState[itemKey];
933
+ if (!item)
934
+ continue;
935
+ if (item.data) {
936
+ someItemWasUpdated = true;
937
+ const newData = produceNewData(item.data, item);
938
+ if (newData) {
939
+ item.data = newData;
940
+ }
941
+ }
942
+ }
943
+ });
944
+ if (ifNothingWasUpdated && !someItemWasUpdated) {
945
+ ifNothingWasUpdated();
946
+ }
947
+ },
948
+ { type: "update-item-state", item: itemKeys }
949
+ );
950
+ return someItemWasUpdated;
951
+ }
952
+ if (!disableRefetchOnWindowFocus) {
953
+ let handleFocus2 = function() {
954
+ invalidateItem(() => true, "lowPriority");
955
+ };
956
+ var handleFocus = handleFocus2;
957
+ window.addEventListener("focus", handleFocus2);
958
+ window.addEventListener("visibilitychange", handleFocus2);
959
+ }
960
+ return {
961
+ store,
962
+ scheduleFetch,
963
+ awaitFetch,
964
+ useMultipleItems,
965
+ useItem,
966
+ getItemKey,
967
+ getItemState,
968
+ startMutation,
969
+ invalidateItem,
970
+ updateItemState,
971
+ addItemToState,
972
+ deleteItemState
973
+ };
974
+ }
975
+
976
+ // src/listQueryStore.ts
977
+ import mitt4 from "mitt";
978
+ import { useCallback as useCallback3, useEffect as useEffect4, useMemo as useMemo4 } from "react";
979
+ import { deepEqual as deepEqual4, Store as Store3, useSubscribeToStore as useSubscribeToStore3 } from "t-state";
980
+ import { klona as klona2 } from "klona/json";
981
+ var noFetchFnError = "No fetchItemFn was provided";
982
+ function newTSDFListQueryStore({
983
+ debugName,
984
+ fetchListFn,
985
+ fetchItemFn,
986
+ errorNormalizer,
987
+ defaultQuerySize = 50,
988
+ initialData,
989
+ disableRefetchOnWindowFocus,
990
+ disableRefetchOnMount: globalDisableRefetchOnMount,
991
+ lowPriorityThrottleMs,
992
+ disableInitialDataInvalidation,
993
+ mediumPriorityThrottleMs,
994
+ dynamicRealtimeThrottleMs,
995
+ syncMutationsAndInvalidations
996
+ }) {
997
+ const initialState = { items: {}, queries: {}, itemQueries: {} };
998
+ if (initialData) {
999
+ for (const { payload, data } of initialData.items) {
1000
+ const itemKey = getItemKey(payload);
1001
+ initialState.items[itemKey] = data;
1002
+ initialState.itemQueries[itemKey] = {
1003
+ error: null,
1004
+ status: "success",
1005
+ refetchOnMount: disableInitialDataInvalidation ? false : "lowPriority",
1006
+ wasLoaded: true,
1007
+ payload
1008
+ };
1009
+ }
1010
+ for (const { payload, items, hasMore } of initialData.queries) {
1011
+ const queryKey = getQueryKey(payload);
1012
+ initialState.queries[queryKey] = {
1013
+ error: null,
1014
+ status: "success",
1015
+ refetchOnMount: disableInitialDataInvalidation ? false : "lowPriority",
1016
+ wasLoaded: true,
1017
+ payload,
1018
+ items: items.map(getItemKey),
1019
+ hasMore
1020
+ };
1021
+ }
1022
+ }
1023
+ const store = new Store3({
1024
+ debugName,
1025
+ state: initialState
1026
+ });
1027
+ function getQueryKey(params) {
1028
+ return getCacheId(params);
1029
+ }
1030
+ function getItemKey(params) {
1031
+ return getCacheId(params);
1032
+ }
1033
+ async function fetchQuery(fetchCtx, [fetchType, queryPayload, size = defaultQuerySize]) {
1034
+ const payload = klona2(queryPayload);
1035
+ const queryKey = getQueryKey(payload);
1036
+ const queryState = store.state.queries[queryKey];
1037
+ const isLoading = !queryState?.wasLoaded;
1038
+ store.produceState(
1039
+ (draft) => {
1040
+ const query = draft.queries[queryKey];
1041
+ if (!query) {
1042
+ draft.queries[queryKey] = {
1043
+ error: null,
1044
+ status: "loading",
1045
+ wasLoaded: false,
1046
+ payload,
1047
+ refetchOnMount: false,
1048
+ hasMore: false,
1049
+ items: []
1050
+ };
1051
+ return;
1052
+ }
1053
+ query.status = query.wasLoaded ? fetchType === "loadMore" ? "loadingMore" : "refetching" : "loading";
1054
+ query.error = null;
1055
+ query.refetchOnMount = false;
1056
+ },
1057
+ {
1058
+ equalityCheck: deepEqual4,
1059
+ action: {
1060
+ type: isLoading ? "fetch-query-start-loading" : fetchType === "loadMore" ? "fetch-query-loading-more" : "refetching-query-start",
1061
+ payload
1062
+ }
1063
+ }
1064
+ );
1065
+ const currentQuerySize = queryState?.items.length ?? 0;
1066
+ const querySize = (() => {
1067
+ if (fetchType === "loadMore") {
1068
+ return currentQuerySize + size;
1069
+ }
1070
+ if (isLoading)
1071
+ return size;
1072
+ return Math.max(currentQuerySize, size);
1073
+ })();
1074
+ try {
1075
+ const { items, hasMore } = await fetchListFn(payload, querySize);
1076
+ if (fetchCtx.shouldAbort())
1077
+ return false;
1078
+ store.produceState(
1079
+ (draft) => {
1080
+ const query = draft.queries[queryKey];
1081
+ if (!query)
1082
+ return;
1083
+ query.status = "success";
1084
+ query.wasLoaded = true;
1085
+ query.hasMore = hasMore;
1086
+ query.items = [];
1087
+ for (const { data, itemPayload } of items) {
1088
+ const itemKey = getItemKey(itemPayload);
1089
+ draft.items[itemKey] = data;
1090
+ query.items.push(String(itemKey));
1091
+ const itemQuery = draft.itemQueries[itemKey];
1092
+ if (!itemQuery || itemQuery.status !== "loading" && itemQuery.status !== "refetching") {
1093
+ draft.itemQueries[itemKey] = {
1094
+ error: null,
1095
+ refetchOnMount: false,
1096
+ status: "success",
1097
+ wasLoaded: true,
1098
+ payload: itemPayload
1099
+ };
1100
+ }
1101
+ }
1102
+ },
1103
+ {
1104
+ equalityCheck: deepEqual4,
1105
+ action: { type: "fetch-query-success", payload }
1106
+ }
1107
+ );
1108
+ for (const { itemPayload: id } of items) {
1109
+ const itemFetchOrquestrator = fetchItemOrquestrator?.get(String(id));
1110
+ if (itemFetchOrquestrator) {
1111
+ itemFetchOrquestrator.setLastFetchStartTime(fetchCtx.getStartTime());
1112
+ }
1113
+ }
1114
+ return true;
1115
+ } catch (exception) {
1116
+ if (fetchCtx.shouldAbort())
1117
+ return false;
1118
+ const error = errorNormalizer(exception);
1119
+ store.produceState(
1120
+ (draft) => {
1121
+ const query = draft.queries[queryKey];
1122
+ if (!query)
1123
+ return;
1124
+ query.status = "error";
1125
+ query.error = error;
1126
+ },
1127
+ {
1128
+ action: { type: "fetch-query-error", payload, error }
1129
+ }
1130
+ );
1131
+ return false;
1132
+ }
1133
+ }
1134
+ function getQueryState(params) {
1135
+ return store.state.queries[getQueryKey(params)];
1136
+ }
1137
+ function getItemState(itemPayload) {
1138
+ if (typeof itemPayload === "function" || Array.isArray(itemPayload)) {
1139
+ const itemsId = getItemsKeyArray(itemPayload);
1140
+ return filterAndMap(itemsId, ({ itemKey }, ignore2) => {
1141
+ const item = store.state.items[itemKey];
1142
+ const payload = store.state.itemQueries[itemKey]?.payload;
1143
+ return !item || !payload ? ignore2 : { payload, data: item };
1144
+ });
1145
+ }
1146
+ return store.state.items[getItemKey(itemPayload)];
1147
+ }
1148
+ const fetchQueryOrquestrator = createCollectionFetchOrquestrator({
1149
+ fetchFn: fetchQuery,
1150
+ lowPriorityThrottleMs,
1151
+ dynamicRealtimeThrottleMs,
1152
+ mediumPriorityThrottleMs
1153
+ });
1154
+ function scheduleListQueryFetch(fetchType, payload, size) {
1155
+ const multiplePayloads = Array.isArray(payload);
1156
+ const payloads = multiplePayloads ? payload : [payload];
1157
+ const results = payloads.map((param) => {
1158
+ return fetchQueryOrquestrator.get(getQueryKey(param)).scheduleFetch(fetchType, ["load", param, size]);
1159
+ });
1160
+ return multiplePayloads ? results : results[0];
1161
+ }
1162
+ function loadMore(params, size) {
1163
+ const queryState = getQueryState(params);
1164
+ if (!queryState || !queryState.hasMore)
1165
+ return "skipped";
1166
+ return fetchQueryOrquestrator.get(getQueryKey(params)).scheduleFetch("highPriority", ["loadMore", params, size]);
1167
+ }
1168
+ function getQueryItems(query, itemDataSelector) {
1169
+ return filterAndMap(query.items, (itemKey, ignore2) => {
1170
+ const item = store.state.items[itemKey];
1171
+ return item ? itemDataSelector(item, itemKey) : ignore2;
1172
+ });
1173
+ }
1174
+ async function awaitListQueryFetch(params, size = defaultQuerySize) {
1175
+ const queryKey = getQueryKey(params);
1176
+ const wasAborted = await fetchQueryOrquestrator.get(queryKey).awaitFetch(["load", params, size]);
1177
+ if (wasAborted) {
1178
+ return {
1179
+ items: [],
1180
+ error: errorNormalizer(new Error("Aborted")),
1181
+ hasMore: false
1182
+ };
1183
+ }
1184
+ const query = store.state.queries[queryKey];
1185
+ if (!query) {
1186
+ return {
1187
+ items: [],
1188
+ error: errorNormalizer(new Error("Not found")),
1189
+ hasMore: false
1190
+ };
1191
+ }
1192
+ return query.error ? { items: [], error: query.error, hasMore: query.hasMore } : {
1193
+ items: getQueryItems(query, (data, itemKey) => ({ data, itemKey })),
1194
+ error: null,
1195
+ hasMore: query.hasMore
1196
+ };
1197
+ }
1198
+ async function awaitItemFetch(itemPayload) {
1199
+ if (!fetchItemOrquestrator)
1200
+ throw new Error(noFetchFnError);
1201
+ const itemKey = getItemKey(itemPayload);
1202
+ const wasAborted = await fetchItemOrquestrator.get(itemKey).awaitFetch(itemPayload);
1203
+ if (wasAborted) {
1204
+ return { data: null, error: errorNormalizer(new Error("Aborted")) };
1205
+ }
1206
+ const item = store.state.items[itemKey];
1207
+ const itemQuery = store.state.itemQueries[itemKey];
1208
+ if (!itemQuery || !item) {
1209
+ return { data: null, error: errorNormalizer(new Error("Not found")) };
1210
+ }
1211
+ return itemQuery.error ? { data: null, error: itemQuery.error } : { data: item, error: null };
1212
+ }
1213
+ function getQueriesKeyArray(payloads) {
1214
+ if (Array.isArray(payloads)) {
1215
+ return payloads.map((payload) => ({
1216
+ key: getQueryKey(payload),
1217
+ payload
1218
+ }));
1219
+ } else if (typeof payloads === "function") {
1220
+ return filterAndMap(
1221
+ Object.entries(store.state.queries),
1222
+ ([queryKey, query], ignore2) => {
1223
+ return payloads(query.payload, query, queryKey) ? {
1224
+ key: queryKey,
1225
+ payload: query.payload
1226
+ } : ignore2;
1227
+ }
1228
+ );
1229
+ } else {
1230
+ return [{ key: getQueryKey(payloads), payload: payloads }];
1231
+ }
1232
+ }
1233
+ const storeEvents = mitt4();
1234
+ const queryInvalidationWasTriggered = /* @__PURE__ */ new Set();
1235
+ function invalidateQuery(queryPayload, priority = "highPriority", ignoreInvalidationSync = false) {
1236
+ const queriesKey = getQueriesKeyArray(queryPayload);
1237
+ for (const { key } of queriesKey) {
1238
+ store.produceState(
1239
+ (draft) => {
1240
+ const query = draft.queries[key];
1241
+ if (!query)
1242
+ return;
1243
+ query.refetchOnMount = priority;
1244
+ },
1245
+ { action: { type: "invalidate-data", key } }
1246
+ );
1247
+ queryInvalidationWasTriggered.delete(key);
1248
+ storeEvents.emit("invalidateQuery", { priority, queryKey: key });
1249
+ }
1250
+ if (syncMutationsAndInvalidations && !ignoreInvalidationSync) {
1251
+ invalidateItem(
1252
+ (itemPayload) => queriesKey.some(({ payload }) => {
1253
+ return syncMutationsAndInvalidations.syncItemAndQuery(
1254
+ itemPayload,
1255
+ payload
1256
+ );
1257
+ }),
1258
+ priority,
1259
+ true
1260
+ );
1261
+ invalidateQuery(
1262
+ (queryToInvalidatePayload, _, queryToInvalidateKey) => queriesKey.some((alreadyInvalidatedQueryPayload) => {
1263
+ return queryToInvalidateKey !== alreadyInvalidatedQueryPayload.key && syncMutationsAndInvalidations.syncQueries(
1264
+ alreadyInvalidatedQueryPayload.payload,
1265
+ queryToInvalidatePayload
1266
+ );
1267
+ }),
1268
+ priority,
1269
+ true
1270
+ );
1271
+ }
1272
+ }
1273
+ function defaultItemSelector(data, id) {
1274
+ return { id, data };
1275
+ }
1276
+ function useMultipleListQueries(queries, {
1277
+ itemSelector = defaultItemSelector,
1278
+ omitPayload,
1279
+ returnIdleStatus,
1280
+ returnRefetchingStatus,
1281
+ loadSize,
1282
+ disableRefetchOnMount = globalDisableRefetchOnMount
1283
+ } = {}) {
1284
+ const queriesWithId = useDeepMemo(() => {
1285
+ return queries.map((payload) => {
1286
+ return {
1287
+ key: getQueryKey(payload),
1288
+ payload
1289
+ };
1290
+ });
1291
+ }, [queries]);
1292
+ const dataSelector = useCallback3(itemSelector, []);
1293
+ const resultSelector = useCallback3(
1294
+ (state) => {
1295
+ return queriesWithId.map(
1296
+ ({
1297
+ key: queryKey,
1298
+ payload
1299
+ }) => {
1300
+ const query = state.queries[queryKey];
1301
+ if (!query) {
1302
+ return {
1303
+ queryKey,
1304
+ status: returnIdleStatus ? "idle" : "loading",
1305
+ items: [],
1306
+ error: null,
1307
+ hasMore: false,
1308
+ payload: omitPayload ? void 0 : payload,
1309
+ isLoading: returnIdleStatus ? false : true
1310
+ };
1311
+ }
1312
+ let status = query.status;
1313
+ if (!returnRefetchingStatus && query.status === "refetching") {
1314
+ status = "success";
1315
+ }
1316
+ return {
1317
+ queryKey,
1318
+ status,
1319
+ items: getQueryItems(query, dataSelector),
1320
+ error: query.error,
1321
+ hasMore: query.hasMore,
1322
+ isLoading: status === "loading",
1323
+ payload: omitPayload ? void 0 : query.payload
1324
+ };
1325
+ }
1326
+ );
1327
+ },
1328
+ [
1329
+ dataSelector,
1330
+ omitPayload,
1331
+ queriesWithId,
1332
+ returnIdleStatus,
1333
+ returnRefetchingStatus
1334
+ ]
1335
+ );
1336
+ const storeState = store.useSelector(resultSelector, {
1337
+ equalityFn: deepEqual4,
1338
+ useExternalDeps: true
1339
+ });
1340
+ useOnMittEvent(storeEvents, "invalidateQuery", (event) => {
1341
+ for (const { key, payload } of queriesWithId) {
1342
+ if (key !== event.queryKey)
1343
+ continue;
1344
+ if (!queryInvalidationWasTriggered.has(key)) {
1345
+ scheduleListQueryFetch(event.priority, payload);
1346
+ queryInvalidationWasTriggered.add(key);
1347
+ }
1348
+ }
1349
+ });
1350
+ const loadSizeConst = useConst(() => loadSize);
1351
+ useEffect4(() => {
1352
+ for (const { key: itemId, payload: fetchParams } of queriesWithId) {
1353
+ if (itemId) {
1354
+ if (disableRefetchOnMount) {
1355
+ const itemState = getQueryState(fetchParams);
1356
+ const shouldFetch = !itemState || !itemState.wasLoaded || itemState.refetchOnMount;
1357
+ if (shouldFetch) {
1358
+ scheduleListQueryFetch(
1359
+ itemState?.refetchOnMount || "lowPriority",
1360
+ fetchParams,
1361
+ loadSizeConst
1362
+ );
1363
+ return;
1364
+ }
1365
+ } else {
1366
+ scheduleListQueryFetch("lowPriority", fetchParams, loadSizeConst);
1367
+ }
1368
+ }
1369
+ }
1370
+ }, [disableRefetchOnMount, loadSizeConst, queriesWithId]);
1371
+ return storeState;
1372
+ }
1373
+ function useListQuery(payload, options = {}) {
1374
+ const { ensureIsLoaded } = options;
1375
+ const query = useMemo4(
1376
+ () => payload === false || payload === null || payload === void 0 ? [] : [payload],
1377
+ [payload]
1378
+ );
1379
+ const queryResult = useMultipleListQueries(query, options);
1380
+ const result = useMemo4(
1381
+ () => queryResult[0] ?? {
1382
+ payload: void 0,
1383
+ error: null,
1384
+ hasMore: false,
1385
+ isLoading: false,
1386
+ status: "idle",
1387
+ queryKey: "",
1388
+ items: []
1389
+ },
1390
+ [queryResult]
1391
+ );
1392
+ const [useModifyResult, emitIsLoadedEvt] = useEnsureIsLoaded(
1393
+ ensureIsLoaded,
1394
+ !!payload,
1395
+ () => {
1396
+ if (payload) {
1397
+ scheduleListQueryFetch("highPriority", payload);
1398
+ }
1399
+ }
1400
+ );
1401
+ useSubscribeToStore3(store, ({ observe }) => {
1402
+ if (!ensureIsLoaded)
1403
+ return;
1404
+ observe.ifSelector((state) => state.queries[result.queryKey]?.status).change.then(({ current }) => {
1405
+ if (current === "success" || current === "error") {
1406
+ emitIsLoadedEvt("isLoaded", true);
1407
+ }
1408
+ });
1409
+ });
1410
+ return useModifyResult(result);
1411
+ }
1412
+ async function fetchItem(fetchCtx, itemPayload) {
1413
+ if (!fetchItemOrquestrator) {
1414
+ throw new Error(noFetchFnError);
1415
+ }
1416
+ const itemKey = getCacheId(itemPayload);
1417
+ const isLoaded = !store.state.itemQueries[itemKey]?.wasLoaded;
1418
+ store.produceState(
1419
+ (draft) => {
1420
+ const itemQuery = draft.itemQueries[itemKey];
1421
+ if (!itemQuery) {
1422
+ draft.itemQueries[itemKey] = {
1423
+ status: "loading",
1424
+ error: null,
1425
+ wasLoaded: false,
1426
+ refetchOnMount: false,
1427
+ payload: klona2(itemPayload)
1428
+ };
1429
+ return;
1430
+ }
1431
+ itemQuery.status = itemQuery.wasLoaded ? "refetching" : "loading";
1432
+ itemQuery.error = null;
1433
+ itemQuery.refetchOnMount = false;
1434
+ },
1435
+ {
1436
+ equalityCheck: deepEqual4,
1437
+ action: {
1438
+ type: isLoaded ? "fetch-item-start" : "fetch-item-refetch-start",
1439
+ itemPayload
1440
+ }
1441
+ }
1442
+ );
1443
+ try {
1444
+ const item = await fetchItemFn(itemPayload);
1445
+ if (fetchCtx.shouldAbort())
1446
+ return false;
1447
+ store.produceState(
1448
+ (draft) => {
1449
+ const itemQuery = draft.itemQueries[itemKey];
1450
+ if (!itemQuery)
1451
+ return;
1452
+ itemQuery.status = "success";
1453
+ itemQuery.wasLoaded = true;
1454
+ draft.items[itemKey] = item;
1455
+ },
1456
+ {
1457
+ equalityCheck: deepEqual4,
1458
+ action: { type: "fetch-item-success", itemPayload }
1459
+ }
1460
+ );
1461
+ return true;
1462
+ } catch (exception) {
1463
+ if (fetchCtx.shouldAbort())
1464
+ return false;
1465
+ const error = errorNormalizer(exception);
1466
+ store.produceState(
1467
+ (draft) => {
1468
+ const itemQuery = draft.itemQueries[itemKey];
1469
+ if (!itemQuery)
1470
+ return;
1471
+ itemQuery.status = "error";
1472
+ itemQuery.error = error;
1473
+ },
1474
+ {
1475
+ action: { type: "fetch-item-error", itemPayload }
1476
+ }
1477
+ );
1478
+ return false;
1479
+ }
1480
+ }
1481
+ const fetchItemOrquestrator = fetchItemFn && createCollectionFetchOrquestrator({
1482
+ fetchFn: fetchItem,
1483
+ lowPriorityThrottleMs,
1484
+ dynamicRealtimeThrottleMs,
1485
+ mediumPriorityThrottleMs
1486
+ });
1487
+ function scheduleItemFetch(fetchType, itemPayload) {
1488
+ if (!fetchItemOrquestrator) {
1489
+ throw new Error(noFetchFnError);
1490
+ }
1491
+ const fetchMultiple = Array.isArray(itemPayload);
1492
+ const itemsId = fetchMultiple ? itemPayload : [itemPayload];
1493
+ const results = itemsId.map((payload) => {
1494
+ const itemKey = getCacheId(payload);
1495
+ return fetchItemOrquestrator.get(itemKey).scheduleFetch(fetchType, payload);
1496
+ });
1497
+ return fetchMultiple ? results : results[0];
1498
+ }
1499
+ function getItemsKeyArray(itemsPayload) {
1500
+ if (Array.isArray(itemsPayload)) {
1501
+ return itemsPayload.map((payload) => ({
1502
+ itemKey: getItemKey(payload),
1503
+ payload
1504
+ }));
1505
+ }
1506
+ if (typeof itemsPayload === "function") {
1507
+ return filterAndMap(
1508
+ Object.entries(store.state.items),
1509
+ ([itemKey, item], ignore2) => {
1510
+ const payload = store.state.itemQueries[itemKey]?.payload;
1511
+ if (item === null || !payload)
1512
+ return ignore2;
1513
+ return itemsPayload(payload, item) ? { itemKey, payload } : ignore2;
1514
+ }
1515
+ );
1516
+ }
1517
+ return [{ payload: itemsPayload, itemKey: getItemKey(itemsPayload) }];
1518
+ }
1519
+ const itemInvalidationWasTriggered = /* @__PURE__ */ new Set();
1520
+ function invalidateItem(itemId, priority = "highPriority", ignoreInvalidationSync = false) {
1521
+ if (!fetchItemOrquestrator) {
1522
+ throw new Error(noFetchFnError);
1523
+ }
1524
+ const itemsKey = getItemsKeyArray(itemId);
1525
+ for (const { itemKey } of itemsKey) {
1526
+ store.produceState(
1527
+ (draft) => {
1528
+ const query = draft.itemQueries[itemKey];
1529
+ if (!query)
1530
+ return;
1531
+ query.refetchOnMount = priority;
1532
+ },
1533
+ { action: { type: "invalidate-item", queryKey: itemKey } }
1534
+ );
1535
+ itemInvalidationWasTriggered.delete(itemKey);
1536
+ storeEvents.emit("invalidateItem", { priority, itemKey });
1537
+ }
1538
+ if (syncMutationsAndInvalidations && !ignoreInvalidationSync) {
1539
+ invalidateQuery(
1540
+ (query) => itemsKey.some(
1541
+ ({ payload }) => syncMutationsAndInvalidations.syncItemAndQuery(payload, query)
1542
+ ),
1543
+ priority,
1544
+ true
1545
+ );
1546
+ }
1547
+ }
1548
+ function startItemMutation(itemId) {
1549
+ if (!fetchItemOrquestrator)
1550
+ throw new Error(noFetchFnError);
1551
+ const itemsKey = getItemsKeyArray(itemId);
1552
+ const endMutations = [];
1553
+ for (const { itemKey, payload } of itemsKey) {
1554
+ endMutations.push(fetchItemOrquestrator.get(itemKey).startMutation());
1555
+ if (syncMutationsAndInvalidations) {
1556
+ for (const [queryKey, query] of Object.entries(store.state.queries)) {
1557
+ if (syncMutationsAndInvalidations.syncItemAndQuery(
1558
+ payload,
1559
+ query.payload
1560
+ )) {
1561
+ endMutations.push(
1562
+ fetchQueryOrquestrator.get(queryKey).startMutation()
1563
+ );
1564
+ }
1565
+ }
1566
+ }
1567
+ }
1568
+ return () => {
1569
+ for (const endMutation of endMutations) {
1570
+ endMutation();
1571
+ }
1572
+ };
1573
+ }
1574
+ function defaultItemDataSelector(data) {
1575
+ return data;
1576
+ }
1577
+ function useMultipleItems(itemsPayload_, {
1578
+ selector = defaultItemDataSelector,
1579
+ returnIdleStatus,
1580
+ returnRefetchingStatus,
1581
+ disableRefetchOnMount
1582
+ } = {}) {
1583
+ const dataSelector = useCallback3(selector, []);
1584
+ const memoizedItemKeys = useDeepMemo(
1585
+ () => itemsPayload_.map(
1586
+ (itemPayload) => ({
1587
+ payload: itemPayload,
1588
+ itemKey: getItemKey(itemPayload)
1589
+ })
1590
+ ),
1591
+ [itemsPayload_]
1592
+ );
1593
+ const resultSelector = useCallback3(
1594
+ (state) => {
1595
+ return memoizedItemKeys.map(
1596
+ ({
1597
+ itemKey,
1598
+ payload
1599
+ }) => {
1600
+ const itemQuery = state.itemQueries[itemKey];
1601
+ const itemState = state.items[itemKey];
1602
+ if (itemQuery === null) {
1603
+ return {
1604
+ status: "deleted",
1605
+ error: null,
1606
+ isLoading: false,
1607
+ payload,
1608
+ data: dataSelector(null, itemKey)
1609
+ };
1610
+ }
1611
+ if (!itemQuery) {
1612
+ return {
1613
+ status: returnIdleStatus ? "idle" : "loading",
1614
+ error: null,
1615
+ isLoading: returnIdleStatus ? false : true,
1616
+ payload,
1617
+ data: dataSelector(null, itemKey)
1618
+ };
1619
+ }
1620
+ let status = itemQuery.status;
1621
+ if (!returnRefetchingStatus && itemQuery.status === "refetching") {
1622
+ status = "success";
1623
+ }
1624
+ return {
1625
+ status,
1626
+ error: itemQuery.error,
1627
+ isLoading: status === "loading",
1628
+ data: dataSelector(itemState ?? null, itemKey),
1629
+ payload
1630
+ };
1631
+ }
1632
+ );
1633
+ },
1634
+ [
1635
+ dataSelector,
1636
+ memoizedItemKeys,
1637
+ returnIdleStatus,
1638
+ returnRefetchingStatus
1639
+ ]
1640
+ );
1641
+ const storeState = store.useSelector(resultSelector, {
1642
+ equalityFn: deepEqual4,
1643
+ useExternalDeps: true
1644
+ });
1645
+ useOnMittEvent(storeEvents, "invalidateItem", (event) => {
1646
+ for (const { payload, itemKey } of memoizedItemKeys) {
1647
+ if (itemKey !== event.itemKey)
1648
+ continue;
1649
+ if (!itemInvalidationWasTriggered.has(itemKey)) {
1650
+ scheduleItemFetch(event.priority, payload);
1651
+ itemInvalidationWasTriggered.add(itemKey);
1652
+ }
1653
+ }
1654
+ });
1655
+ useEffect4(() => {
1656
+ for (const { payload, itemKey } of memoizedItemKeys) {
1657
+ if (itemKey) {
1658
+ if (disableRefetchOnMount) {
1659
+ const itemState = store.state.itemQueries[itemKey];
1660
+ const shouldFetch = !itemState || !itemState.wasLoaded || itemState.refetchOnMount;
1661
+ if (shouldFetch) {
1662
+ scheduleItemFetch(
1663
+ itemState?.refetchOnMount || "lowPriority",
1664
+ payload
1665
+ );
1666
+ return;
1667
+ }
1668
+ } else {
1669
+ scheduleItemFetch("lowPriority", payload);
1670
+ }
1671
+ }
1672
+ }
1673
+ }, [disableRefetchOnMount, memoizedItemKeys]);
1674
+ return storeState;
1675
+ }
1676
+ function useItem(itemPayload, options = {}) {
1677
+ const { ensureIsLoaded } = options;
1678
+ const query = useMemo4(
1679
+ () => itemPayload === false || itemPayload === null || itemPayload === void 0 ? [] : [itemPayload],
1680
+ [itemPayload]
1681
+ );
1682
+ const queryResult = useMultipleItems(query, options);
1683
+ const memoizedSelector = useCallback3(
1684
+ options.selector ?? defaultItemDataSelector,
1685
+ []
1686
+ );
1687
+ const result = useMemo4(
1688
+ () => queryResult[0] ?? {
1689
+ error: null,
1690
+ isLoading: false,
1691
+ status: "idle",
1692
+ data: memoizedSelector(null, ""),
1693
+ payload: itemPayload || null
1694
+ },
1695
+ [itemPayload, memoizedSelector, queryResult]
1696
+ );
1697
+ const [useModifyResult, emitIsLoadedEvt] = useEnsureIsLoaded(
1698
+ ensureIsLoaded,
1699
+ !!itemPayload,
1700
+ () => {
1701
+ if (itemPayload) {
1702
+ scheduleItemFetch("highPriority", itemPayload);
1703
+ }
1704
+ }
1705
+ );
1706
+ useSubscribeToStore3(store, ({ observe }) => {
1707
+ if (!ensureIsLoaded || !itemPayload)
1708
+ return;
1709
+ observe.ifSelector((state) => state.itemQueries[itemPayload]?.status).change.then(({ current }) => {
1710
+ if (current === "success" || current === "error") {
1711
+ emitIsLoadedEvt("isLoaded", true);
1712
+ }
1713
+ });
1714
+ });
1715
+ return useModifyResult(result);
1716
+ }
1717
+ function updateItemState(itemIds, produceNewData, ifNothingWasUpdated) {
1718
+ const itemKeys = getItemsKeyArray(itemIds);
1719
+ let someItemWasUpdated = false;
1720
+ store.batch(
1721
+ () => {
1722
+ store.produceState((draftState) => {
1723
+ for (const { itemKey, payload } of itemKeys) {
1724
+ const item = draftState.items[itemKey];
1725
+ if (!item)
1726
+ continue;
1727
+ someItemWasUpdated = true;
1728
+ const newData = produceNewData(item, payload);
1729
+ if (newData) {
1730
+ draftState.items[itemKey] = newData;
1731
+ }
1732
+ }
1733
+ });
1734
+ if (ifNothingWasUpdated && !someItemWasUpdated) {
1735
+ ifNothingWasUpdated();
1736
+ }
1737
+ },
1738
+ { type: "update-item-state", item: itemKeys }
1739
+ );
1740
+ return someItemWasUpdated;
1741
+ }
1742
+ function addItemToState(itemPayload, data) {
1743
+ const itemKey = getItemKey(itemPayload);
1744
+ store.produceState(
1745
+ (draftState) => {
1746
+ draftState.items[itemKey] = data;
1747
+ draftState.itemQueries[itemKey] = {
1748
+ status: "success",
1749
+ wasLoaded: true,
1750
+ refetchOnMount: false,
1751
+ error: null,
1752
+ payload: klona2(itemPayload)
1753
+ };
1754
+ },
1755
+ { action: { type: "create-item-state", itemPayload } }
1756
+ );
1757
+ }
1758
+ function deleteItemState(itemId) {
1759
+ const itemsId = getItemsKeyArray(itemId);
1760
+ store.produceState(
1761
+ (draftState) => {
1762
+ for (const { itemKey } of itemsId) {
1763
+ draftState.items[itemKey] = null;
1764
+ draftState.itemQueries[itemKey] = null;
1765
+ for (const query of Object.values(draftState.queries)) {
1766
+ if (query.items.includes(itemKey)) {
1767
+ query.items = query.items.filter((i) => i !== itemKey);
1768
+ }
1769
+ }
1770
+ }
1771
+ },
1772
+ { action: { type: "delete-item-state", itemId } }
1773
+ );
1774
+ }
1775
+ if (!disableRefetchOnWindowFocus) {
1776
+ let handleFocus2 = function() {
1777
+ invalidateQuery(() => true, "lowPriority");
1778
+ invalidateItem(() => true, "lowPriority");
1779
+ };
1780
+ var handleFocus = handleFocus2;
1781
+ window.addEventListener("focus", handleFocus2);
1782
+ window.addEventListener("visibilitychange", handleFocus2);
1783
+ }
1784
+ return {
1785
+ store,
1786
+ scheduleListQueryFetch,
1787
+ getQueryState,
1788
+ getQueryKey,
1789
+ deleteItemState,
1790
+ getItemState,
1791
+ loadMore,
1792
+ invalidateQuery,
1793
+ invalidateItem,
1794
+ scheduleItemFetch,
1795
+ awaitItemFetch,
1796
+ awaitListQueryFetch,
1797
+ useMultipleListQueries,
1798
+ useListQuery,
1799
+ getItemKey,
1800
+ useItem,
1801
+ useMultipleItems,
1802
+ addItemToState,
1803
+ updateItemState,
1804
+ startItemMutation
1805
+ };
1806
+ }
1807
+ export {
1808
+ newTSDFCollectionStore,
1809
+ newTSDFDocumentStore,
1810
+ newTSDFListQueryStore
1811
+ };