reactjrx 1.35.0 → 1.40.1

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 (48) hide show
  1. package/dist/index.cjs +987 -269
  2. package/dist/index.d.ts +4 -4
  3. package/dist/index.js +989 -271
  4. package/dist/lib/logger.d.ts +48 -0
  5. package/dist/lib/queries/client/cache/cacheClient.d.ts +12 -0
  6. package/dist/lib/queries/client/cache/invalidateCache.d.ts +5 -0
  7. package/dist/lib/queries/client/cache/logger.d.ts +24 -0
  8. package/dist/lib/queries/client/cache/registerResultInCache.d.ts +8 -0
  9. package/dist/lib/queries/client/createClient.d.ts +69 -17
  10. package/dist/lib/queries/client/deduplication/deduplicate.d.ts +3 -0
  11. package/dist/lib/queries/client/fetch/notifyQueryResult.d.ts +3 -0
  12. package/dist/lib/queries/client/fetch/queryFetch.d.ts +12 -0
  13. package/dist/lib/queries/client/invalidation/invalidationClient.d.ts +12 -0
  14. package/dist/lib/queries/client/invalidation/logger.d.ts +24 -0
  15. package/dist/lib/queries/client/invalidation/markAsStale.d.ts +8 -0
  16. package/dist/lib/queries/client/keys/compareKeys.d.ts +4 -0
  17. package/dist/lib/queries/client/keys/serializeKey.d.ts +3 -0
  18. package/dist/lib/queries/client/keys/types.d.ts +10 -0
  19. package/dist/lib/queries/client/operators.d.ts +2 -3
  20. package/dist/lib/queries/client/refetch/client.d.ts +18 -0
  21. package/dist/lib/queries/client/store/createQueryStore.d.ts +55 -0
  22. package/dist/lib/queries/client/store/debugger.d.ts +3 -0
  23. package/dist/lib/queries/client/store/garbageCache.d.ts +5 -0
  24. package/dist/lib/queries/client/store/initializeQueryInStore.d.ts +8 -0
  25. package/dist/lib/queries/client/store/mapStoreQueryToRunnerOptions.d.ts +4 -0
  26. package/dist/lib/queries/client/store/queryListener.d.ts +3 -0
  27. package/dist/lib/queries/client/store/updateStoreWithQuery.d.ts +14 -0
  28. package/dist/lib/queries/client/triggers.d.ts +17 -0
  29. package/dist/lib/queries/client/types.d.ts +42 -1
  30. package/dist/lib/queries/{Provider.d.ts → react/Provider.d.ts} +2 -15
  31. package/dist/lib/queries/react/helpers.d.ts +27 -0
  32. package/dist/lib/queries/react/triggers/activityTrigger.d.ts +9 -0
  33. package/dist/lib/queries/react/triggers/networkTrigger.d.ts +7 -0
  34. package/dist/lib/queries/react/types.d.ts +13 -0
  35. package/dist/lib/queries/react/useQuery.d.ts +6 -0
  36. package/dist/lib/utils/difference.d.ts +1 -0
  37. package/package.json +1 -1
  38. package/dist/lib/queries/cache/useCreateCacheStore.d.ts +0 -9
  39. package/dist/lib/queries/deduplication/deduplicate.d.ts +0 -3
  40. package/dist/lib/queries/deduplication/useQueryStore.d.ts +0 -3
  41. package/dist/lib/queries/invalidation/autoRefetch.d.ts +0 -4
  42. package/dist/lib/queries/keys/serializeKey.d.ts +0 -1
  43. package/dist/lib/queries/operators.d.ts +0 -2
  44. package/dist/lib/queries/querx.d.ts +0 -3
  45. package/dist/lib/queries/types.d.ts +0 -10
  46. package/dist/lib/queries/useQuery.d.ts +0 -12
  47. /package/dist/lib/queries/{useAsyncQuery.d.ts → react/useAsyncQuery.d.ts} +0 -0
  48. /package/dist/lib/queries/{useSubscribeEffect.d.ts → react/useSubscribeEffect.d.ts} +0 -0
package/dist/index.cjs CHANGED
@@ -242,7 +242,6 @@ const PersistSignals = react.memo(
242
242
  ).pipe(rxjs.map(() => true));
243
243
  return stream.pipe(
244
244
  rxjs.tap(() => {
245
- console.log("hydration complete");
246
245
  if (onReadyRef.current != null)
247
246
  onReadyRef.current();
248
247
  }),
@@ -411,15 +410,6 @@ function retryBackoff(config) {
411
410
  );
412
411
  });
413
412
  }
414
- const retryFromOptions = (options) => retryBackoff({
415
- initialInterval: 100,
416
- ...typeof options.retry === "function" ? {
417
- shouldRetry: options.retry
418
- } : {
419
- maxRetries: options.retry === false ? 0 : options.retry ?? 3
420
- }
421
- });
422
- const querx = (options) => (source) => source.pipe(retryFromOptions(options));
423
413
  const useBehaviorSubject = (state) => {
424
414
  const subject = useConstant(() => new rxjs.BehaviorSubject(state));
425
415
  const completed = react.useRef(false);
@@ -459,6 +449,31 @@ function shallowEqual(objA, objB) {
459
449
  }
460
450
  return true;
461
451
  }
452
+ const retryOnError = (options) => retryBackoff({
453
+ initialInterval: 100,
454
+ ...typeof options.retry === "function" ? {
455
+ shouldRetry: options.retry
456
+ } : {
457
+ maxRetries: options.retry === false ? 0 : options.retry ?? 3
458
+ }
459
+ });
460
+ const mergeResults = (stream$) => stream$.pipe(
461
+ rxjs.scan(
462
+ (acc, current) => {
463
+ return {
464
+ ...acc,
465
+ ...current
466
+ };
467
+ },
468
+ {
469
+ data: void 0,
470
+ error: void 0,
471
+ fetchStatus: "idle",
472
+ status: "loading"
473
+ }
474
+ ),
475
+ rxjs.distinctUntilChanged(shallowEqual)
476
+ );
462
477
  function useAsyncQuery(query, mapOperatorOrOptions, options = {}) {
463
478
  const queryRef = useLiveRef(query);
464
479
  const triggerSubject = useSubject();
@@ -505,7 +520,7 @@ function useAsyncQuery(query, mapOperatorOrOptions, options = {}) {
505
520
  }),
506
521
  rxjs.combineLatest([
507
522
  rxjs.defer(() => rxjs.from(queryRef.current(args))).pipe(
508
- querx(optionsRef.current),
523
+ retryOnError(optionsRef.current),
509
524
  rxjs.first(),
510
525
  rxjs.map((data) => ({ data, isError: false })),
511
526
  rxjs.catchError((error) => {
@@ -519,7 +534,6 @@ function useAsyncQuery(query, mapOperatorOrOptions, options = {}) {
519
534
  isLastMutationCalled
520
535
  ]).pipe(
521
536
  rxjs.map(([{ data, isError }, isLastMutationCalled2]) => {
522
- console.log("success", { data, isLastMutationCalled: isLastMutationCalled2 });
523
537
  if (!isError) {
524
538
  if (optionsRef.current.onSuccess != null)
525
539
  optionsRef.current.onSuccess(data, args);
@@ -580,217 +594,15 @@ function useAsyncQuery(query, mapOperatorOrOptions, options = {}) {
580
594
  }, []);
581
595
  return { ...result, isLoading: result.status === "loading", mutate, reset };
582
596
  }
583
- const useCreateCacheStore = () => {
584
- const cacheStore = useBehaviorSubject({});
585
- useSubscribe(
586
- () => cacheStore.current.pipe(
587
- rxjs.skip(1),
588
- rxjs.tap(() => {
589
- const store = cacheStore.current.getValue();
590
- console.log(
591
- "[cache] update",
592
- Object.keys(store).reduce((acc, key) => {
593
- const entry = store[key];
594
- if (entry != null) {
595
- acc[key] = entry;
596
- }
597
- acc[key]._debug = {
598
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
599
- // @ts-expect-error
600
- eol: new Date(store[key].date + store[key].ttl)
601
- };
602
- return acc;
603
- }, {})
604
- );
605
- })
606
- ),
607
- [cacheStore]
608
- );
609
- useSubscribe(
610
- () => rxjs.interval(1e3).pipe(
611
- rxjs.withLatestFrom(cacheStore.current),
612
- rxjs.tap(() => {
613
- const now = (/* @__PURE__ */ new Date()).getTime();
614
- const store = cacheStore.current.getValue();
615
- const keys = Object.keys(store);
616
- const validKeys = keys.filter((key) => {
617
- const value = store[key];
618
- if (value != null && value.date + value.ttl > now) {
619
- return true;
620
- }
621
- return false;
622
- });
623
- if (validKeys.length === keys.length) {
624
- return;
625
- }
626
- const newStore = validKeys.reduce((acc, key) => {
627
- const entry = store[key];
628
- if (entry != null) {
629
- acc[key] = entry;
630
- }
631
- return acc;
632
- }, {});
633
- cacheStore.current.next(newStore);
634
- })
635
- ),
636
- [cacheStore]
637
- );
638
- return cacheStore;
639
- };
640
- const useQueryStore = () => {
641
- const [store] = react.useState(/* @__PURE__ */ new Map());
642
- return store;
643
- };
644
- const DEFAULT_STALE = 9999;
645
- const autoRefetch = (options$ = rxjs.of({})) => (source) => {
646
- return source.pipe(
647
- rxjs.repeat({
648
- delay: () => options$.pipe(
649
- rxjs.switchMap(
650
- (options) => options.staleTime === Infinity ? rxjs.EMPTY : rxjs.timer(options.staleTime ?? DEFAULT_STALE)
651
- )
652
- )
653
- })
654
- );
655
- };
656
- const deduplicate = (key, queryStore) => (source) => {
657
- if (!key)
658
- return source;
659
- const sourceFromStore = queryStore == null ? void 0 : queryStore.get(key);
660
- const finalSource = sourceFromStore ?? source.pipe(
661
- rxjs.finalize(() => {
662
- queryStore == null ? void 0 : queryStore.delete(key);
663
- }),
664
- rxjs.shareReplay({
665
- refCount: true,
666
- bufferSize: 1
667
- })
668
- );
669
- if (sourceFromStore == null) {
670
- queryStore == null ? void 0 : queryStore.set(key, finalSource);
671
- }
672
- return finalSource;
673
- };
674
- const serializeKey = (key) => {
675
- if (key.length === 0)
676
- return "";
677
- return JSON.stringify(key);
678
- };
679
- const notifyQueryResult = (options$) => (stream$) => stream$.pipe(
680
- rxjs.withLatestFrom(options$),
681
- rxjs.map(([result, options]) => {
682
- var _a, _b;
683
- if (result.error) {
684
- (_a = options.onError) == null ? void 0 : _a.call(options, result.error);
685
- } else {
686
- (_b = options.onSuccess) == null ? void 0 : _b.call(options, result);
687
- }
688
- return result;
689
- })
690
- );
691
- const mergeResults = (stream$) => stream$.pipe(
692
- rxjs.startWith({ isLoading: false, data: void 0, error: void 0 }),
693
- rxjs.pairwise(),
694
- rxjs.map(([previous, current]) => ({
695
- isLoading: false,
696
- data: void 0,
697
- error: void 0,
698
- ...previous,
699
- ...current
700
- })),
701
- rxjs.distinctUntilChanged(shallowEqual)
702
- );
703
- const createClient = () => {
704
- const queryStore = /* @__PURE__ */ new Map();
705
- const refetch$ = new rxjs.Subject();
706
- const query$ = ({
707
- key,
708
- fn$,
709
- options$
710
- }) => {
711
- const refetch$2 = new rxjs.Subject();
712
- const enabled$ = options$.pipe(rxjs.map(({ enabled = true }) => enabled));
713
- const disabled$ = enabled$.pipe(
714
- rxjs.distinctUntilChanged(),
715
- rxjs.filter((enabled) => !enabled)
716
- );
717
- const triggers = [
718
- refetch$2.pipe(rxjs.startWith(null)),
719
- enabled$.pipe(
720
- rxjs.distinctUntilChanged(),
721
- rxjs.filter((enabled) => enabled)
722
- )
723
- ];
724
- const serializedKey = serializeKey(key);
725
- const query$2 = rxjs.combineLatest(triggers).pipe(
726
- rxjs.tap((params) => {
727
- console.log("query$ trigger", { key, params });
728
- }),
729
- rxjs.withLatestFrom(fn$),
730
- rxjs.switchMap(([, query]) => {
731
- const deferredQuery = rxjs.defer(() => {
732
- const queryOrResponse = typeof query === "function" ? query() : query;
733
- return rxjs.from(queryOrResponse);
734
- });
735
- return rxjs.merge(
736
- disabled$.pipe(
737
- rxjs.take(1),
738
- rxjs.map(() => ({
739
- isLoading: false
740
- }))
741
- ),
742
- rxjs.merge(
743
- rxjs.of({ isLoading: true, error: void 0 }),
744
- deferredQuery.pipe(
745
- deduplicate(serializedKey, queryStore),
746
- rxjs.map((result) => ({
747
- isLoading: false,
748
- data: { result },
749
- error: void 0
750
- })),
751
- rxjs.catchError(
752
- (error) => rxjs.of({
753
- isLoading: false,
754
- data: void 0,
755
- error
756
- })
757
- ),
758
- notifyQueryResult(options$)
759
- )
760
- ).pipe(autoRefetch(options$), rxjs.takeUntil(disabled$))
761
- );
762
- }),
763
- mergeResults,
764
- rxjs.tap((data) => {
765
- console.log("query$ return", data);
766
- })
767
- );
768
- return {
769
- query$: query$2,
770
- refetch$: refetch$2,
771
- enabled$
772
- };
773
- };
774
- return {
775
- query$,
776
- refetch$,
777
- queryStore,
778
- destroy: () => {
779
- }
780
- };
781
- };
782
597
  const Context = react.createContext({
783
- cacheStore: {},
784
- client: createClient()
598
+ client: null
785
599
  });
786
600
  const Provider = react.memo(
787
601
  ({
788
602
  children,
789
603
  client
790
604
  }) => {
791
- const cacheStore = useCreateCacheStore();
792
- const queryStore = useQueryStore();
793
- const value = react.useMemo(() => ({ cacheStore, queryStore, client }), [client]);
605
+ const value = react.useMemo(() => ({ client }), [client]);
794
606
  react.useEffect(
795
607
  () => () => {
796
608
  client.destroy();
@@ -800,91 +612,137 @@ const Provider = react.memo(
800
612
  return /* @__PURE__ */ jsxRuntime.jsx(Context.Provider, { value, children });
801
613
  }
802
614
  );
803
- const useProvider = () => {
615
+ const useReactJrxProvider = () => {
804
616
  const context = react.useContext(Context);
617
+ if (context === null) {
618
+ throw new Error("You forgot to register the provider");
619
+ }
805
620
  return { ...context };
806
621
  };
807
622
  const arrayEqual = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);
808
623
  function isDefined(arg) {
809
624
  return arg !== null && arg !== void 0;
810
625
  }
811
- const defaultValue = { data: void 0, isLoading: true, error: void 0 };
812
- function useQuery(keyOrQuery, queryOrOptionOrNothing, optionsOrNothing) {
813
- const query = Array.isArray(keyOrQuery) ? queryOrOptionOrNothing : keyOrQuery;
814
- const options = optionsOrNothing ?? (queryOrOptionOrNothing !== query ? queryOrOptionOrNothing : void 0) ?? {};
815
- const internalRefresh$ = useSubject();
816
- const { client } = useProvider();
817
- const key = Array.isArray(keyOrQuery) ? keyOrQuery : void 0;
818
- const params$ = useBehaviorSubject({ key, options, query });
626
+ const createActivityTrigger = (params$) => {
627
+ return params$.pipe(
628
+ rxjs.switchMap(({ options: { refetchOnWindowFocus = true } }) => {
629
+ const shouldRunTrigger = typeof refetchOnWindowFocus === "function" ? refetchOnWindowFocus({}) : refetchOnWindowFocus;
630
+ return shouldRunTrigger !== false ? rxjs.merge(
631
+ rxjs.fromEvent(document, "visibilitychange").pipe(
632
+ rxjs.filter(() => !document.hidden),
633
+ rxjs.map(() => ({ ignoreStale: shouldRunTrigger === "always" }))
634
+ ),
635
+ rxjs.fromEvent(window, "focus").pipe(
636
+ rxjs.map(() => ({ ignoreStale: shouldRunTrigger === "always" }))
637
+ )
638
+ ) : rxjs.EMPTY;
639
+ })
640
+ );
641
+ };
642
+ const createNetworkTrigger = (params$) => {
643
+ return params$.pipe(
644
+ rxjs.switchMap(({ options: { refetchOnReconnect = true } }) => {
645
+ const shouldRunTrigger = typeof refetchOnReconnect === "function" ? refetchOnReconnect({}) : refetchOnReconnect;
646
+ return shouldRunTrigger !== false ? rxjs.fromEvent(window, "online").pipe(
647
+ rxjs.map(() => ({ ignoreStale: shouldRunTrigger === "always" }))
648
+ ) : rxjs.EMPTY;
649
+ })
650
+ );
651
+ };
652
+ const useQueryParams = ({
653
+ queryKey,
654
+ queryFn,
655
+ ...options
656
+ }) => {
657
+ const params$ = useBehaviorSubject({ queryKey, options, queryFn });
819
658
  react.useEffect(() => {
820
659
  params$.current.next({
821
- key,
660
+ queryKey,
822
661
  options,
823
- query
662
+ queryFn
824
663
  });
825
- }, [key, options, query]);
664
+ }, [queryKey, options, queryFn]);
665
+ return params$;
666
+ };
667
+ const defaultValue = {
668
+ data: void 0,
669
+ isLoading: true,
670
+ error: void 0,
671
+ status: "loading",
672
+ fetchStatus: "idle"
673
+ };
674
+ function useQuery({
675
+ queryKey,
676
+ queryFn,
677
+ ...options
678
+ }) {
679
+ const internalRefresh$ = useSubject();
680
+ const { client } = useReactJrxProvider();
681
+ const params$ = useQueryParams({ queryFn, queryKey, ...options });
826
682
  const result = useObserve(
827
683
  () => {
828
- const computedDefaultValue = {
829
- ...defaultValue,
830
- isLoading: params$.current.getValue().options.enabled !== false
831
- };
832
- const newKeyReceived$ = params$.current.pipe(
833
- rxjs.map(({ key: key2 }) => key2 ?? []),
834
- rxjs.distinctUntilChanged(arrayEqual)
684
+ const key$ = params$.current.pipe(rxjs.map(({ queryKey: queryKey2 }) => queryKey2 ?? []));
685
+ const initialTrigger$ = rxjs.of(null);
686
+ const newKeyTrigger$ = key$.pipe(
687
+ rxjs.distinctUntilChanged(arrayEqual),
688
+ rxjs.skip(1)
835
689
  );
690
+ const isQueryObject = (query) => !!query && typeof query !== "function";
836
691
  const newObservableObjectQuery$ = params$.current.pipe(
837
- rxjs.map(({ query: query2 }) => query2),
692
+ rxjs.map(({ queryFn: queryFn2 }) => queryFn2),
693
+ rxjs.filter(isQueryObject),
838
694
  rxjs.distinctUntilChanged(shallowEqual),
839
- rxjs.skip(1),
840
- rxjs.filter((query2) => !!query2 && typeof query2 !== "function"),
841
- rxjs.startWith(params$.current.getValue().query),
842
- rxjs.filter(isDefined)
695
+ isQueryObject(params$.current.getValue().queryFn) ? rxjs.skip(1) : rxjs.identity
843
696
  );
844
697
  const fn$ = params$.current.pipe(
845
- rxjs.map(({ query: query2 }) => query2),
698
+ rxjs.map(({ queryFn: queryFn2 }) => queryFn2),
846
699
  rxjs.filter(isDefined)
847
700
  );
848
701
  const options$ = params$.current.pipe(rxjs.map(({ options: options2 }) => options2));
849
- const triggers$ = rxjs.combineLatest([
850
- newKeyReceived$,
702
+ const activityRefetch$ = createActivityTrigger(params$.current);
703
+ const networkRefetch$ = createNetworkTrigger(params$.current);
704
+ const newQueryTrigger$ = rxjs.merge(
705
+ initialTrigger$,
706
+ newKeyTrigger$,
851
707
  newObservableObjectQuery$
852
- ]);
853
- return triggers$.pipe(
854
- rxjs.switchMap(([key2]) => {
855
- const { query$, refetch$ } = client.query$({
856
- key: key2,
708
+ );
709
+ const refetch$ = rxjs.merge(
710
+ internalRefresh$.current.pipe(rxjs.map(() => ({ ignoreStale: true }))),
711
+ rxjs.merge(activityRefetch$, networkRefetch$).pipe(rxjs.throttleTime(500))
712
+ );
713
+ return newQueryTrigger$.pipe(
714
+ rxjs.withLatestFrom(key$),
715
+ rxjs.switchMap(([, key]) => {
716
+ const { result$ } = client.query$({
717
+ key,
857
718
  fn$,
858
- options$
719
+ options$,
720
+ refetch$
859
721
  });
860
- const subscriptions = [internalRefresh$.current.subscribe(refetch$)];
861
- return query$.pipe(
862
- rxjs.finalize(() => {
863
- subscriptions.forEach((sub) => {
864
- sub.unsubscribe();
865
- });
866
- }),
867
- rxjs.startWith(computedDefaultValue),
868
- rxjs.pairwise(),
869
- rxjs.map(
870
- ([
871
- { data: previousData, ...restPrevious },
872
- { data: currentData, ...restCurrent }
873
- ]) => ({
874
- ...restPrevious,
875
- ...restCurrent,
876
- data: currentData && "result" in currentData ? currentData.result : previousData == null ? void 0 : previousData.result
877
- })
722
+ return result$.pipe(
723
+ rxjs.scan(
724
+ (previousValue, { data: currentData, ...currentValue }) => ({
725
+ data: void 0,
726
+ ...previousValue,
727
+ ...currentValue,
728
+ isLoading: currentValue.status === "loading",
729
+ ...currentData && {
730
+ data: currentData.result
731
+ }
732
+ }),
733
+ {}
878
734
  )
879
735
  );
880
- }),
736
+ })
881
737
  /**
882
738
  * @important
883
739
  * We skip the first result as it is comparable to default passed value.
884
740
  * This is assuming all query are async and does not return a result right away.
885
741
  * This is a design choice.
886
742
  */
887
- params$.current.getValue().options.enabled !== false ? rxjs.skip(1) : rxjs.identity
743
+ // params$.current.getValue().options.enabled !== false
744
+ // ? skip(1)
745
+ // : identity
888
746
  );
889
747
  },
890
748
  {
@@ -920,6 +778,865 @@ function useSubscribeEffect(source, unsafeOptions, deps = []) {
920
778
  );
921
779
  useSubscribe(enhancerMakeObservable, deps);
922
780
  }
781
+ const serializeObject = (object) => {
782
+ if (Array.isArray(object)) {
783
+ return object.reduce((acc, value, index) => {
784
+ if (index === object.length - 1)
785
+ return `${acc}${serializeObject(value)}]`;
786
+ return `${acc}${serializeObject(value)},`;
787
+ }, "[");
788
+ }
789
+ if (object === void 0)
790
+ return "";
791
+ return JSON.stringify(object, Object.keys(object).sort());
792
+ };
793
+ const serializeKey = (key) => {
794
+ if (key.length === 0)
795
+ return "[]";
796
+ return serializeObject(key);
797
+ };
798
+ const resetStyle = { backgroundColor: "transparent", color: "inherit" };
799
+ function createLogger(env) {
800
+ const _logger = {
801
+ namespaces: [
802
+ { name: "@reactjrx", style: { backgroundColor: "#d02f4e", color: "white" } }
803
+ ],
804
+ namespace(name, style) {
805
+ const logger2 = createLogger(env);
806
+ logger2.namespaces.push({
807
+ name,
808
+ style: style ?? resetStyle
809
+ });
810
+ return logger2;
811
+ },
812
+ printNamespaces() {
813
+ return {
814
+ namespaces: _logger.namespaces.map(({ name }) => `%c ${name} %c`).join(" "),
815
+ styles: _logger.namespaces.reduce((acc, { style }) => {
816
+ acc.push(
817
+ `background-color: ${style.backgroundColor}; color: ${style.color};`
818
+ );
819
+ acc.push("background-color: transparent; color: inherit;");
820
+ return acc;
821
+ }, [])
822
+ };
823
+ },
824
+ print(method, ...message) {
825
+ if (env === "development") {
826
+ const { namespaces, styles } = _logger.printNamespaces();
827
+ console[method](namespaces, ...styles, ...message);
828
+ }
829
+ return _logger;
830
+ },
831
+ printWithoutNamespace(method, ...message) {
832
+ if (env === "development") {
833
+ console[method](...message);
834
+ }
835
+ return _logger;
836
+ },
837
+ log(...message) {
838
+ return _logger.print("log", ...message);
839
+ },
840
+ warn(...message) {
841
+ return _logger.print("warn", ...message);
842
+ },
843
+ error(...message) {
844
+ return _logger.print("error", ...message);
845
+ },
846
+ group(...message) {
847
+ return _logger.print("group", ...message);
848
+ },
849
+ groupEnd() {
850
+ if (env === "development") {
851
+ console.groupEnd();
852
+ }
853
+ return _logger;
854
+ }
855
+ };
856
+ return _logger;
857
+ }
858
+ const Logger = createLogger("development");
859
+ const logger$3 = Logger.namespace("store");
860
+ const createDebugger = (store$) => {
861
+ return store$.pipe(
862
+ rxjs.map(
863
+ (value) => [...value.keys()].reduce((acc, key) => {
864
+ var _a;
865
+ acc[key] = (_a = value.get(key)) == null ? void 0 : _a.getValue();
866
+ return acc;
867
+ }, {})
868
+ ),
869
+ rxjs.distinctUntilChanged(shallowEqual)
870
+ ).subscribe((value) => {
871
+ logger$3.log("store", "update", value);
872
+ });
873
+ };
874
+ const createQueryStore = () => {
875
+ const store = /* @__PURE__ */ new Map();
876
+ const store$ = new rxjs.BehaviorSubject(store);
877
+ const queryEventSubject = new rxjs.Subject();
878
+ const queryTriggerSubject = new rxjs.Subject();
879
+ const notify = () => {
880
+ store$.next(store);
881
+ };
882
+ const setValue = (key, value) => {
883
+ store.set(key, new rxjs.BehaviorSubject(value));
884
+ notify();
885
+ };
886
+ const getValue = (serializedKey) => {
887
+ var _a;
888
+ return (_a = store.get(serializedKey)) == null ? void 0 : _a.getValue();
889
+ };
890
+ const getValue$ = (key) => {
891
+ return store$.pipe(
892
+ rxjs.map(() => store.get(key)),
893
+ rxjs.filter(isDefined),
894
+ rxjs.map((entry) => entry.getValue()),
895
+ rxjs.distinctUntilChanged(shallowEqual)
896
+ );
897
+ };
898
+ const updateValue = (key, value) => {
899
+ const existingObject = store.get(key);
900
+ if (!existingObject)
901
+ return;
902
+ if (typeof value === "function") {
903
+ existingObject.next({
904
+ ...existingObject.getValue(),
905
+ ...value(existingObject.getValue())
906
+ });
907
+ } else {
908
+ existingObject.next({ ...existingObject.getValue(), ...value });
909
+ }
910
+ store$.next(store);
911
+ };
912
+ const updateMany = (value, predicate = () => true) => {
913
+ store.forEach((oldValue$) => {
914
+ const oldValue = oldValue$.getValue();
915
+ if (predicate(oldValue)) {
916
+ oldValue$.next({ ...oldValue, ...value });
917
+ }
918
+ });
919
+ store$.next(store);
920
+ };
921
+ const deleteValue = (key) => {
922
+ store.delete(key);
923
+ store$.next(store);
924
+ };
925
+ const addRunner = (key, stream) => {
926
+ updateValue(key, (old) => ({
927
+ ...old,
928
+ runners: [...old.runners, stream]
929
+ }));
930
+ return () => {
931
+ var _a;
932
+ const newListeners = ((_a = store.get(key)) == null ? void 0 : _a.getValue().runners.filter((reference) => reference !== stream)) ?? [];
933
+ updateValue(key, (old) => ({
934
+ ...old,
935
+ runners: newListeners
936
+ }));
937
+ };
938
+ };
939
+ const debugger$ = createDebugger(store$);
940
+ return {
941
+ set: setValue,
942
+ get: getValue,
943
+ get$: getValue$,
944
+ delete: deleteValue,
945
+ update: updateValue,
946
+ keys: () => store.keys(),
947
+ updateMany,
948
+ addRunner,
949
+ store$,
950
+ queryEvent$: queryEventSubject.asObservable(),
951
+ dispatchQueryEvent: (event) => {
952
+ queryEventSubject.next(event);
953
+ },
954
+ queryTrigger$: queryTriggerSubject.asObservable(),
955
+ dispatchQueryTrigger: (event) => {
956
+ queryTriggerSubject.next(event);
957
+ },
958
+ size: () => store.size,
959
+ destroy: () => {
960
+ debugger$.unsubscribe();
961
+ queryEventSubject.complete();
962
+ queryTriggerSubject.complete();
963
+ }
964
+ };
965
+ };
966
+ const createQueryTrigger = ({
967
+ refetch$,
968
+ options$,
969
+ queryStore,
970
+ key
971
+ }) => {
972
+ const enabledOption$ = options$.pipe(
973
+ rxjs.map(({ enabled = true }) => enabled),
974
+ rxjs.distinctUntilChanged()
975
+ );
976
+ const enabledTrigger$ = enabledOption$.pipe(
977
+ rxjs.skip(1),
978
+ rxjs.filter((enabled) => enabled)
979
+ );
980
+ return rxjs.merge(
981
+ queryStore.queryTrigger$.pipe(
982
+ rxjs.filter((event) => key === event.key),
983
+ rxjs.map(({ trigger: trigger2 }) => trigger2)
984
+ ),
985
+ refetch$.pipe(
986
+ rxjs.map((event) => ({
987
+ ...event,
988
+ type: "refetch"
989
+ }))
990
+ ),
991
+ enabledTrigger$.pipe(
992
+ rxjs.map(() => ({
993
+ type: "enabled",
994
+ ignoreStale: false
995
+ }))
996
+ )
997
+ );
998
+ };
999
+ const deduplicate = (key, queryStore) => (source) => {
1000
+ if (key === serializeKey([]))
1001
+ return source;
1002
+ return rxjs.defer(() => {
1003
+ var _a;
1004
+ const sourceFromStore = (_a = queryStore.get(key)) == null ? void 0 : _a.deduplication_fn;
1005
+ const deleteFromStore = () => {
1006
+ queryStore.update(key, {
1007
+ deduplication_fn: void 0
1008
+ });
1009
+ };
1010
+ const finalSource = sourceFromStore ?? source.pipe(
1011
+ /**
1012
+ * Ideally we would want to remove the query from the store only on finalize,
1013
+ * which means whenever the query complete or error. Unfortunately finalize is
1014
+ * triggered after a new stream arrive which create a concurrency issue.
1015
+ * tap is triggered correctly synchronously and before a new query arrive.
1016
+ */
1017
+ rxjs.tap({
1018
+ error: deleteFromStore,
1019
+ complete: deleteFromStore
1020
+ }),
1021
+ /**
1022
+ * Because tap is not called on unsubscription we still need to handle the case.
1023
+ */
1024
+ rxjs.finalize(deleteFromStore),
1025
+ rxjs.shareReplay({
1026
+ refCount: true,
1027
+ bufferSize: 1
1028
+ })
1029
+ );
1030
+ if (!sourceFromStore) {
1031
+ queryStore.update(key, {
1032
+ deduplication_fn: finalSource
1033
+ });
1034
+ }
1035
+ return finalSource;
1036
+ });
1037
+ };
1038
+ const notifyQueryResult = (options$) => (stream$) => stream$.pipe(
1039
+ rxjs.withLatestFrom(options$),
1040
+ rxjs.map(([result, options]) => {
1041
+ var _a, _b;
1042
+ if (result.error) {
1043
+ (_a = options.onError) == null ? void 0 : _a.call(options, result.error);
1044
+ } else {
1045
+ (_b = options.onSuccess) == null ? void 0 : _b.call(options, result);
1046
+ }
1047
+ return result;
1048
+ })
1049
+ );
1050
+ const registerResultInCache = ({
1051
+ queryStore,
1052
+ serializedKey,
1053
+ options
1054
+ }) => (stream) => stream.pipe(
1055
+ rxjs.tap(({ data }) => {
1056
+ if (data == null ? void 0 : data.result) {
1057
+ const result = data == null ? void 0 : data.result;
1058
+ queryStore.update(serializedKey, {
1059
+ ...options.cacheTime !== 0 && {
1060
+ cache_fnResult: { result }
1061
+ }
1062
+ });
1063
+ }
1064
+ })
1065
+ );
1066
+ const createQueryFetch = ({
1067
+ options$,
1068
+ options,
1069
+ fn,
1070
+ queryStore,
1071
+ serializedKey,
1072
+ trigger: trigger2,
1073
+ trigger$
1074
+ }) => {
1075
+ const enabledOption$ = options$.pipe(
1076
+ rxjs.map(({ enabled = true }) => enabled),
1077
+ rxjs.distinctUntilChanged()
1078
+ );
1079
+ const disabled$ = enabledOption$.pipe(
1080
+ rxjs.distinctUntilChanged(),
1081
+ rxjs.filter((enabled) => !enabled)
1082
+ );
1083
+ const deferredQuery = rxjs.defer(() => {
1084
+ const queryOrResponse = typeof fn === "function" ? fn() : fn;
1085
+ return rxjs.from(queryOrResponse);
1086
+ });
1087
+ const fnExecution$ = deferredQuery.pipe(
1088
+ retryOnError(options),
1089
+ deduplicate(serializedKey, queryStore),
1090
+ rxjs.tap(() => {
1091
+ queryStore.dispatchQueryEvent({
1092
+ key: serializedKey,
1093
+ type: "fetchSuccess"
1094
+ });
1095
+ queryStore.update(serializedKey, {
1096
+ lastFetchedAt: (/* @__PURE__ */ new Date()).getTime()
1097
+ });
1098
+ }),
1099
+ rxjs.map((result) => ({
1100
+ status: "success",
1101
+ data: { result },
1102
+ error: void 0
1103
+ })),
1104
+ rxjs.endWith({
1105
+ fetchStatus: "idle"
1106
+ }),
1107
+ rxjs.catchError((error) => {
1108
+ queryStore.dispatchQueryEvent({
1109
+ key: serializedKey,
1110
+ type: "fetchError"
1111
+ });
1112
+ return rxjs.of({
1113
+ fetchStatus: "idle",
1114
+ status: "error",
1115
+ data: void 0,
1116
+ error
1117
+ });
1118
+ }),
1119
+ notifyQueryResult(options$),
1120
+ registerResultInCache({ serializedKey, options, queryStore })
1121
+ );
1122
+ const newCache$ = queryStore.queryEvent$.pipe(
1123
+ rxjs.filter(
1124
+ (event) => event.key === serializedKey && event.type === "queryDataSet"
1125
+ ),
1126
+ rxjs.map(() => {
1127
+ var _a, _b;
1128
+ return (_b = (_a = queryStore.get(serializedKey)) == null ? void 0 : _a.cache_fnResult) == null ? void 0 : _b.result;
1129
+ }),
1130
+ rxjs.filter(isDefined),
1131
+ rxjs.map((result) => ({
1132
+ status: "success",
1133
+ data: { result }
1134
+ })),
1135
+ /**
1136
+ * @important
1137
+ * To avoid cache update being returned being the first result is returned.
1138
+ * For example if user set query data inside onSuccess callback, we simulate
1139
+ * a small delay to ensure it happens after.
1140
+ */
1141
+ rxjs.delay(1)
1142
+ );
1143
+ const execution$ = rxjs.merge(
1144
+ disabled$.pipe(
1145
+ rxjs.take(1),
1146
+ rxjs.map(() => ({
1147
+ fetchStatus: "idle"
1148
+ }))
1149
+ ),
1150
+ rxjs.merge(
1151
+ rxjs.of({ fetchStatus: "fetching", error: void 0 }),
1152
+ fnExecution$
1153
+ ).pipe(rxjs.takeUntil(disabled$)),
1154
+ newCache$
1155
+ ).pipe(rxjs.takeUntil(trigger$));
1156
+ const query = queryStore.get(serializedKey);
1157
+ const cacheResult = query == null ? void 0 : query.cache_fnResult;
1158
+ const hasCache = !!cacheResult;
1159
+ if (hasCache) {
1160
+ if (!(query == null ? void 0 : query.isStale) && !trigger2.ignoreStale) {
1161
+ return rxjs.of({
1162
+ fetchStatus: "idle",
1163
+ status: "success",
1164
+ data: { result: cacheResult.result },
1165
+ error: void 0
1166
+ });
1167
+ } else {
1168
+ return rxjs.merge(
1169
+ rxjs.of({
1170
+ fetchStatus: "fetching",
1171
+ status: "success",
1172
+ data: { result: cacheResult.result },
1173
+ error: void 0
1174
+ }),
1175
+ execution$
1176
+ );
1177
+ }
1178
+ }
1179
+ return execution$;
1180
+ };
1181
+ const compareKeys = (keyA, keyB, { exact = false } = {}) => {
1182
+ if (exact) {
1183
+ return serializeKey(keyA) === serializeKey(keyB);
1184
+ }
1185
+ return keyA.reduce((acc, value, index) => {
1186
+ if (!acc)
1187
+ return false;
1188
+ return serializeObject(value) === serializeObject(keyB[index]);
1189
+ }, true);
1190
+ };
1191
+ const logger$2 = Logger.namespace("invalidation");
1192
+ const createInvalidationClient = ({
1193
+ queryStore
1194
+ }) => {
1195
+ const invalidateQueries = ({
1196
+ queryKey,
1197
+ exact = false,
1198
+ predicate
1199
+ } = {}) => {
1200
+ let keysToRefetch = [];
1201
+ if (queryKey) {
1202
+ logger$2.log(`invalidation requested for`, queryKey);
1203
+ queryStore.updateMany({ isStale: true }, (entry) => {
1204
+ const isValid = compareKeys(queryKey, entry.queryKey, { exact });
1205
+ if (isValid) {
1206
+ keysToRefetch.push(serializeKey(entry.queryKey));
1207
+ }
1208
+ return isValid;
1209
+ });
1210
+ } else if (predicate) {
1211
+ queryStore.updateMany({ isStale: true }, (entry) => {
1212
+ const isValid = predicate(entry);
1213
+ if (isValid) {
1214
+ keysToRefetch.push(serializeKey(entry.queryKey));
1215
+ }
1216
+ return isValid;
1217
+ });
1218
+ } else {
1219
+ logger$2.log(`Invalidation requested for all queries`);
1220
+ queryStore.updateMany({ isStale: true });
1221
+ keysToRefetch = Array.from(queryStore.keys());
1222
+ }
1223
+ keysToRefetch.forEach((key) => {
1224
+ queryStore.dispatchQueryTrigger({
1225
+ key,
1226
+ trigger: { ignoreStale: true, type: "refetch" }
1227
+ });
1228
+ });
1229
+ };
1230
+ return {
1231
+ invalidateQueries,
1232
+ destroy: () => {
1233
+ }
1234
+ };
1235
+ };
1236
+ const logger$1 = Logger.namespace("refetch");
1237
+ const createRefetchClient = ({
1238
+ queryStore
1239
+ }) => {
1240
+ const pipeQueryResult = ({
1241
+ options$
1242
+ }) => (stream) => {
1243
+ const sharedStream = stream.pipe(rxjs.share());
1244
+ return rxjs.merge(
1245
+ sharedStream,
1246
+ sharedStream.pipe(
1247
+ rxjs.filter(
1248
+ (result) => !!result.data && result.fetchStatus !== "fetching"
1249
+ ),
1250
+ rxjs.distinctUntilChanged((prev, curr) => prev.data === curr.data),
1251
+ rxjs.withLatestFrom(options$),
1252
+ rxjs.map(([, { refetchInterval }]) => refetchInterval),
1253
+ rxjs.filter(isDefined),
1254
+ rxjs.switchMap((refetchInterval) => {
1255
+ if (typeof refetchInterval === "number") {
1256
+ return rxjs.timer(refetchInterval).pipe(
1257
+ rxjs.map(() => ({
1258
+ type: "refetch",
1259
+ ignoreStale: true
1260
+ })),
1261
+ rxjs.switchMap(() => rxjs.EMPTY)
1262
+ );
1263
+ }
1264
+ return rxjs.EMPTY;
1265
+ })
1266
+ )
1267
+ );
1268
+ };
1269
+ const pipeQueryTrigger = ({
1270
+ key
1271
+ }) => (stream) => {
1272
+ return rxjs.merge(
1273
+ stream.pipe(
1274
+ rxjs.tap(({ ignoreStale }) => {
1275
+ const query = queryStore.get(key);
1276
+ if (query && ignoreStale && !query.isStale) {
1277
+ logger$1.log(key, "marked stale by trigger!");
1278
+ queryStore.update(key, {
1279
+ isStale: true
1280
+ });
1281
+ }
1282
+ })
1283
+ )
1284
+ );
1285
+ };
1286
+ return {
1287
+ pipeQueryResult,
1288
+ pipeQueryTrigger,
1289
+ destroy: () => {
1290
+ }
1291
+ };
1292
+ };
1293
+ const difference = (a, b) => a.filter((element) => !b.includes(element));
1294
+ const createQueryListener = (store, onQuery) => store.store$.pipe(
1295
+ rxjs.map((store2) => [...store2.keys()]),
1296
+ rxjs.startWith([]),
1297
+ rxjs.pairwise(),
1298
+ rxjs.mergeMap(([previousKeys, currentKeys]) => {
1299
+ const newKeys = difference(currentKeys, previousKeys);
1300
+ return rxjs.merge(
1301
+ ...newKeys.map((key) => {
1302
+ const deleted$ = store.store$.pipe(
1303
+ rxjs.map(() => store.get(key)),
1304
+ rxjs.filter((item) => item === void 0)
1305
+ );
1306
+ return rxjs.merge(rxjs.NEVER, rxjs.of(key)).pipe(
1307
+ rxjs.tap(() => {
1308
+ }),
1309
+ onQuery,
1310
+ rxjs.finalize(() => {
1311
+ }),
1312
+ rxjs.takeUntil(deleted$)
1313
+ );
1314
+ })
1315
+ );
1316
+ })
1317
+ );
1318
+ const mapStoreQueryToRunnerOptions = (stream) => stream.pipe(
1319
+ rxjs.switchMap((entry) => rxjs.combineLatest(entry.runners)),
1320
+ rxjs.map((runnerValues) => runnerValues.map(({ options }) => options))
1321
+ );
1322
+ const mapOptionsToOption$1 = (stream) => stream.pipe(
1323
+ rxjs.map(
1324
+ (options) => options.reduce(
1325
+ (acc, value) => {
1326
+ return {
1327
+ ...acc,
1328
+ lowestStaleTime: value.staleTime === void 0 ? acc.lowestStaleTime : Math.min(
1329
+ value.staleTime ?? Infinity,
1330
+ acc.lowestStaleTime ?? Infinity
1331
+ )
1332
+ };
1333
+ },
1334
+ { lowestStaleTime: void 0 }
1335
+ )
1336
+ ),
1337
+ rxjs.distinctUntilChanged(shallowEqual)
1338
+ );
1339
+ const onlyFetchEventDone = (key) => (stream) => stream.pipe(
1340
+ rxjs.filter(
1341
+ (event) => event.key === key && (event.type === "fetchError" || event.type === "fetchSuccess")
1342
+ )
1343
+ );
1344
+ const markAsStale = ({
1345
+ queryStore
1346
+ }) => (stream) => stream.pipe(
1347
+ rxjs.switchMap((key) => {
1348
+ const query$ = queryStore.get$(key);
1349
+ return queryStore.queryEvent$.pipe(
1350
+ onlyFetchEventDone(key),
1351
+ rxjs.switchMap(
1352
+ () => query$.pipe(
1353
+ mapStoreQueryToRunnerOptions,
1354
+ mapOptionsToOption$1,
1355
+ rxjs.tap(({ lowestStaleTime = 0 }) => {
1356
+ var _a;
1357
+ if (lowestStaleTime === 0) {
1358
+ logger$2.log(key, "marked as stale!", {
1359
+ staleTime: lowestStaleTime
1360
+ });
1361
+ queryStore.update(key, { isStale: true });
1362
+ } else if ((_a = queryStore.get(key)) == null ? void 0 : _a.isStale) {
1363
+ logger$2.log(key, "marked non stale", {
1364
+ staleTime: lowestStaleTime
1365
+ });
1366
+ queryStore.update(key, { isStale: false });
1367
+ }
1368
+ }),
1369
+ rxjs.filter(
1370
+ ({ lowestStaleTime }) => lowestStaleTime !== Infinity && lowestStaleTime !== 0
1371
+ ),
1372
+ rxjs.switchMap(({ lowestStaleTime = 0 }) => rxjs.timer(lowestStaleTime)),
1373
+ rxjs.tap(() => {
1374
+ var _a;
1375
+ if (!((_a = queryStore.get(key)) == null ? void 0 : _a.isStale)) {
1376
+ logger$2.log(key, "marked as stale!");
1377
+ queryStore.update(key, { isStale: true });
1378
+ }
1379
+ })
1380
+ )
1381
+ ),
1382
+ rxjs.map(() => key)
1383
+ );
1384
+ })
1385
+ );
1386
+ const mapOptionsToOption = (stream) => stream.pipe(
1387
+ rxjs.map(
1388
+ (options) => options.reduce(
1389
+ (acc, value) => {
1390
+ return {
1391
+ ...acc,
1392
+ lowestCacheTime: value.cacheTime === void 0 ? acc.lowestCacheTime : Math.min(
1393
+ value.cacheTime ?? Infinity,
1394
+ acc.lowestCacheTime ?? Infinity
1395
+ )
1396
+ };
1397
+ },
1398
+ { lowestCacheTime: void 0 }
1399
+ )
1400
+ ),
1401
+ rxjs.distinctUntilChanged(shallowEqual)
1402
+ );
1403
+ const onCacheUpdate = (stream) => stream.pipe(
1404
+ rxjs.map((item) => item.cache_fnResult),
1405
+ rxjs.distinctUntilChanged(shallowEqual)
1406
+ );
1407
+ const invalidateCache = ({
1408
+ queryStore
1409
+ }) => (stream) => stream.pipe(
1410
+ rxjs.switchMap((key) => {
1411
+ const query$ = queryStore.get$(key);
1412
+ const invalidateCache$ = query$.pipe(
1413
+ onCacheUpdate,
1414
+ rxjs.switchMap(
1415
+ () => query$.pipe(
1416
+ mapStoreQueryToRunnerOptions,
1417
+ mapOptionsToOption,
1418
+ rxjs.switchMap(
1419
+ ({
1420
+ lowestCacheTime = 5 * 60 * 1e3
1421
+ /* 5mn */
1422
+ }) => rxjs.timer(lowestCacheTime).pipe(
1423
+ rxjs.tap(() => {
1424
+ queryStore.update(key, { cache_fnResult: void 0 });
1425
+ })
1426
+ )
1427
+ )
1428
+ )
1429
+ )
1430
+ );
1431
+ return invalidateCache$.pipe(rxjs.map(() => key));
1432
+ })
1433
+ );
1434
+ const garbageCache = ({
1435
+ queryStore
1436
+ }) => (stream) => stream.pipe(
1437
+ rxjs.switchMap((key) => {
1438
+ const query$ = queryStore.get$(key);
1439
+ return query$.pipe(
1440
+ rxjs.filter((entry) => !entry.cache_fnResult),
1441
+ rxjs.map((entry) => entry.runners.length > 0),
1442
+ rxjs.pairwise(),
1443
+ rxjs.filter(([hadRunners, hasRunners]) => hadRunners && !hasRunners),
1444
+ rxjs.tap(() => {
1445
+ queryStore.delete(key);
1446
+ }),
1447
+ rxjs.map(() => key)
1448
+ );
1449
+ })
1450
+ );
1451
+ const getInitialQueryEntity = ({ key }) => ({
1452
+ isStale: true,
1453
+ queryKey: key,
1454
+ runners: []
1455
+ });
1456
+ const updateStoreWithQuery = ({
1457
+ queryStore,
1458
+ serializedKey,
1459
+ runner$,
1460
+ key
1461
+ }) => (stream) => stream.pipe(
1462
+ rxjs.map((value) => {
1463
+ if (key.length === 0)
1464
+ return [value, () => {
1465
+ }];
1466
+ if (!queryStore.get(serializedKey)) {
1467
+ queryStore.set(serializedKey, getInitialQueryEntity({ key }));
1468
+ } else {
1469
+ queryStore.update(serializedKey, {
1470
+ queryKey: key,
1471
+ ...value.options.markStale && {
1472
+ isStale: true
1473
+ }
1474
+ });
1475
+ }
1476
+ return [value, queryStore.addRunner(serializedKey, runner$)];
1477
+ })
1478
+ );
1479
+ const logger = Logger.namespace("cache");
1480
+ const createCacheClient = ({
1481
+ queryStore
1482
+ }) => {
1483
+ const setQueryData = ({
1484
+ queryKey,
1485
+ updater
1486
+ }) => {
1487
+ const serializedKey = serializeKey(queryKey);
1488
+ if (queryKey.length === 0)
1489
+ return;
1490
+ logger.log("set cache for query", serializeKey);
1491
+ if (!queryStore.get(serializedKey)) {
1492
+ queryStore.set(serializedKey, getInitialQueryEntity({ key: queryKey }));
1493
+ }
1494
+ queryStore.update(serializedKey, (entity) => {
1495
+ var _a;
1496
+ if (typeof updater === "function") {
1497
+ const callableUpdater = updater;
1498
+ return {
1499
+ ...entity,
1500
+ cache_fnResult: {
1501
+ result: callableUpdater(
1502
+ (_a = entity.cache_fnResult) == null ? void 0 : _a.result
1503
+ )
1504
+ }
1505
+ };
1506
+ }
1507
+ return {
1508
+ ...entity,
1509
+ cache_fnResult: {
1510
+ result: updater
1511
+ }
1512
+ };
1513
+ });
1514
+ queryStore.dispatchQueryEvent({
1515
+ key: serializedKey,
1516
+ type: "queryDataSet"
1517
+ });
1518
+ };
1519
+ return {
1520
+ setQueryData
1521
+ };
1522
+ };
1523
+ const createClient = () => {
1524
+ const queryStore = createQueryStore();
1525
+ const invalidationClient = createInvalidationClient({ queryStore });
1526
+ const cacheClient = createCacheClient({ queryStore });
1527
+ const refetchClient = createRefetchClient({ queryStore });
1528
+ const query$ = ({
1529
+ key,
1530
+ fn$: maybeFn$,
1531
+ fn: maybeFn,
1532
+ refetch$ = new rxjs.Subject(),
1533
+ options$ = new rxjs.BehaviorSubject({})
1534
+ }) => {
1535
+ const serializedKey = serializeKey(key);
1536
+ const internalRefetch$ = new rxjs.Subject();
1537
+ const fn$ = maybeFn$ ?? (maybeFn ? rxjs.of(maybeFn) : rxjs.NEVER);
1538
+ Logger.log("query$()", serializedKey);
1539
+ const runner$ = options$.pipe(rxjs.map((options) => ({ options })));
1540
+ let deleteRunner = () => {
1541
+ };
1542
+ const initialTrigger$ = rxjs.of({
1543
+ type: "initial",
1544
+ ignoreStale: false
1545
+ });
1546
+ const trigger$ = createQueryTrigger({
1547
+ options$,
1548
+ refetch$: rxjs.merge(refetch$, internalRefetch$),
1549
+ key: serializedKey,
1550
+ queryStore
1551
+ }).pipe(refetchClient.pipeQueryTrigger({ options$, key: serializedKey }));
1552
+ const result$ = rxjs.merge(initialTrigger$, trigger$).pipe(
1553
+ rxjs.withLatestFrom(fn$, options$),
1554
+ rxjs.map(([trigger2, fn, options]) => ({ trigger: trigger2, fn, options })),
1555
+ updateStoreWithQuery({
1556
+ key,
1557
+ queryStore,
1558
+ runner$,
1559
+ serializedKey
1560
+ }),
1561
+ rxjs.map(([value, deleteRunnerFn]) => {
1562
+ deleteRunner = deleteRunnerFn;
1563
+ Logger.log("reactjrx", serializedKey, "query trigger", {
1564
+ trigger: value.trigger,
1565
+ options: value.options
1566
+ });
1567
+ return value;
1568
+ }),
1569
+ rxjs.filter(({ options }) => options.enabled !== false),
1570
+ rxjs.mergeMap(
1571
+ ({ fn, options, trigger: trigger2 }) => createQueryFetch({
1572
+ options$,
1573
+ options,
1574
+ fn,
1575
+ queryStore,
1576
+ serializedKey,
1577
+ trigger: trigger2,
1578
+ trigger$
1579
+ })
1580
+ ),
1581
+ // hooks
1582
+ rxjs.switchMap(
1583
+ (result) => rxjs.merge(
1584
+ rxjs.of(result).pipe(
1585
+ refetchClient.pipeQueryResult({
1586
+ key: serializedKey,
1587
+ queryStore,
1588
+ options$,
1589
+ refetch$: internalRefetch$
1590
+ })
1591
+ )
1592
+ )
1593
+ ),
1594
+ mergeResults,
1595
+ rxjs.withLatestFrom(options$),
1596
+ rxjs.takeWhile(([result, options]) => {
1597
+ const shouldStop = result.data !== void 0 && options.terminateOnFirstResult;
1598
+ return !shouldStop;
1599
+ }, true),
1600
+ rxjs.map(([result]) => result),
1601
+ rxjs.finalize(() => {
1602
+ deleteRunner();
1603
+ })
1604
+ );
1605
+ return {
1606
+ result$
1607
+ };
1608
+ };
1609
+ const queryListenerSub = createQueryListener(
1610
+ queryStore,
1611
+ (stream) => stream.pipe(
1612
+ rxjs.switchMap((key) => {
1613
+ const key$ = rxjs.of(key);
1614
+ return rxjs.merge(
1615
+ invalidateCache({
1616
+ queryStore
1617
+ })(key$),
1618
+ markAsStale({
1619
+ queryStore
1620
+ })(key$),
1621
+ garbageCache({
1622
+ queryStore
1623
+ })(key$)
1624
+ );
1625
+ })
1626
+ )
1627
+ ).subscribe();
1628
+ return {
1629
+ query$,
1630
+ queryStore,
1631
+ ...invalidationClient,
1632
+ ...cacheClient,
1633
+ ...refetchClient,
1634
+ destroy: () => {
1635
+ queryStore.destroy();
1636
+ queryListenerSub.unsubscribe();
1637
+ }
1638
+ };
1639
+ };
923
1640
  exports.PersistSignals = PersistSignals;
924
1641
  exports.ReactjrxQueryProvider = Provider;
925
1642
  exports.SIGNAL_RESET = SIGNAL_RESET;
@@ -937,6 +1654,7 @@ exports.useObserve = useObserve;
937
1654
  exports.useObserveCallback = useObserveCallback;
938
1655
  exports.usePersistSignalsContext = usePersistSignalsContext;
939
1656
  exports.useQuery = useQuery;
1657
+ exports.useReactJrxProvider = useReactJrxProvider;
940
1658
  exports.useScopeSignals = useScopeSignals;
941
1659
  exports.useSetSignal = useSetSignal;
942
1660
  exports.useSignal = useSignal;