reactjrx 1.99.0 → 1.101.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.
package/dist/index.cjs CHANGED
@@ -1 +1,3433 @@
1
- "use strict";var yt=Object.defineProperty;var Ke=s=>{throw TypeError(s)};var St=(s,e,t)=>e in s?yt(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var m=(s,e,t)=>St(s,typeof e!="symbol"?e+"":e,t),Ne=(s,e,t)=>e.has(s)||Ke("Cannot "+t);var o=(s,e,t)=>(Ne(s,e,"read from private field"),t?t.call(s):e.get(s)),w=(s,e,t)=>e.has(s)?Ke("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(s):e.set(s,t),M=(s,e,t,n)=>(Ne(s,e,"write to private field"),n?n.call(s,t):e.set(s,t),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const S=require("react"),r=require("rxjs"),K=require("rxjs/operators"),qe=require("react/jsx-runtime");function vt(s){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(s){for(const t in s)if(t!=="default"){const n=Object.getOwnPropertyDescriptor(s,t);Object.defineProperty(e,t,n.get?n:{enumerable:!0,get:()=>s[t]})}}return e.default=s,Object.freeze(e)}const we=vt(S),Q=s=>{const e=S.useRef(s);return S.useMemo(()=>{e.current=s},[s]),e};function je(s){return s instanceof Promise||s&&typeof s=="object"&&"then"in s&&typeof s.then=="function"&&"catch"in s&&s.catch==="function"}function R(s){if(r.isObservable(s))return s;if(je(s))return r.from(s);if(typeof s!="function")return r.of(s);const e=s;return r.defer(()=>{const t=e();return je(t)?r.from(t):r.isObservable(t)?t:r.of(t)})}function fe(s,e,t){const n=e!=null&&!Array.isArray(e)?e:{defaultValue:void 0,unsubscribeOnUnmount:!0},i=!t&&Array.isArray(e)?e:typeof s=="function"?t??[]:[s],u=S.useRef("getValue"in s&&typeof s.getValue=="function"?s.getValue():n.defaultValue),a=Q(s),l=Q(n),h=S.useCallback(b=>{const E=a.current,d=R(E).pipe(r.distinctUntilChanged((p,g)=>p===g),r.tap(p=>{u.current=p}),r.catchError(p=>(console.error(p),r.EMPTY))).subscribe(b);return()=>{l.current.unsubscribeOnUnmount!==!1&&d.unsubscribe()}},[...i]),f=S.useCallback(()=>u.current,[]);return S.useSyncExternalStore(h,f,f)}function Re(s,e=[]){const t=Q(s);S.useEffect(()=>{const n=R(t.current).pipe(r.catchError(i=>(console.error(i),r.EMPTY))).subscribe();return()=>{n.unsubscribe()}},[...e,t])}const $e=s=>{const e=S.useRef();return e.current||(e.current=s()),S.useEffect(()=>{process.env.NODE_ENV},[]),e},xe=({onBeforeComplete:s,completeOnUnmount:e=!0}={})=>{const t=$e(()=>new r.Subject),n=S.useRef(!1),i=Q(s),u=Q(e);return S.useEffect(()=>(n.current&&(t.current=new r.Subject,n.current=!1),()=>{if(!u.current){n.current=!0;return}n.current||(i.current!=null&&i.current(),t.current.complete(),n.current=!0)}),[u,i,t]),t},Ot=()=>{const s=xe(),e=Q(s.current.asObservable()),t=S.useCallback(n=>{s.current.next(n)},[]);return[e.current,t]},Ue=s=>{const e=$e(()=>new r.BehaviorSubject(s)),t=S.useRef(!1),n=S.useRef(s);return S.useEffect(()=>(t.current&&(e.current=new r.BehaviorSubject(n.current),t.current=!1),()=>{t.current||(e.current.complete(),t.current=!0)}),[e]),e},wt=s=>{const e=Ue(s),t=Q(e.current.asObservable()),n=S.useCallback(i=>{e.current.next(i)},[e.current]);return[t.current,n,e.current.getValue()]},Je=Symbol("SIGNAL_RESET");function Xe(s={}){const e={default:s.default,key:s.key},{default:t}=e??{},n=new r.BehaviorSubject(t),i=a=>{if(typeof a=="function"){const l=a(n.getValue());if(l===n.getValue())return;n.next(l);return}if(a===Je){n.next(t??void 0);return}n.next(a)},u=()=>n.getValue();if("get"in s){const a=h=>(h.subject.pipe(r.skip(1),r.first()).subscribe(()=>{var c;const f=(c=s.get)==null?void 0:c.call(s,a);i(f)}),h.getValue()),l=s.get(a);return i(l),{getValue:u,config:s,subject:n}}return{setValue:i,getValue:u,config:e,subject:n}}function Ze(s,e){const n=e??(()=>s.getValue());return fe(()=>s.subject.pipe(r.map(u=>n(u)),r.distinctUntilChanged()),{defaultValue:n(s.getValue())},[])}const $t=s=>{const[e]=S.useState(()=>Xe(s));return[Ze(e),e]},Et=s=>({getItem:async e=>{const t=await s.getItem(e);if(t)return JSON.parse(t)},setItem:async(e,t)=>{await s.setItem(e,JSON.stringify(t))},removeItem:async e=>{},clear:async()=>{}}),Ce=s=>{if(!(!s||typeof s!="object"))return s},Ct=({adapter:s,key:e})=>({clear:async()=>await s.removeItem(e),removeItem:async t=>{const n=await s.getItem(e),{[t]:i,...u}=Ce(n)??{};await s.setItem(e,u)},getItem:async t=>{const n=await s.getItem(e),i=Ce(n)??{};if(t in i)return i[t]},setItem:async(t,n)=>{const i=await s.getItem(e),u=Ce(i)??{};await s.setItem(e,{...u,[t]:n})}}),et=({key:s}={})=>s?Ct({adapter:et(),key:s}):{clear:async()=>{localStorage.clear()},removeItem:async e=>{localStorage.removeItem(e)},getItem:async e=>{const t=localStorage.getItem(e);if(t)return JSON.parse(t)},setItem:async(e,t)=>{localStorage.setItem(e,JSON.stringify(t))}},se="__reactjrx",jt=s=>{if(typeof s=="object"&&s!==null&&se in s&&s[se]===se)return s};function me(s){return s!=null}const He=s=>{const e=Ue(s);return S.useEffect(()=>{e.current.next(s)},[s,e]),e},Mt=({adapter:s,config:e})=>{const{signal:t,version:n}=e,u={value:t.getValue(),[se]:se,migrationVersion:n};return r.from(s.setItem(t.config.key,u)).pipe(r.catchError(a=>(console.error(a),r.of(null))))};function Ft({adapter:s,config:e}){const{hydrate:t=({value:u})=>u,signal:n,version:i}=e;return r.from(s.getItem(n.config.key)).pipe(r.switchMap(u=>{const a=jt(u);if(!a||a.migrationVersion!==void 0&&i>a.migrationVersion||a.value===void 0)return r.of(u);const l=a.value;return n.setValue(t({value:l,version:i})),r.of(u)}))}function Rt({entries:s=[],onReady:e,adapter:t}){const n=Q(s),i=Q(e),u=He(t),a=fe(()=>{const h=n.current;return u.current.pipe(r.switchMap(f=>(h.length===0||!f?r.of(!0):r.zip(...h.map(b=>Ft({adapter:f,config:b}))).pipe(r.map(()=>!0))).pipe(r.tap(()=>{i.current!=null&&i.current()}),r.catchError(b=>(console.error("Unable to hydrate",b),r.EMPTY)))))},{defaultValue:!1},[u,n]),l=He(a);return Re(()=>l.current.pipe(r.filter(h=>h),r.switchMap(()=>u.current),r.filter(me),r.switchMap(h=>r.merge(...n.current.map(f=>f.signal.subject.pipe(r.throttleTime(500,r.asyncScheduler,{trailing:!0}),r.switchMap(()=>r.from(Mt({adapter:h,config:f})))))))),[l,u]),{isHydrated:a}}const xt=()=>{const s=xe({onBeforeComplete:()=>{s.current.next()}});return s},tt=s=>{S.useEffect(s,[])},Ut=s=>{tt(()=>{s()})};function rt(s,e){return Math.min(s,e)}function st(s,e){return Math.pow(2,s)*e}function Ae(s){const{retry:e,retryDelay:t,retryAfterDelay:n,retryAfter:i=()=>r.of(!0)}=s,u=typeof e!="function"?e===!1?0:e===!0?1/0:e??1/0:1/0,a=typeof e=="function"?e:()=>!0,l=typeof t=="number"?t:100,h={shouldRetry:a,...s},{maxInterval:f=1/0,resetOnSuccess:c=!1,backoffDelay:b=st}=h;return E=>r.defer(()=>{let d=0;const p=(g,C)=>g<u?a(g,C):!1;return E.pipe(K.catchError(g=>{var $;if(d++,!p(d-1,g))throw g;const C=($=s.caughtError)==null?void 0:$.call(s,d,g);if(!C)throw g;return C.pipe(K.mergeMap(O=>r.merge(r.of(O),r.throwError(()=>g))))}),K.retryWhen(g=>g.pipe(K.concatMap(C=>{const $=d-1;return i().pipe(K.first(),K.mergeMap(()=>p($,C)?r.timer(rt(b($,l),f)).pipe(K.mergeMap(O=>n&&!n($,C)?r.throwError(()=>C):r.of(O))):r.throwError(()=>C)))}))),K.catchError(g=>{if(s.catchError)return s.catchError(d,g);throw g}),K.tap(()=>{c&&(d=0)}))})}const At=(s,e)=>s.length===e.length&&s.every((t,n)=>t===e[n]),J=typeof window>"u"||"Deno"in window;function Le(s){return Object.prototype.toString.call(s)==="[object Object]"}function Me(s){if(!Le(s))return!1;const e=s.constructor;if(typeof e>"u")return!0;const t=e.prototype;return!(!Le(t)||!t.hasOwnProperty("isPrototypeOf"))}const re=s=>JSON.stringify(s,(e,t)=>Me(t)?Object.keys(t).sort().reduce((n,i)=>(n[i]=t[i],n),{}):t),Qe=(s=21)=>crypto.getRandomValues(new Uint8Array(s)).reduce((e,t)=>(t&=63,t<36?e+=t.toString(36):t<62?e+=(t-26).toString(36).toUpperCase():t>62?e+="-":e+="_",e),""),X=()=>({context:void 0,data:void 0,error:null,status:"idle",submittedAt:0,variables:void 0,failureCount:0,failureReason:null,isPaused:!1});function Pe(s){let e=0;return function(n){return new r.Observable(i=>{e++;const u=n.subscribe(i);return s(e),()=>{e--,s(e),u.unsubscribe()}})}}const ne=s=>s.pipe(r.takeWhile(e=>e.status!=="error"&&e.status!=="success",!0));var H;class Qt{constructor({__queryFinalizeHook:e}={}){w(this,H,new r.Subject);m(this,"state$");const t=new r.BehaviorSubject(0),n=t.pipe(r.filter(i=>i===0));this.state$=o(this,H).pipe(r.concatMap(({args:i,mutation:u,options:a})=>{const l=a.mapOperator??"merge",h=o(this,H).pipe(r.filter(()=>l==="merge")),f=o(this,H).pipe(r.filter(()=>l==="switch"),r.tap(()=>{u.cancel()})),c=r.defer(()=>(u.execute(i),r.EMPTY)),b=u.state$.pipe(ne,r.last(),r.mergeMap(()=>u.state$),r.takeUntil(o(this,H))),E=u.state$.pipe(ne,r.skip(1)),d=r.merge(n,h,f,u.cancelled$);return r.merge(E,b,c).pipe(r.map(p=>({state:p,mutation:u})),e??r.identity,r.takeUntil(d))}),r.shareReplay({refCount:!0,bufferSize:1}),Pe(i=>{t.next(i)}))}trigger({args:e,options:t,mutation:n}){o(this,H).next({args:e,options:t,mutation:n})}}H=new WeakMap;function Ee(s,e){return s===e?!0:typeof s!=typeof e?!1:s&&e&&typeof s=="object"&&typeof e=="object"?!Object.keys(e).some(t=>!Ee(s[t],e[t])):!1}const ye=(s,e,{exact:t=!1}={})=>t?re(s)===re(e):Ee(s,e);function x(s,e){if(s==null||e===void 0||typeof s!="object"||typeof e!="object")return s===e;if(s.constructor!==(e==null?void 0:e.constructor))return!1;const t=Object.keys(s),n=Object.keys(e);if(t.length!==n.length)return!1;for(const i of t)if(!e.hasOwnProperty(i)||s[i]!==e[i])return!1;return!0}const nt=s=>s.pipe(r.distinctUntilChanged(({data:e,...t},{data:n,...i})=>x(t,i)&&x(e,n)));var B,I;class Pt{constructor(e,t={},n){w(this,B);w(this,I,new r.BehaviorSubject(void 0));m(this,"observed$");m(this,"getObserverResultFromState",e=>({...X(),...e,isSuccess:e.status==="success",isPending:e.status==="pending",isIdle:e.status==="idle",isError:e.status==="error",mutate:this.mutate,reset:this.reset}));var i;this.client=e,this.options=t,this.options.mutationKey=((i=this.options)==null?void 0:i.mutationKey)??[Qe()],M(this,B,n??new Qt(this.options)),this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this),o(this,I).pipe(r.filter(me),r.mergeMap(u=>o(this,B).state$.pipe(r.takeUntil(u.mutation.state$.pipe(ne,r.last()))))).subscribe(),this.observed$=o(this,I).pipe(r.switchMap(u=>(u==null?void 0:u.mutation.state$.pipe(r.map(a=>({state:a,options:u.options}))))??r.EMPTY),r.tap(({state:u,options:a})=>{u.status==="error"&&(a!=null&&a.onError&&(a==null||a.onError(u.error,u.variables,u.context)),a!=null&&a.onSettled&&(a==null||a.onSettled(u.data,u.error,u.variables,u.context))),u.status==="success"&&(a!=null&&a.onSuccess&&(a==null||a.onSuccess(u.data,u.variables,u.context)),a!=null&&a.onSettled&&(a==null||a.onSettled(u.data,u.error,u.variables,u.context)))}),r.ignoreElements())}setOptions(e){var i;const t=this.options;this.options=this.client.defaultMutationOptions({mutationKey:this.options.mutationKey,...e});const n=(i=o(this,I).getValue())==null?void 0:i.mutation;this.options.mutationKey&&t.mutationKey&&!ye(this.options.mutationKey,t.mutationKey,{exact:!0})?this.reset():n==null||n.setOptions(this.options)}observe(){var u;const e=this.getObserverResultFromState(((u=o(this,I).getValue())==null?void 0:u.mutation.state)??X()),t=o(this,B).state$.pipe(r.distinctUntilChanged(({mutation:a,state:{data:l,...h}},{mutation:f,state:{data:c,...b}})=>a===f&&x(h,b)&&x(l,c)),r.map(({state:a})=>a),r.scan((a,l)=>({...a,...l,...l.status==="pending"&&{data:l.data??a.data},...l.status==="pending"&&{error:l.error??a.error}})),r.map(a=>this.getObserverResultFromState(a))),n=o(this,I).pipe(r.filter(me),r.switchMap(a=>a.mutation.cancelled$),r.map(()=>this.getObserverResultFromState(X())));return{result$:r.merge(this.observed$,t,n).pipe(nt),lastValue:e}}subscribe(e){const t=this.observe().result$.subscribe(n=>{e(n)});return()=>{t.unsubscribe()}}async mutate(e,t={}){const n=this.client.getMutationCache().build(this.client,this.options);return o(this,I).next({mutation:n,options:t}),o(this,B).trigger({args:e,options:this.options,mutation:n}),await new Promise((i,u)=>{n.state$.pipe(ne,r.last()).subscribe({error:a=>{u(a)},next:a=>{a.error?u(a.error):i(a.data)}})})}getCurrentResult(){var t;const e=this.client.getMutationCache().find({exact:!0,mutationKey:(t=this.options)==null?void 0:t.mutationKey});return this.getObserverResultFromState((e==null?void 0:e.state)??X())}reset(){const{mutation:e}=o(this,I).getValue()??{};o(this,I).next(void 0),e==null||e.cancel()}}B=new WeakMap,I=new WeakMap;const it=S.createContext(void 0),kt=({client:s})=>(S.useEffect(()=>(s.mount(),()=>{s.unmount()}),[s]),null),Vt=S.memo(({children:s,client:e})=>{const t=S.useMemo(()=>e,[e]);return qe.jsxs(it.Provider,{value:t,children:[qe.jsx(kt,{client:e}),s]})}),ke=s=>{const e=S.useContext(it);if(s)return s;if(!e)throw new Error("No QueryClient set, use QueryClientProvider to set one");return e};function It(){}function Tt(s,e){const t=ke(e),n=Q(s),i=$e(()=>[Qe()]),u=re(s.mutationKey??i.current),[a]=S.useState(()=>new Pt(t,s));S.useEffect(()=>{a.setOptions(s)},[a,s]);const l=S.useMemo(()=>a.observe(),[u,a]),h=fe(l.result$)??l.lastValue,f=S.useCallback((c,b)=>{a.mutate(c,b).catch(It)},[a]);return S.useEffect(()=>()=>{n.current.cancelOnUnMount&&a.reset()},[a,n]),{...h,mutate:f,mutateAsync:h.mutate}}function Dt(s){return e=>e.pipe(K.tap(t=>{s.next(t)}))}class Kt{constructor(){m(this,"isOnlineSubject",new r.BehaviorSubject(!0));m(this,"online$",this.isOnlineSubject.pipe(r.distinctUntilChanged()));m(this,"backToOnline$",this.online$.pipe(r.filter(e=>e),r.first()));r.merge(J?r.EMPTY:r.fromEvent(window,"offline").pipe(r.map(()=>!1)),J?r.EMPTY:r.fromEvent(window,"online").pipe(r.map(()=>!0))).pipe(Dt(this.isOnlineSubject)).subscribe()}isOnline(){return this.isOnlineSubject.getValue()}setOnline(e){this.isOnlineSubject.getValue()!==e&&this.isOnlineSubject.next(e)}}const _=new Kt;function Ve(s,e){return s.isStaleByTime(e.staleTime)}function Nt(s,e){return e.enabled!==!1&&!s.state.dataUpdatedAt&&!(s.state.status==="error"&&e.retryOnMount===!1)&&s.state.fetchStatus!=="fetching"}function We(s,e){return Nt(s,e)||s.state.dataUpdatedAt>0&&at(s,e,e.refetchOnMount)}function _e(s,e,t,n){return s.state.fetchStatus!=="fetching"&&t.enabled!==!1&&(s!==e||n.enabled===!1)&&(!t.suspense||s.state.status!=="error")&&Ve(s,t)}function qt(s,e){return at(s,e,e.refetchOnWindowFocus)}function at(s,e,t){if(e.enabled!==!1){const n=typeof t=="function"?t(s):t;return n==="idle"?s.state.fetchStatus==="idle":n==="always"||n!==!1&&Ve(s,e)}return!1}function Ht(s){return(s??"online")==="online"?_.isOnline():!0}function Be(s,e){return e.reduce((t,n)=>n in s?{...t,[n]:s[n]}:t,{})}function ze(s){return Array.isArray(s)&&s.length===Object.keys(s).length}function ut(s,e){if(s===e)return s;const t=ze(s)&&ze(e);if(t||Me(s)&&Me(e)){const n=t?s:Object.keys(s),i=n.length,u=t?e:Object.keys(e),a=u.length,l=t?[]:{};let h=0;for(let f=0;f<a;f++){const c=t?f:u[f];!t&&s[c]===void 0&&e[c]===void 0&&n.includes(c)?(l[c]=void 0,h++):(l[c]=ut(s[c],e[c]),l[c]===s[c]&&s[c]!==void 0&&h++)}return i===a&&h===i?s:l}return e}function Ie(s,e){return((e==null?void 0:e.queryKeyHashFn)??re)(s)}function Ye(s,e){const{type:t="all",exact:n,fetchStatus:i,predicate:u,queryKey:a,stale:l}=s;if(a){if(n){if(e.queryHash!==Ie(a,e.options))return!1}else if(!Ee(e.queryKey,a))return!1}if(t!=="all"){const h=e.isActive();if(t==="active"&&!h||t==="inactive"&&h)return!1}return!(typeof l=="boolean"&&e.isStale()!==l||typeof i<"u"&&i!==e.state.fetchStatus||u&&!u(e))}function Lt(s,e){return Math.max(s+(e??0)-Date.now(),0)}function Wt(s,e){return typeof s=="function"?s(e):s}function Se(s,e,t){return typeof t.structuralSharing=="function"?t.structuralSharing(s,e):t.structuralSharing!==!1?ut(s,e):e}const Fe=Symbol(),_t=({getOptions:s,getState:e,initialState:t})=>n=>n.pipe(r.scan((i,{command:u,state:a})=>{if(u==="reset")return{...i,...a};if(u==="cancel"){const v=i.status==="pending"?"pending":a.status??i.status;return{...i,...a,status:v}}const l=a.data,h=l!==void 0&&l!==i.data,f="data"in a,c=a.status==="success",b=i.data!==void 0,E=i.error!==void 0||i.error!==null,d=a.status??i.status,p=h?Se(e().data,l,s()):f?a.data:i.data,g=i.status==="error"||i.status==="success",C=a.status==="error"&&(i.status==="error"&&i.fetchStatus==="fetching"||i.status!=="error")?i.errorUpdateCount+1:i.errorUpdateCount,$=h?i.dataUpdateCount+1:a.dataUpdateCount??i.dataUpdateCount,O=a.status==="pending"&&g&&(b||E),U=d==="pending"?null:a.error??i.error;return{...i,...a,status:d,error:U,errorUpdateCount:C,...c&&{isInvalidated:!1},data:p,dataUpdateCount:$,...O&&{status:i.status}}},t)),Bt=s=>s.pipe(r.map(({status:e,fetchStatus:t})=>t==="idle"&&(e==="success"||e==="error"))),ot=s=>s.pipe(r.takeWhile(e=>e.fetchStatus!=="idle",!0));var Oe,L;class zt{constructor(){w(this,Oe,r.merge(J?r.EMPTY:r.fromEvent(document,"visibilitychange"),J?r.EMPTY:r.fromEvent(window,"visibilitychange")).pipe(r.map(()=>document.visibilityState)));w(this,L,new r.BehaviorSubject(J?!0:document.visibilityState==="visible"));m(this,"focused$",o(this,L));m(this,"focusRegained$",this.focused$.pipe(r.skip(1),r.filter(e=>e)));o(this,Oe).pipe(r.tap(e=>{o(this,L).next(e==="visible")})).subscribe()}isFocused(){return o(this,L).getValue()}setFocused(e){o(this,L).getValue()!==(e??!0)&&o(this,L).next(e??!0)}subscribe(e){const t=this.focused$.subscribe(e);return()=>{t.unsubscribe()}}refresh(){document.dispatchEvent(new Event("visibilitychange"))}}Oe=new WeakMap,L=new WeakMap;const ve=new zt,Yt=s=>s.pipe(r.filter(e=>e.status==="success"),r.map(e=>({data:e.data,status:e.status,dataUpdatedAt:e.dataUpdatedAt})),r.distinctUntilChanged(x));var q,j,ie,z,A,Z,ae;class ct{constructor(e,t){w(this,q);w(this,j);w(this,ie,new r.Subject);m(this,"queryUpdateSubject",new r.Subject);w(this,z);w(this,A);w(this,Z);w(this,ae,0);m(this,"getObserverResultFromQuery",({options:e,query:t,optimisticResult:n,prevResult:{result:i,options:u,state:a,select:l,selectError:h,selectResult:f}})=>{var ge;const c=t.state,b=t.state.status==="pending",E=o(this,j),d=this.options,g=t!==E?t.state:o(this,z);let{errorUpdatedAt:C,fetchStatus:$,error:O}=c;if(n){const P=!!o(this,ae),De=!P&&We(t,e),mt=P&&_e(t,E,e,d);(De||mt)&&($=Ht(t.options.networkMode)?"fetching":"paused")}const U=b&&$==="fetching";let v,y=h,T=l??null,D=f;if(e.select&&typeof c.data<"u")if(i&&c.data===(a==null?void 0:a.data)&&e.select===l)v=f;else try{T=e.select,v=e.select(c.data),v=Se(i==null?void 0:i.data,v,e),D=v,y=null}catch(P){v=f,y=P}else v=c.data,y=null;let V=$!=="idle"&&!c.dataUpdatedAt?"pending":c.status;y&&(O=y,v=f,C=(i==null?void 0:i.errorUpdatedAt)??C,V="error");const de=V==="error";let pe=!1;if(typeof e.placeholderData<"u"&&typeof v>"u"&&V==="pending"){let P;if(i!=null&&i.isPlaceholderData&&e.placeholderData===(u==null?void 0:u.placeholderData))P=i.data;else if(P=typeof e.placeholderData=="function"?e.placeholderData((ge=o(this,Z))==null?void 0:ge.state.data,o(this,Z)):e.placeholderData,e.select&&typeof P<"u")try{P=e.select(P)}catch{}typeof P<"u"&&(V="success",v=Se(i==null?void 0:i.data,P,e),pe=!0)}const be=$==="fetching";return{result:{status:V,fetchStatus:$,isPending:b,isSuccess:V==="success",isError:de,isInitialLoading:U,isLoading:U,data:v,dataUpdatedAt:c.dataUpdatedAt,error:O,errorUpdatedAt:C,failureCount:c.fetchFailureCount,failureReason:c.fetchFailureReason,errorUpdateCount:c.errorUpdateCount,isFetched:c.dataUpdateCount>0||c.errorUpdateCount>0,isFetchedAfterMount:c.dataUpdateCount>g.dataUpdateCount||c.errorUpdateCount>g.errorUpdateCount,isFetching:be,isRefetching:be&&!b,isLoadingError:de&&c.dataUpdatedAt===0,isPaused:$==="paused",isPlaceholderData:pe,isRefetchError:de&&c.dataUpdatedAt!==0,isStale:Ve(t,e),refetch:this.refetch},selectError:y,select:T,selectResult:D}});this.options=t,M(this,q,e),this.bindMethods(),M(this,j,this.setOptions(t));const n=o(this,j);M(this,z,n.state);const{result:i,select:u}=this.getObserverResultFromQuery({query:n,options:this.options,prevResult:{options:this.options,state:n.state}});M(this,A,{state:n.state,options:t,result:i,select:u})}bindMethods(){this.refetch=this.refetch.bind(this)}setOptions(e){const t=this.options;if(this.options=o(this,q).defaultQueryOptions(e),x(this.options,t)||o(this,q).getQueryCache().notify({type:"observerOptionsUpdated",query:o(this,j),observer:this}),typeof this.options.enabled<"u"&&typeof this.options.enabled!="boolean")throw new Error("Expected enabled to be a boolean");const n=this.buildQuery(this.options);return n!==o(this,j)&&(M(this,z,n.state),M(this,j,n)),this.queryUpdateSubject.next({options:this.options,query:n}),n}buildQuery(e){const t=o(this,q).getQueryCache().build(o(this,q),e);return!t.options.queryFn&&this.options.queryFn&&t.setOptions(e),t}getCurrentResult(){return this.getObserverResultFromQuery({options:this.options,prevResult:o(this,A),query:o(this,j)}).result}getCurrentQuery(){return o(this,j)}getOptimisticResult(e){const t=this.buildQuery(e),n=this.getObserverResultFromQuery({query:t,options:e,optimisticResult:!0,prevResult:o(this,A)});return Gt(this,n.result)&&this.updateResult({query:t,...n}),n.result}updateResult({query:e,result:t,selectError:n,select:i,selectResult:u}){o(this,A).state=e.state,o(this,A).result=t,o(this,A).selectResult=u,n!==void 0&&(o(this,A).selectError=n),i!==void 0&&(o(this,A).select=i),o(this,A).options=this.options,e.state.data!==void 0&&M(this,Z,e),o(this,q).getQueryCache().notify({query:o(this,j),type:"observerResultsUpdated"})}async refetch({...e}={}){return await this.fetch({...e})}async fetch(e){const t=this.buildQuery(this.options);t!==o(this,j)&&(M(this,j,t),M(this,z,t.state),this.queryUpdateSubject.next({options:this.options,query:t}));const n={...e,cancelRefetch:(e==null?void 0:e.cancelRefetch)??!0};o(this,j).fetch(this.options,n).catch(r.noop),o(this,ie).next({query:t,fetchOptions:n}),await t.getFetchResultAsPromise();const{result:i}=this.getObserverResultFromQuery({query:t,options:this.options,prevResult:o(this,A)});return i}subscribe(e){const t=this.observe().subscribe(e);return()=>{t.unsubscribe()}}observe(){const e=o(this,j),t=this.queryUpdateSubject.pipe(r.map(({query:a})=>a),r.startWith(o(this,j)),r.distinctUntilChanged()),n=this.queryUpdateSubject.pipe(r.startWith({query:o(this,j),options:this.options}),r.pairwise(),r.tap(([{options:a,query:l},{options:h,query:f}])=>{_e(f,l,h,a)&&this.fetch().catch(r.noop)}),r.ignoreElements()),i=t.pipe(r.switchMap(a=>a.observe(this)),r.ignoreElements());return r.merge(i,n,t.pipe(r.switchMap(a=>{const l=this.options,h=this.queryUpdateSubject.pipe(r.startWith({query:a,options:l}),r.filter(y=>y.query===a),r.map(y=>y.options),r.distinctUntilChanged(),r.shareReplay(1)),f=o(this,ie).pipe(r.filter(y=>y.query===a)),c=a.state$.pipe(Yt,r.switchMap(y=>this.options.staleTime===1/0?r.NEVER:(this.options.staleTime??0)<=0?r.of(y).pipe(r.delay(1)):r.timer(this.options.staleTime??1)),r.takeWhile(()=>this.options.enabled??!0)),b=(y,T)=>{const D=l.notifyOnChangeProps,V=typeof D=="function"?D():D;return(Array.isArray(V)?V.length===0?()=>!0:(pe,be)=>{const Te=Be(pe,V),ge=Be(be,V);return x(Te,ge)}:x)(y,T)},E=f.pipe(r.switchMap(()=>a.state$),ot),d=h.pipe(r.map(({refetchInterval:y,refetchIntervalInBackground:T})=>({refetchInterval:(typeof y=="function"?y(o(this,j)):y)??!1,refetchIntervalInBackground:T})),r.distinctUntilChanged(x),r.switchMap(({refetchInterval:y,refetchIntervalInBackground:T})=>y?r.interval(y).pipe(r.tap(()=>{(T||ve.isFocused())&&this.fetch({cancelRefetch:!1}).catch(r.noop)})):r.NEVER),r.ignoreElements()),p=h.pipe(r.map(({enabled:y})=>y??!0),r.distinctUntilChanged()),g=p.pipe(r.filter(y=>!y),r.map(()=>a.state)),C=p.pipe(r.filter(y=>y),r.switchMap(()=>ve.focusRegained$),r.withLatestFrom(h),r.tap(([,y])=>{qt(a,y)&&this.fetch({cancelRefetch:!1}).catch(r.noop)}),r.ignoreElements()),$=g.pipe(r.map(()=>a.state)),O=y=>y.pipe(r.withLatestFrom(h),r.map(([,T])=>{const D=this.getObserverResultFromQuery({query:a,options:T,prevResult:o(this,A)});return this.updateResult({query:a,...D}),D.result})),v=r.merge($,E,a.state$,c).pipe(O,r.distinctUntilChanged(x),r.distinctUntilChanged(b));return r.merge(d,C,v)})).pipe(Pe(a=>M(this,ae,a)),r.tap({subscribe:()=>{We(e,this.options)&&this.fetch().catch(r.noop)}})))}destroy(){}}q=new WeakMap,j=new WeakMap,ie=new WeakMap,z=new WeakMap,A=new WeakMap,Z=new WeakMap,ae=new WeakMap;function Gt(s,e){return!x(s.getCurrentResult(),e)}const lt=we.createContext(!1),Jt=()=>we.useContext(lt);lt.Provider;function Xt(){let s=!1;return{clearReset:()=>{s=!1},reset:()=>{s=!0},isReset:()=>s}}const Zt=we.createContext(Xt()),er=()=>we.useContext(Zt);function tr(s,e){return typeof s=="function"?s(...e):!!s}const rr=({result:s,errorResetBoundary:e,throwOnError:t,query:n})=>s.isError&&!e.isReset()&&!s.isFetching&&n&&tr(t,[s.error,n]);function ht(s,e,t){if(process.env.NODE_ENV!=="production"&&(typeof s!="object"||Array.isArray(s)))throw new Error('Bad argument type. Starting with v5, only the "Object" form is allowed when calling query related functions. Please use the error stack to find the culprit call. More info here: https://tanstack.com/query/latest/docs/react/guides/migrating-to-v5#supports-a-single-signature-one-object');const n=ke(t),i=Jt(),u=er(),a=n.defaultQueryOptions(s);a._optimisticResults=i?"isRestoring":"optimistic";const[l]=S.useState(()=>new e(n,a)),h=$e(()=>l.observe()),f=Q(l.getOptimisticResult(a)),c=f.current;fe(()=>h.current.pipe(r.filter(E=>!x(E,f.current))),[]),S.useEffect(()=>{l.setOptions(a)},[a,l]);const b=c.error;if(b&&rr({result:c,errorResetBoundary:u,throwOnError:a.throwOnError,query:n.getQueryCache().get(a.queryHash)}))throw b;return f.current}function sr(s,e){return ht(s,ct,e)}function nr(s,e){return ht({refetchOnMount:"idle",refetchOnReconnect:!1,refetchInterval:!1,refetchOnWindowFocus:!1,...s},ct,e)}function ir(s,e,t=[]){const n=e!=null&&!Array.isArray(e)?e:{},i=n.retry??!0,u=Q(n.onError??(h=>{console.error(h)})),a=S.useCallback(()=>R(s),t),l=S.useCallback(()=>a().pipe(r.catchError(h=>{throw u.current(h),h}),i?r.retry():r.identity),[a,i,u]);Re(l,t)}const ft=()=>s=>r.merge(r.of({isPaused:!0}),_.backToOnline$.pipe(r.mergeMap(()=>r.merge(r.of({isPaused:!1}),s)))),ar=s=>{let e=0;return s.pipe(r.catchError(t=>(e++,e<=1&&!_.isOnline()?r.merge(r.of({failureCount:e,failureReason:t}),r.timer(1).pipe(r.mergeMap(()=>r.throwError(()=>t).pipe(ft())))):r.throwError(()=>t))))},ur=({variables:s,state:e,options:t})=>{const n=e.isPaused,i=async()=>await Promise.reject(new Error("No mutationFn found")),u=t.mutationFn??i,a=R(()=>{var d;return((d=t.onMutate)==null?void 0:d.call(t,s))??void 0}),l=r.of(e.context),h=r.iif(()=>n,l,a).pipe(r.shareReplay(1)),f=(d,p,g)=>R(()=>{var $;return($=t.onError)==null?void 0:$.call(t,d,s,p)}).pipe(r.catchError(()=>r.of(d)),r.map(()=>({failureCount:g,error:d,failureReason:d,context:p,status:"error"}))),c=h.pipe(r.switchMap(d=>{const g=(typeof u=="function"?R(()=>u(s)):u).pipe(r.share()),C=g.pipe(r.isEmpty(),r.tap(O=>{if(O)throw new Error("Mutation completed without any emission (EMPTY)")}),r.ignoreElements()),$=r.merge(g,C).pipe(r.map(O=>({result:{data:O},error:null,context:d})),ar,Ae({...t,retry:(O,U)=>{const v=t.retry??0;return typeof v=="function"?v(O,U):typeof v=="boolean"?v:O<v},caughtError:(O,U)=>r.of({failureCount:O,failureReason:U}),catchError:(O,U)=>f(U,d,O).pipe(r.map(v=>({...v,result:void 0})))}),r.takeWhile(({result:O,error:U})=>(O==null?void 0:O.data)===void 0&&U===void 0,!0));return _.isOnline()||t.networkMode==="offlineFirst"||t.networkMode==="always"?$:$.pipe(ft())})),b=r.of({...e,variables:s,status:"pending",isPaused:!1,failureCount:0,failureReason:null,submittedAt:e.submittedAt??new Date().getTime()});return r.merge(b,h.pipe(r.map(d=>({context:d}))),c.pipe(r.switchMap(({result:d,error:p,...g})=>{if(!d&&!p)return r.of({...g});const C=p?r.of(null):R(()=>{var v;return(v=t.onSuccess)==null?void 0:v.call(t,d==null?void 0:d.data,s,g.context)}),O=R(()=>{var v;return(v=t.onSettled)==null?void 0:v.call(t,d==null?void 0:d.data,p,s,g.context)}).pipe(r.catchError(v=>d?r.of(d):r.of(v)));return r.concat(C,O).pipe(r.toArray(),r.map(()=>p?{error:p,data:void 0,variables:s,...g}:{status:"success",error:p,data:d==null?void 0:d.data,variables:s,failureCount:0,failureReason:null,...g}),r.catchError(v=>f(v,g.context,0).pipe(r.map(y=>({...y,data:void 0})))))}))).pipe(r.scan((d,p)=>({...d,...p,data:p.data??d.data,error:p.error??d.error}),X()))};var ue,W,ee;class or{constructor({options:e,mutationCache:t,state:n}){w(this,ue,new r.BehaviorSubject(0));w(this,W,new r.Subject);w(this,ee,new r.Subject);m(this,"state",X());m(this,"state$");m(this,"options");m(this,"observerCount$",o(this,ue).asObservable());m(this,"cancelled$",o(this,W).asObservable());this.options=e,this.state=n??this.state;const i=o(this,W).pipe(r.filter(()=>this.state.status==="pending"),r.map(()=>({status:"idle"}))),u=o(this,ee).pipe(r.switchMap(l=>ur({options:{...this.options,onMutate:h=>{const f=R(()=>{var d,p;return(p=(d=t.config).onMutate)==null?void 0:p.call(d,h,this)}),b=R(()=>{var d,p;return(p=(d=this.options).onMutate)==null?void 0:p.call(d,h)});return f.pipe(r.mergeMap(()=>b))},onError:(h,f,c)=>{const b=R(()=>{var d,p;return(p=(d=t.config).onError)==null?void 0:p.call(d,h,f,c,this)}),E=R(()=>{var d,p;return(p=(d=this.options).onError)==null?void 0:p.call(d,h,f,c)});return r.concat(b,E).pipe(r.toArray())},onSettled:(h,f,c,b)=>{const E=R(()=>{var p,g;return(g=(p=t.config).onSettled)==null?void 0:g.call(p,h,f,c,b,this)}),d=R(()=>{var p,g;return(g=(p=this.options).onSettled)==null?void 0:g.call(p,h,f,c,b)});return r.concat(E,d).pipe(r.toArray())},onSuccess:(h,f,c)=>{const b=R(()=>{var d,p;return(p=(d=t.config).onSuccess)==null?void 0:p.call(d,h,f,c,this)}),E=R(()=>{var d,p;return(p=(d=this.options).onSuccess)==null?void 0:p.call(d,h,f,c)});return r.concat(b,E).pipe(r.toArray())}},state:this.state,variables:l}).pipe(r.takeUntil(o(this,W))))),a=r.merge(i,u);this.state$=a.pipe(r.startWith(this.state),r.scan((l,h)=>({...l,...h}),this.state),nt,r.tap(l=>{this.state=l}),r.shareReplay(1),Pe(l=>{o(this,ue).next(l)}))}get meta(){return this.options.meta}setOptions(e){this.options={...this.options,...e}}execute(e){return o(this,ee).next(e),o(this,ee).complete(),this.state$.pipe(ne)}continue(){return this.execute(this.state.variables)}cancel(){o(this,W).next(),o(this,W).complete()}}ue=new WeakMap,W=new WeakMap,ee=new WeakMap;const Ge=({mutationKey:s,status:e,predicate:t,exact:n=!0}={})=>u=>n&&s!==void 0&&u.options.mutationKey!==void 0&&!ye(u.options.mutationKey,s,{exact:n})||!n&&s!==void 0&&u.options.mutationKey!==void 0&&!ye(u.options.mutationKey,s,{exact:n})||e&&u.state.status!==e?!1:t?t(u):!0;class dt{constructor(){m(this,"entriesSubject",new r.BehaviorSubject([]));m(this,"changeSubject",new r.Subject);m(this,"entries$",this.entriesSubject.pipe(r.share()));m(this,"added$",this.changeSubject.pipe(r.filter(({type:e})=>e==="added"),r.map(({entity:e})=>e),r.share()));m(this,"removed$",this.changeSubject.pipe(r.filter(({type:e})=>e==="removed"),r.map(({entity:e})=>e),r.share()));m(this,"stateChange$",r.merge(this.entriesSubject.pipe(r.first(),r.mergeMap(e=>r.from(e))),this.added$).pipe(r.mergeMap(e=>e.state$.pipe(r.map(()=>e),r.takeUntil(this.removed$.pipe(r.filter(t=>t===e))))),r.share()))}getValues(){return this.entriesSubject.getValue()}remove(e){this.entriesSubject.next(this.entriesSubject.getValue().filter(t=>e!==t)),this.changeSubject.next({type:"removed",entity:e})}add(e){this.entriesSubject.next([...this.entriesSubject.getValue(),e]),this.changeSubject.next({type:"added",entity:e})}find(e){return this.entriesSubject.getValue().find(e)}}var k;class pt{constructor(e={}){w(this,k,new dt);this.config=e}build(e,t,n){const i=new or({mutationCache:this,options:e.defaultMutationOptions(t),state:n});return i.state$.pipe(r.filter(({status:u})=>u==="success"||u==="error"),r.switchMap(()=>i.observerCount$.pipe(r.filter(u=>u<=1),r.take(1))),r.switchMap(()=>r.timer(i.options.gcTime??5*60*1e3)),r.take(1)).subscribe({complete:()=>{this.remove(i)}}),o(this,k).add(i),i}getAll(){return this.findAll()}remove(e){const t=o(this,k).getValues().find(n=>n===e);t==null||t.cancel(),o(this,k).remove(e)}find(e){const t={exact:!0,...e},n=Ge(t);return o(this,k).getValues().find(i=>n(i))}findAll(e={}){const t={exact:!0,...e},n=Ge(t);return o(this,k).getValues().filter(i=>n(i)).map(i=>i)}observe(){return o(this,k).stateChange$.pipe(r.startWith())}subscribe(e){const t=r.merge(o(this,k).added$.pipe(r.tap(n=>{e({type:"added",mutation:n})})),o(this,k).removed$.pipe(r.tap(n=>{e({type:"removed",mutation:n})})),o(this,k).stateChange$.pipe(r.tap(n=>{e({type:"updated",action:{...n.state,type:"success"},mutation:n})}))).subscribe();return()=>{t.unsubscribe()}}resumePausedMutations(){const e=this.findAll({predicate:n=>n.state.isPaused});if(!e.length)return r.EMPTY;const t=e.map(n=>n.continue());return r.combineLatest(t)}clear(){this.getAll().forEach(e=>{this.remove(e)})}}k=new WeakMap;function cr(s){const e=typeof s.initialData=="function"?s.initialData():s.initialData,t=typeof e<"u",n=t?typeof s.initialDataUpdatedAt=="function"?s.initialDataUpdatedAt():s.initialDataUpdatedAt:0;return{data:e,dataUpdateCount:0,dataUpdatedAt:t?n??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:t?"success":"pending",fetchStatus:"idle"}}const lr=s=>r.defer(()=>ve.isFocused()?s:ve.focusRegained$.pipe(r.mergeMap(()=>s))),hr=s=>{let e=0;return t=>{const n=_.backToOnline$.pipe(r.mergeMap(()=>r.merge(r.of({fetchStatus:"fetching"}),t)));return r.defer(()=>(e++,!_.isOnline()&&s.networkMode==="offlineFirst"&&e>1?r.merge(r.of({fetchStatus:"paused"}),n):!_.isOnline()&&s.networkMode!=="always"&&s.networkMode!=="offlineFirst"?r.merge(r.of({fetchStatus:"paused"}),n):t))}},fr=s=>e=>{const t=new r.Subject,n=t.pipe(r.first(),r.delay(1),r.mergeMap(()=>s.pipe(r.filter(i=>i===0))));return e.pipe(r.tap(()=>{t.next()}),r.takeUntil(n))},dr=s=>{const e=async()=>await Promise.reject(new Error("No query found"));process.env.NODE_ENV!=="production"&&s.queryFn===Fe&&console.error(`Attempted to invoke queryFn when set to skipToken. This is likely a configuration error. Query hash: '${s.queryHash}'`);let t=!1;const n=s.queryFn&&s.queryFn!==Fe?s.queryFn:e,i=new AbortController,u={meta:s.meta,queryKey:s.queryKey};(c=>{Object.defineProperty(c,"signal",{enumerable:!0,get:()=>(s.onSignalConsumed(),i.signal)})})(u);const h=(typeof n=="function"?R(()=>n(u)):n).pipe(fr(s.observers$),r.tap({complete:()=>{t=!0}}),r.map(c=>({data:c})),hr(s),Ae({...s,retryAfter:()=>r.of(!0).pipe(lr),catchError:(c,b)=>r.of({status:"error",fetchStatus:"idle",fetchFailureCount:c,fetchFailureReason:b,error:b}),caughtError:(c,b)=>r.of({fetchFailureCount:c,fetchFailureReason:b})}),r.mergeMap(c=>"data"in c?r.of({...c,status:"success",fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null,dataUpdatedAt:new Date().getTime()}).pipe(r.delay(1),r.map(b=>t?b:{...b,fetchStatus:"fetching"})):r.of(c)),r.endWith({fetchStatus:"idle"}),r.share()),f=r.of({status:"pending",fetchStatus:_.isOnline()?"fetching":"paused"});return{state$:r.merge(f,h).pipe(r.share()),abortController:i}};class pr{constructor(e){m(this,"revert");m(this,"silent");this.revert=e==null?void 0:e.revert,this.silent=e==null?void 0:e.silent}}const br={backgroundColor:"transparent",color:"inherit"};function bt(s){const e={namespaces:[{name:"@reactjrx",style:{backgroundColor:"#d02f4e",color:"white"}}],namespace(t,n){const i=bt();return i.namespaces.push({name:t,style:n??br}),i},printNamespaces(){return{namespaces:e.namespaces.map(({name:t})=>`%c ${t} %c`).join(" "),styles:e.namespaces.reduce((t,{style:n})=>(t.push(`background-color: ${n.backgroundColor}; color: ${n.color};`),t.push("background-color: transparent; color: inherit;"),t),[])}},print(t,...n){return e},printWithoutNamespace(t,...n){return e},log(...t){return e.print("log",...t)},warn(...t){return e.print("warn",...t)},error(...t){return e.print("error",...t)},group(...t){return e.print("group",...t)},groupEnd(){return e}};return e}const gr=bt();var oe,Y;class mr{constructor(e){m(this,"queryKey");m(this,"queryHash");m(this,"gcTime");m(this,"options");w(this,oe);w(this,Y);m(this,"state");m(this,"executeSubject",new r.Subject);m(this,"cancelSubject",new r.Subject);m(this,"setDataSubject",new r.Subject);m(this,"invalidatedSubject",new r.Subject);m(this,"resetSubject",new r.Subject);m(this,"destroySubject",new r.Subject);m(this,"observersSubject",new r.BehaviorSubject([]));m(this,"abortSignalConsumed",!1);m(this,"observerCount$",this.observersSubject.asObservable().pipe(r.map(e=>e.length)));m(this,"observers$",this.observersSubject.asObservable());m(this,"state$");M(this,oe,e.defaultOptions),this.options=this.setOptions(e.options),this.queryKey=e.queryKey,this.queryHash=e.queryHash,M(this,Y,e.state??cr(this.options)),this.state=o(this,Y),this.gcTime=this.updateGcTime(this.options.gcTime),this.state$=r.merge(this.resetSubject.pipe(r.map(()=>({command:"reset",state:o(this,Y)}))),this.invalidatedSubject.pipe(r.filter(()=>!this.state.isInvalidated),r.map(()=>({command:"invalidate",state:{isInvalidated:!0}}))),this.cancelSubject.pipe(r.filter(()=>!(this.state.error&&this.state.status==="error")),r.map(t=>({command:"cancel",state:{status:t!=null&&t.revert?this.state.status:"error",fetchStatus:"idle",error:new pr(t)}}))),this.executeSubject.pipe(r.mergeMap(()=>{let t=!1;const n=this.executeSubject.pipe(r.filter(f=>(f==null?void 0:f.cancelRefetch)!==!1)),i=this.observers$.pipe(r.pairwise(),r.tap(([f,c])=>{c.length===0&&f.length>0?t=!0:t=!1}),r.ignoreElements()),{state$:u,abortController:a}=dr({...this.options,observers$:this.observerCount$,queryKey:this.queryKey,retry:(f,c)=>{const b=this.options.retry??!0;return typeof b=="function"?b(f,c):typeof b=="boolean"?b:f<b},retryAfterDelay:()=>!t,onSignalConsumed:()=>{this.abortSignalConsumed=!0}}),l=this.observerCount$.pipe(r.filter(f=>f===0&&this.abortSignalConsumed),r.tap(()=>{this.cancelSubject.next({revert:!0})})),h=r.merge(this.cancelSubject,n,this.resetSubject,l).pipe(r.tap(()=>{this.abortSignalConsumed&&a.abort()}));return r.merge(u,i).pipe(r.map(f=>({command:"execute",state:f})),r.takeUntil(h))})),this.setDataSubject.pipe(r.map(({data:t,options:n})=>({command:"setData",state:{status:"success",data:t,dataUpdatedAt:(n==null?void 0:n.updatedAt)!==void 0?n.updatedAt:new Date().getTime()}})))).pipe(_t({initialState:this.state,getOptions:()=>this.options,getState:()=>this.state}),r.startWith(o(this,Y)),r.distinctUntilChanged(x),r.tap(t=>{this.state=t}),r.catchError(t=>{throw gr.error(t),t}),r.takeUntil(this.destroySubject),r.shareReplay({bufferSize:1,refCount:!1}))}setOptions(e){return this.options={...o(this,oe),...e},this.updateGcTime(this.options.gcTime),this.options}get meta(){return this.options.meta}get success$(){return this.state$.pipe(r.map(({data:e,status:t})=>({data:e,status:t})),r.distinctUntilChanged(x),r.filter(({status:e})=>e==="success"))}get error$(){return this.state$.pipe(r.map(({error:e,status:t})=>({error:e,status:t})),r.distinctUntilChanged(x),r.filter(({status:e})=>e==="error"))}get settled$(){return this.state$.pipe(r.map(({status:e})=>({status:e})),r.distinctUntilChanged(x),r.filter(({status:e})=>e==="success"||e==="error"))}observe(e){return this.state$.pipe(r.tap({subscribe:()=>{this.observersSubject.next([e,...this.observersSubject.getValue()])},unsubscribe:()=>{this.observersSubject.next(this.observersSubject.getValue().filter(n=>n!==e))}}))}getObserversCount(){return this.observersSubject.getValue().length}updateGcTime(e){return this.gcTime=Math.max(this.gcTime||0,e??(J?1/0:5*60*1e3)),this.gcTime}isActive(){return this.observersSubject.getValue().some(e=>e.options.enabled!==!1)}isDisabled(){return this.getObserversCount()>0&&!this.isActive()}isStale(){return this.state.isInvalidated||!this.state.dataUpdatedAt||this.observersSubject.getValue().some(e=>e.getCurrentResult().isStale)}isStaleByTime(e=0){return this.state.isInvalidated||!this.state.dataUpdatedAt||!Lt(this.state.dataUpdatedAt,e)}async getFetchResultAsPromise(){return await new Promise((e,t)=>{this.state$.pipe(ot,r.last()).subscribe({error:t,next:n=>{n.error?t(n.error):e(n.data)}})})}async fetch(e,t){const{cancelRefetch:n}=t??{};return this.state.fetchStatus!=="idle"&&!(!!this.state.dataUpdatedAt&&n)?await this.getFetchResultAsPromise():(e&&this.setOptions(e),this.executeSubject.next(t),await this.getFetchResultAsPromise())}setData(e,t){const n=Se(this.state.data,e,this.options);return this.setDataSubject.next({data:n,options:t}),n}invalidate(){this.invalidatedSubject.next()}async cancel(e){this.cancelSubject.next(e)}destroy(){this.destroySubject.next(),this.destroySubject.complete(),this.executeSubject.complete()}reset(){this.resetSubject.next()}}oe=new WeakMap,Y=new WeakMap;var ce,N;class gt{constructor(e={}){w(this,ce,new r.Subject);w(this,N,new dt);this.config=e}mount(){}unmount(){}notify(e){o(this,ce).next(e)}observeIsFetching(e){return o(this,N).stateChange$.pipe(r.startWith(),r.map(()=>this.findAll({...e,fetchStatus:"fetching"}).length),r.distinctUntilChanged())}getAll(){return[...o(this,N).getValues()]}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(n=>Ye(e,n)):t}build(e,t,n){const i=t.queryKey??[Qe()],u=t.queryHash??Ie(i,t);let a=this.get(u);return a||(a=new mr({cache:this,queryKey:i,queryHash:u,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(i)}),this.add(a)),a}add(e){if(!o(this,N).find(t=>t.queryHash===e.queryHash)){o(this,N).add(e);const t=e.observerCount$.pipe(r.filter(n=>n<1),r.take(1));e.success$.subscribe(()=>{var n,i;(i=(n=this.config).onSuccess)==null||i.call(n,e.state.data,e)}),e.error$.subscribe(()=>{var n,i;(i=(n=this.config).onError)==null||i.call(n,e.state.error,e)}),e.settled$.subscribe(()=>{var n,i;(i=(n=this.config).onSettled)==null||i.call(n,e.state.data,e.state.error,e)}),e.state$.pipe(Bt,r.switchMap(n=>n?t.pipe(r.switchMap(()=>e.gcTime===1/0?r.NEVER:(setTimeout(r.noop,e.gcTime),r.timer(e.gcTime)))):r.NEVER),r.take(1)).subscribe({complete:()=>{this.remove(e)}})}}get(e){return o(this,N).find(t=>t.queryHash===e)}find(e){const t={exact:!0,...e};return this.getAll().find(n=>Ye(t,n))}subscribe(e){const t=r.merge(o(this,ce).pipe(r.tap(e))).subscribe();return()=>{t.unsubscribe()}}remove(e){const t=o(this,N).find(n=>n===e);t&&(e.destroy(),t===e&&o(this,N).remove(e))}clear(){}}ce=new WeakMap,N=new WeakMap;var G,F,le,he,te;class yr{constructor({mutationCache:e,queryCache:t,defaultOptions:n}={}){w(this,G);w(this,F);w(this,le,new Map);w(this,he,new Map);w(this,te);M(this,G,e??new pt),M(this,F,t??new gt),M(this,te,n??{})}mount(){}unmount(){}getMutationCache(){return o(this,G)}getQueryCache(){return o(this,F)}defaultMutationOptions(e){return{...o(this,te).mutations,...(e==null?void 0:e.mutationKey)&&this.getMutationDefaults(e.mutationKey),...e}}defaultQueryOptions(e){if(e._defaulted)return e;const t={...o(this,te).queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Ie(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.enabled!==!0&&t.queryFn===Fe&&(t.enabled=!1),t}async fetchQuery(e){const t=this.defaultQueryOptions(e);typeof t.retry>"u"&&(t.retry=!1);const n=o(this,F).build(this,t);return n.isStaleByTime(t.staleTime)?await n.fetch(t):await Promise.resolve(n.state.data)}async prefetchQuery(e){await this.fetchQuery(e).then(r.noop).catch(r.noop)}async resetQueries(e,t){const n=o(this,F),i={type:"active",...e};n.findAll(e).forEach(u=>{u.reset()}),await this.refetchQueries(i,t)}async refetchQueries(e={},t){const n={...t,cancelRefetch:(t==null?void 0:t.cancelRefetch)??!0},i=o(this,F).findAll(e).filter(u=>!u.isDisabled()).map(async u=>{let a=u.fetch(void 0,n);return n.throwOnError||(a=a.catch(r.noop)),u.state.fetchStatus==="paused"?void 0:await a});await Promise.all(i).then(r.noop)}getQueryData(e){var n;const t=this.defaultQueryOptions({queryKey:e});return(n=o(this,F).get(t.queryHash))==null?void 0:n.state.data}setQueryData(e,t,n){const i=this.defaultQueryOptions({queryKey:e}),u=o(this,F).get(i.queryHash),a=u==null?void 0:u.state.data,l=Wt(t,a);if(l!==void 0)return o(this,F).build(this,i).setData(l,{...n,manual:!0})}getMutationDefaults(e){const t=[...o(this,le).values()];let n={};return t.forEach(i=>{ye(e,i.mutationKey)&&(n={...n,...i.defaultOptions})}),n}getQueryState(e){var t;return(t=o(this,F).find({queryKey:e}))==null?void 0:t.state}setMutationDefaults(e,t){o(this,le).set(re(e),{mutationKey:e,defaultOptions:t})}setQueryDefaults(e,t){o(this,he).set(re(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...o(this,he).values()];let n={};return t.forEach(i=>{Ee(e,i.queryKey)&&(n={...n,...i.defaultOptions})}),n}removeQueries(e){const t=o(this,F);t.findAll(e).forEach(n=>{t.remove(n)})}async cancelQueries(e={},t={}){const n={revert:!0,...t},i=o(this,F).findAll(e).map(async u=>{await u.cancel(n)});await Promise.all(i).then(r.noop).catch(r.noop)}async invalidateQueries(e={},t={}){if(o(this,F).findAll(e).forEach(i=>{i.invalidate()}),e.refetchType==="none"){await Promise.resolve();return}const n={...e,type:e.refetchType??e.type??"active"};await this.refetchQueries(n,t)}async resumePausedMutations(){return await r.lastValueFrom(o(this,G).resumePausedMutations())}isFetching(e){return o(this,F).findAll({...e,fetchStatus:"fetching"}).length}clear(){o(this,F).clear(),o(this,G).clear()}}G=new WeakMap,F=new WeakMap,le=new WeakMap,he=new WeakMap,te=new WeakMap;exports.MutationCache=pt;exports.QueryCache=gt;exports.QueryClient=yr;exports.QueryClientProvider=Vt;exports.SIGNAL_RESET=Je;exports.arrayEqual=At;exports.createLocalStorageAdapter=et;exports.createLocalforageAdapter=Et;exports.exponentialBackoffDelay=st;exports.getDelay=rt;exports.isDefined=me;exports.isPromiseLike=je;exports.isServer=J;exports.retryBackoff=Ae;exports.signal=Xe;exports.useBehaviorSubject=Ue;exports.useEffectOnce=tt;exports.useForeverQuery=nr;exports.useLiveRef=Q;exports.useMount=Ut;exports.useMutation=Tt;exports.useObservableState=wt;exports.useObserve=fe;exports.useObserveCallback=Ot;exports.usePersistSignals=Rt;exports.useQuery=sr;exports.useQueryClient=ke;exports.useSignal=$t;exports.useSignalValue=Ze;exports.useSubject=xe;exports.useSubscribe=Re;exports.useSubscribeEffect=ir;exports.useUnmountObservable=xt;
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __typeError = (msg) => {
4
+ throw TypeError(msg);
5
+ };
6
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
7
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
8
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
9
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
10
+ var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
11
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
12
+ var _trigger$, _mutationRunner, _currentMutationSubject, _visibility$, _focusedSubject, _client, _currentQuery, _fetchSubject, _currentQueryInitialState, _lastResult, _lastQueryWithDefinedData, _observers, _observerCount, _cancelSubject, _executeSubject, _store, _defaultOptions, _initialState, _notifySubject, _store2, _mutationCache, _queryCache, _mutationDefaults, _queryDefaults, _defaultOptions2;
13
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
14
+ const React = require("react");
15
+ const rxjs = require("rxjs");
16
+ const operators = require("rxjs/operators");
17
+ const jsxRuntime = require("react/jsx-runtime");
18
+ function _interopNamespaceDefault(e) {
19
+ const n = Object.create(null, { [Symbol.toStringTag]: { value: "Module" } });
20
+ if (e) {
21
+ for (const k in e) {
22
+ if (k !== "default") {
23
+ const d = Object.getOwnPropertyDescriptor(e, k);
24
+ Object.defineProperty(n, k, d.get ? d : {
25
+ enumerable: true,
26
+ get: () => e[k]
27
+ });
28
+ }
29
+ }
30
+ }
31
+ n.default = e;
32
+ return Object.freeze(n);
33
+ }
34
+ const React__namespace = /* @__PURE__ */ _interopNamespaceDefault(React);
35
+ const useLiveRef = (value) => {
36
+ const ref = React.useRef(value);
37
+ React.useMemo(() => {
38
+ ref.current = value;
39
+ }, [value]);
40
+ return ref;
41
+ };
42
+ function isPromiseLike(value) {
43
+ return value instanceof Promise || value && typeof value === "object" && "then" in value && typeof value.then === "function" && "catch" in value && value.catch === "function";
44
+ }
45
+ function makeObservable(something) {
46
+ if (rxjs.isObservable(something)) return something;
47
+ if (isPromiseLike(something)) return rxjs.from(something);
48
+ if (typeof something !== "function") return rxjs.of(something);
49
+ const somethingAsFunction = something;
50
+ return rxjs.defer(() => {
51
+ const result = somethingAsFunction();
52
+ if (isPromiseLike(result)) {
53
+ return rxjs.from(result);
54
+ }
55
+ if (rxjs.isObservable(result)) {
56
+ return result;
57
+ }
58
+ return rxjs.of(result);
59
+ });
60
+ }
61
+ function useObserve(source$, optionsOrDeps, maybeDeps) {
62
+ const options = optionsOrDeps != null && !Array.isArray(optionsOrDeps) ? optionsOrDeps : {
63
+ defaultValue: void 0,
64
+ unsubscribeOnUnmount: true,
65
+ compareFn: void 0
66
+ };
67
+ const deps = !maybeDeps && Array.isArray(optionsOrDeps) ? optionsOrDeps : typeof source$ === "function" ? maybeDeps ?? [] : [source$];
68
+ const valueRef = React.useRef(
69
+ "getValue" in source$ && typeof source$.getValue === "function" ? source$.getValue() : options.defaultValue
70
+ );
71
+ const sourceRef = useLiveRef(source$);
72
+ const optionsRef = useLiveRef(options);
73
+ const subscribe = React.useCallback(
74
+ (next) => {
75
+ const source = sourceRef.current;
76
+ const sub = makeObservable(source).pipe(
77
+ optionsRef.current.defaultValue ? rxjs.startWith(optionsRef.current.defaultValue) : rxjs.identity,
78
+ /**
79
+ * @important there is already a Object.is comparison in place from react
80
+ * so we only add a custom compareFn if provided
81
+ */
82
+ optionsRef.current.compareFn ? rxjs.distinctUntilChanged((a, b) => {
83
+ if (a === void 0 || b === void 0) return false;
84
+ return optionsRef.current.compareFn(a, b);
85
+ }) : rxjs.identity,
86
+ rxjs.tap((value) => {
87
+ valueRef.current = value;
88
+ }),
89
+ rxjs.catchError((error) => {
90
+ console.error(error);
91
+ return rxjs.EMPTY;
92
+ })
93
+ ).subscribe(next);
94
+ return () => {
95
+ if (optionsRef.current.unsubscribeOnUnmount === false) return;
96
+ sub.unsubscribe();
97
+ };
98
+ },
99
+ // eslint-disable-next-line react-hooks/exhaustive-deps
100
+ [...deps]
101
+ );
102
+ const getSnapshot = React.useCallback(() => {
103
+ return valueRef.current;
104
+ }, []);
105
+ const result = React.useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
106
+ return result;
107
+ }
108
+ function useSubscribe(source, deps = []) {
109
+ const sourceRef = useLiveRef(source);
110
+ React.useEffect(() => {
111
+ const sub = makeObservable(sourceRef.current).pipe(
112
+ rxjs.catchError((error) => {
113
+ console.error(error);
114
+ return rxjs.EMPTY;
115
+ })
116
+ ).subscribe();
117
+ return () => {
118
+ sub.unsubscribe();
119
+ };
120
+ }, [
121
+ // eslint-disable-next-line react-hooks/exhaustive-deps
122
+ ...deps,
123
+ sourceRef
124
+ ]);
125
+ }
126
+ const useConstant = (fn) => {
127
+ const ref = React.useRef();
128
+ if (!ref.current) {
129
+ ref.current = fn();
130
+ }
131
+ React.useEffect(() => {
132
+ if (process.env.NODE_ENV === "development") ;
133
+ }, []);
134
+ return ref;
135
+ };
136
+ const useSubject = ({
137
+ onBeforeComplete,
138
+ completeOnUnmount = true
139
+ } = {}) => {
140
+ const subject = useConstant(() => new rxjs.Subject());
141
+ const completed = React.useRef(false);
142
+ const onBeforeCompleteRef = useLiveRef(onBeforeComplete);
143
+ const completeOnUnmountRef = useLiveRef(completeOnUnmount);
144
+ React.useEffect(() => {
145
+ if (completed.current) {
146
+ subject.current = new rxjs.Subject();
147
+ completed.current = false;
148
+ }
149
+ return () => {
150
+ if (!completeOnUnmountRef.current) {
151
+ completed.current = true;
152
+ return;
153
+ }
154
+ if (!completed.current) {
155
+ if (onBeforeCompleteRef.current != null) onBeforeCompleteRef.current();
156
+ subject.current.complete();
157
+ completed.current = true;
158
+ }
159
+ };
160
+ }, [completeOnUnmountRef, onBeforeCompleteRef, subject]);
161
+ return subject;
162
+ };
163
+ const useObserveCallback = () => {
164
+ const subject = useSubject();
165
+ const event$ = useLiveRef(subject.current.asObservable());
166
+ const trigger = React.useCallback(
167
+ (arg) => {
168
+ subject.current.next(arg);
169
+ },
170
+ // eslint-disable-next-line react-hooks/exhaustive-deps
171
+ []
172
+ );
173
+ return [event$.current, trigger];
174
+ };
175
+ const useBehaviorSubject = (state) => {
176
+ const subject = useConstant(() => new rxjs.BehaviorSubject(state));
177
+ const completed = React.useRef(false);
178
+ const stateRef = React.useRef(state);
179
+ React.useEffect(() => {
180
+ if (completed.current) {
181
+ subject.current = new rxjs.BehaviorSubject(stateRef.current);
182
+ completed.current = false;
183
+ }
184
+ return () => {
185
+ if (!completed.current) {
186
+ subject.current.complete();
187
+ completed.current = true;
188
+ }
189
+ };
190
+ }, [subject]);
191
+ return subject;
192
+ };
193
+ const useObservableState = (defaultValue) => {
194
+ const subject = useBehaviorSubject(defaultValue);
195
+ const subject$ = useLiveRef(subject.current.asObservable());
196
+ const setState = React.useCallback(
197
+ (value) => {
198
+ subject.current.next(value);
199
+ },
200
+ // eslint-disable-next-line react-hooks/exhaustive-deps
201
+ [subject.current]
202
+ );
203
+ return [subject$.current, setState, subject.current.getValue()];
204
+ };
205
+ const SIGNAL_RESET = Symbol("SIGNAL_RESET");
206
+ function signal(config = {}) {
207
+ const normalizedConfig = {
208
+ default: config.default,
209
+ key: config.key
210
+ };
211
+ const { default: defaultValue } = normalizedConfig ?? {};
212
+ const subject = new rxjs.BehaviorSubject(defaultValue);
213
+ const setValue = (arg) => {
214
+ const update = (value) => {
215
+ if ("key" in config) {
216
+ console.log(
217
+ "[reactjrx][state][signal]:",
218
+ `Value update for signal ${config.key}`,
219
+ { prev: subject.getValue(), curr: value }
220
+ );
221
+ }
222
+ subject.next(value);
223
+ };
224
+ if (typeof arg === "function") {
225
+ const change = arg(subject.getValue());
226
+ if (change === subject.getValue()) return;
227
+ return update(change);
228
+ }
229
+ if (arg === SIGNAL_RESET) {
230
+ if (defaultValue === subject.getValue()) return;
231
+ return update(defaultValue ?? void 0);
232
+ }
233
+ if (arg === subject.getValue()) return;
234
+ return update(arg);
235
+ };
236
+ const getValue = () => subject.getValue();
237
+ if ("get" in config) {
238
+ const getter = (signal2) => {
239
+ signal2.subject.pipe(rxjs.skip(1), rxjs.first()).subscribe(() => {
240
+ var _a;
241
+ const newValue = (_a = config.get) == null ? void 0 : _a.call(config, getter);
242
+ setValue(newValue);
243
+ });
244
+ return signal2.getValue();
245
+ };
246
+ const defaultValue2 = config.get(getter);
247
+ setValue(defaultValue2);
248
+ return {
249
+ getValue,
250
+ config,
251
+ subject
252
+ };
253
+ }
254
+ return {
255
+ setValue,
256
+ getValue,
257
+ config: normalizedConfig,
258
+ subject
259
+ };
260
+ }
261
+ function useSignalValue(signal2, selector) {
262
+ const defaultSelector = () => signal2.getValue();
263
+ const selectorOrDefault = selector ?? defaultSelector;
264
+ return useObserve(
265
+ () => {
266
+ const observed$ = signal2.subject.pipe(
267
+ rxjs.map((value) => {
268
+ const selectedValue = selectorOrDefault(value);
269
+ return selectedValue;
270
+ }),
271
+ rxjs.distinctUntilChanged()
272
+ );
273
+ return observed$;
274
+ },
275
+ {
276
+ defaultValue: selectorOrDefault(signal2.getValue())
277
+ },
278
+ []
279
+ );
280
+ }
281
+ const useSignal = (config) => {
282
+ const [stateSignal] = React.useState(() => signal(config));
283
+ const value = useSignalValue(stateSignal);
284
+ return [value, stateSignal];
285
+ };
286
+ const createLocalforageAdapter = (forage) => ({
287
+ getItem: async (key) => {
288
+ const serializedValue = await forage.getItem(key);
289
+ if (!serializedValue) return void 0;
290
+ return JSON.parse(serializedValue);
291
+ },
292
+ setItem: async (key, value) => {
293
+ await forage.setItem(key, JSON.stringify(value));
294
+ },
295
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
296
+ removeItem: async (_) => {
297
+ },
298
+ clear: async () => {
299
+ }
300
+ });
301
+ const normalizeStore = (store) => {
302
+ if (!store || typeof store !== "object") {
303
+ return void 0;
304
+ }
305
+ return store;
306
+ };
307
+ const createSharedStoreAdapter = ({
308
+ adapter,
309
+ key
310
+ }) => ({
311
+ clear: async () => {
312
+ return await adapter.removeItem(key);
313
+ },
314
+ removeItem: async (keyToDelete) => {
315
+ const unsafeStore = await adapter.getItem(key);
316
+ const { [keyToDelete]: toRemove, ...rest } = normalizeStore(unsafeStore) ?? {};
317
+ await adapter.setItem(key, rest);
318
+ },
319
+ getItem: async (itemKey) => {
320
+ const unsafeStore = await adapter.getItem(key);
321
+ const store = normalizeStore(unsafeStore) ?? {};
322
+ if (itemKey in store) {
323
+ return store[itemKey];
324
+ }
325
+ return void 0;
326
+ },
327
+ setItem: async (itemKey, value) => {
328
+ const unsafeStore = await adapter.getItem(key);
329
+ const store = normalizeStore(unsafeStore) ?? {};
330
+ await adapter.setItem(key, { ...store, [itemKey]: value });
331
+ }
332
+ });
333
+ const createLocalStorageAdapter = ({
334
+ key
335
+ } = {}) => {
336
+ if (key) {
337
+ return createSharedStoreAdapter({
338
+ adapter: createLocalStorageAdapter(),
339
+ key
340
+ });
341
+ }
342
+ return {
343
+ clear: async () => {
344
+ localStorage.clear();
345
+ },
346
+ removeItem: async (key2) => {
347
+ localStorage.removeItem(key2);
348
+ },
349
+ getItem: async (key2) => {
350
+ const serializedValue = localStorage.getItem(key2);
351
+ if (!serializedValue) return void 0;
352
+ return JSON.parse(serializedValue);
353
+ },
354
+ setItem: async (key2, value) => {
355
+ localStorage.setItem(key2, JSON.stringify(value));
356
+ }
357
+ };
358
+ };
359
+ const useLiveBehaviorSubject = (state) => {
360
+ const subject = useBehaviorSubject(state);
361
+ React.useEffect(() => {
362
+ subject.current.next(state);
363
+ }, [state, subject]);
364
+ return subject;
365
+ };
366
+ const IDENTIFIER_PERSISTANCE_KEY = "__reactjrx";
367
+ const getNormalizedPersistanceValue = (unknownValue) => {
368
+ if (typeof unknownValue === "object" && unknownValue !== null && IDENTIFIER_PERSISTANCE_KEY in unknownValue && unknownValue[IDENTIFIER_PERSISTANCE_KEY] === IDENTIFIER_PERSISTANCE_KEY) {
369
+ return unknownValue;
370
+ }
371
+ return void 0;
372
+ };
373
+ const persistValue = ({
374
+ adapter,
375
+ config
376
+ }) => {
377
+ const { signal: signal2, version } = config;
378
+ const state = signal2.getValue();
379
+ const value = {
380
+ value: state,
381
+ [IDENTIFIER_PERSISTANCE_KEY]: IDENTIFIER_PERSISTANCE_KEY,
382
+ migrationVersion: version
383
+ };
384
+ if (process.env.NODE_ENV === "development") {
385
+ console.log(
386
+ "[reactjrx][state][persistance]:",
387
+ `Persist value`,
388
+ value,
389
+ `for signal ${signal2.config.key}`
390
+ );
391
+ }
392
+ return rxjs.from(adapter.setItem(signal2.config.key, value)).pipe(
393
+ rxjs.catchError((e) => {
394
+ console.error(e);
395
+ return rxjs.of(null);
396
+ })
397
+ );
398
+ };
399
+ function hydrateValueToSignal({
400
+ adapter,
401
+ config
402
+ }) {
403
+ const { hydrate = ({ value }) => value, signal: signal2, version } = config;
404
+ return rxjs.from(adapter.getItem(signal2.config.key)).pipe(
405
+ rxjs.switchMap((value) => {
406
+ const normalizedValue = getNormalizedPersistanceValue(value);
407
+ if (!normalizedValue) return rxjs.of(value);
408
+ const storedVersionIsInvalid = typeof normalizedValue.migrationVersion !== "number";
409
+ const signalVersionIsSuperior = normalizedValue.migrationVersion !== void 0 && version > normalizedValue.migrationVersion;
410
+ if (storedVersionIsInvalid || signalVersionIsSuperior || normalizedValue.value === void 0) {
411
+ return rxjs.of(value);
412
+ }
413
+ const correctVersionValue = normalizedValue.value;
414
+ if (process.env.NODE_ENV === "development") {
415
+ console.log(
416
+ "[reactjrx][state][persistance]:",
417
+ `Hydrate value`,
418
+ normalizedValue,
419
+ `for signal ${signal2.config.key}`
420
+ );
421
+ }
422
+ signal2.setValue(hydrate({ value: correctVersionValue, version }));
423
+ return rxjs.of(value);
424
+ })
425
+ );
426
+ }
427
+ function persistSignals({
428
+ entries = [],
429
+ onHydrated,
430
+ adapter
431
+ }) {
432
+ const signalsHydrated$ = entries.length === 0 ? rxjs.of([]) : rxjs.zip(
433
+ ...entries.map(
434
+ (config) => hydrateValueToSignal({
435
+ adapter,
436
+ config
437
+ })
438
+ )
439
+ );
440
+ const isHydrated$ = signalsHydrated$.pipe(
441
+ rxjs.tap(onHydrated),
442
+ rxjs.catchError((error) => {
443
+ console.error("Unable to hydrate", error);
444
+ return rxjs.EMPTY;
445
+ }),
446
+ rxjs.share()
447
+ );
448
+ const persisted$ = isHydrated$.pipe(
449
+ rxjs.switchMap(
450
+ () => rxjs.merge(
451
+ ...entries.map(
452
+ (config) => config.signal.subject.pipe(
453
+ rxjs.throttleTime(500, rxjs.asyncScheduler, {
454
+ trailing: true
455
+ }),
456
+ rxjs.switchMap(
457
+ () => rxjs.from(
458
+ persistValue({
459
+ adapter,
460
+ config
461
+ })
462
+ )
463
+ )
464
+ )
465
+ )
466
+ )
467
+ )
468
+ );
469
+ return rxjs.merge(
470
+ isHydrated$.pipe(
471
+ rxjs.map(() => ({
472
+ type: "hydrated"
473
+ }))
474
+ ),
475
+ persisted$.pipe(
476
+ rxjs.map(() => ({
477
+ type: "persisted"
478
+ }))
479
+ )
480
+ );
481
+ }
482
+ function shallowEqual(objA, objB) {
483
+ if (objA === null || objA === void 0 || objB === void 0) {
484
+ return objA === objB;
485
+ }
486
+ if (typeof objA !== "object" || typeof objB !== "object") {
487
+ return objA === objB;
488
+ }
489
+ if (objA.constructor !== (objB == null ? void 0 : objB.constructor)) {
490
+ return false;
491
+ }
492
+ const keysA = Object.keys(objA);
493
+ const keysB = Object.keys(objB);
494
+ if (keysA.length !== keysB.length) {
495
+ return false;
496
+ }
497
+ for (const key of keysA) {
498
+ if (!objB.hasOwnProperty(key) || objA[key] !== objB[key]) {
499
+ return false;
500
+ }
501
+ }
502
+ return true;
503
+ }
504
+ function usePersistSignals({
505
+ entries = [],
506
+ onHydrated,
507
+ adapter
508
+ }) {
509
+ const onHydratedRef = useLiveRef(onHydrated);
510
+ const adapterSubject = useLiveBehaviorSubject(adapter);
511
+ const entriesSubject = useLiveBehaviorSubject(entries);
512
+ return useObserve(
513
+ () => {
514
+ const persistence$ = adapterSubject.current.pipe(
515
+ rxjs.switchMap((adapter2) => {
516
+ if (!adapter2) return rxjs.of({ type: "reset" });
517
+ return rxjs.merge(
518
+ rxjs.of({ type: "reset" }),
519
+ entriesSubject.current.pipe(
520
+ rxjs.concatMap(
521
+ (entries2) => persistSignals({
522
+ adapter: adapter2,
523
+ entries: entries2,
524
+ onHydrated: () => {
525
+ var _a;
526
+ (_a = onHydratedRef.current) == null ? void 0 : _a.call(onHydratedRef);
527
+ }
528
+ })
529
+ )
530
+ )
531
+ );
532
+ })
533
+ );
534
+ return persistence$.pipe(
535
+ rxjs.scan(
536
+ (acc, event) => {
537
+ if (event.type === "reset") return { isHydrated: false };
538
+ if (event.type === "hydrated") return { isHydrated: true };
539
+ return acc;
540
+ },
541
+ { isHydrated: false }
542
+ )
543
+ );
544
+ },
545
+ { defaultValue: { isHydrated: false }, compareFn: shallowEqual },
546
+ [adapterSubject, entriesSubject]
547
+ );
548
+ }
549
+ const useUnmountObservable = () => {
550
+ const subject = useSubject({
551
+ onBeforeComplete: () => {
552
+ subject.current.next();
553
+ }
554
+ });
555
+ return subject;
556
+ };
557
+ const useEffectOnce = (effect) => {
558
+ React.useEffect(effect, []);
559
+ };
560
+ const useMount = (fn) => {
561
+ useEffectOnce(() => {
562
+ fn();
563
+ });
564
+ };
565
+ function getDelay(backoffDelay, maxInterval) {
566
+ return Math.min(backoffDelay, maxInterval);
567
+ }
568
+ function exponentialBackoffDelay(iteration, initialInterval) {
569
+ return Math.pow(2, iteration) * initialInterval;
570
+ }
571
+ function retryBackoff(config) {
572
+ const {
573
+ retry,
574
+ retryDelay,
575
+ retryAfterDelay,
576
+ retryAfter = () => rxjs.of(true)
577
+ } = config;
578
+ const maxRetries = typeof retry !== "function" ? retry === false ? 0 : retry === true ? Infinity : retry ?? Infinity : Infinity;
579
+ const shouldRetry = typeof retry === "function" ? (
580
+ // ? (attempt: number, error: TError) => of(retry(attempt, error))
581
+ retry
582
+ ) : () => true;
583
+ const initialInterval = typeof retryDelay === "number" ? retryDelay : 100;
584
+ const normalizedConfig = {
585
+ shouldRetry,
586
+ ...config
587
+ };
588
+ const {
589
+ maxInterval = Infinity,
590
+ resetOnSuccess = false,
591
+ backoffDelay = exponentialBackoffDelay
592
+ } = normalizedConfig;
593
+ return (source) => rxjs.defer(() => {
594
+ let caughtErrors = 0;
595
+ const shouldRetryFn = (attempt, error) => attempt < maxRetries ? shouldRetry(attempt, error) : false;
596
+ return source.pipe(
597
+ operators.catchError((error) => {
598
+ var _a;
599
+ caughtErrors++;
600
+ if (!shouldRetryFn(caughtErrors - 1, error)) throw error;
601
+ const caughtErrorResult$ = (_a = config.caughtError) == null ? void 0 : _a.call(config, caughtErrors, error);
602
+ if (!caughtErrorResult$) throw error;
603
+ return caughtErrorResult$.pipe(
604
+ operators.mergeMap(
605
+ (source2) => rxjs.merge(
606
+ rxjs.of(source2),
607
+ rxjs.throwError(() => error)
608
+ )
609
+ )
610
+ );
611
+ }),
612
+ operators.retryWhen((errors) => {
613
+ return errors.pipe(
614
+ operators.concatMap((error) => {
615
+ const attempt = caughtErrors - 1;
616
+ return retryAfter().pipe(
617
+ operators.first(),
618
+ operators.mergeMap(
619
+ () => shouldRetryFn(attempt, error) ? rxjs.timer(
620
+ getDelay(
621
+ backoffDelay(attempt, initialInterval),
622
+ maxInterval
623
+ )
624
+ ).pipe(
625
+ operators.mergeMap((timer2) => {
626
+ if (retryAfterDelay && !retryAfterDelay(attempt, error))
627
+ return rxjs.throwError(() => error);
628
+ return rxjs.of(timer2);
629
+ })
630
+ ) : rxjs.throwError(() => error)
631
+ )
632
+ );
633
+ })
634
+ );
635
+ }),
636
+ operators.catchError((e) => {
637
+ if (config.catchError) {
638
+ return config.catchError(caughtErrors, e);
639
+ }
640
+ throw e;
641
+ }),
642
+ operators.tap(() => {
643
+ if (resetOnSuccess) {
644
+ caughtErrors = 0;
645
+ }
646
+ })
647
+ );
648
+ });
649
+ }
650
+ function isDefined(arg) {
651
+ return arg !== null && arg !== void 0;
652
+ }
653
+ const arrayEqual = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);
654
+ const isServer = typeof window === "undefined" || "Deno" in window;
655
+ function hasObjectPrototype(o) {
656
+ return Object.prototype.toString.call(o) === "[object Object]";
657
+ }
658
+ function isPlainObject(o) {
659
+ if (!hasObjectPrototype(o)) {
660
+ return false;
661
+ }
662
+ const ctor = o.constructor;
663
+ if (typeof ctor === "undefined") {
664
+ return true;
665
+ }
666
+ const prot = ctor.prototype;
667
+ if (!hasObjectPrototype(prot)) {
668
+ return false;
669
+ }
670
+ if (!prot.hasOwnProperty("isPrototypeOf")) {
671
+ return false;
672
+ }
673
+ return true;
674
+ }
675
+ const hashKey = (queryKey) => {
676
+ return JSON.stringify(
677
+ queryKey,
678
+ (_, val) => isPlainObject(val) ? Object.keys(val).sort().reduce((result, key) => {
679
+ result[key] = val[key];
680
+ return result;
681
+ }, {}) : val
682
+ );
683
+ };
684
+ const nanoid = (size = 21) => crypto.getRandomValues(new Uint8Array(size)).reduce((id, byte) => {
685
+ byte &= 63;
686
+ if (byte < 36) {
687
+ id += byte.toString(36);
688
+ } else if (byte < 62) {
689
+ id += (byte - 26).toString(36).toUpperCase();
690
+ } else if (byte > 62) {
691
+ id += "-";
692
+ } else {
693
+ id += "_";
694
+ }
695
+ return id;
696
+ }, "");
697
+ const getDefaultMutationState = () => ({
698
+ context: void 0,
699
+ data: void 0,
700
+ error: null,
701
+ status: "idle",
702
+ submittedAt: 0,
703
+ variables: void 0,
704
+ failureCount: 0,
705
+ failureReason: null,
706
+ isPaused: false
707
+ });
708
+ function trackSubscriptions(onCountUpdate) {
709
+ let count = 0;
710
+ return function refCountOperatorFunction(source) {
711
+ return new rxjs.Observable((observer) => {
712
+ count++;
713
+ const sub = source.subscribe(observer);
714
+ onCountUpdate(count);
715
+ return () => {
716
+ count--;
717
+ onCountUpdate(count);
718
+ sub.unsubscribe();
719
+ };
720
+ });
721
+ };
722
+ }
723
+ const observeUntilFinished = (source) => source.pipe(
724
+ rxjs.takeWhile(
725
+ (result) => result.status !== "error" && result.status !== "success",
726
+ true
727
+ )
728
+ );
729
+ class MutationRunner {
730
+ constructor({
731
+ __queryFinalizeHook
732
+ } = {}) {
733
+ __privateAdd(this, _trigger$, new rxjs.Subject());
734
+ __publicField(this, "state$");
735
+ const refCountSubject = new rxjs.BehaviorSubject(0);
736
+ const noMoreObservers$ = refCountSubject.pipe(
737
+ rxjs.filter((value) => value === 0)
738
+ );
739
+ this.state$ = __privateGet(this, _trigger$).pipe(
740
+ rxjs.concatMap(({ args, mutation, options }) => {
741
+ const mapOperator = options.mapOperator ?? "merge";
742
+ const mergeTrigger$ = __privateGet(this, _trigger$).pipe(
743
+ rxjs.filter(() => mapOperator === "merge")
744
+ );
745
+ const switchTrigger$ = __privateGet(this, _trigger$).pipe(
746
+ rxjs.filter(() => mapOperator === "switch"),
747
+ rxjs.tap(() => {
748
+ mutation.cancel();
749
+ })
750
+ );
751
+ const deferExecution$ = rxjs.defer(() => {
752
+ mutation.execute(args);
753
+ return rxjs.EMPTY;
754
+ });
755
+ const resetState$ = mutation.state$.pipe(
756
+ observeUntilFinished,
757
+ rxjs.last(),
758
+ rxjs.mergeMap(() => mutation.state$),
759
+ rxjs.takeUntil(__privateGet(this, _trigger$))
760
+ );
761
+ const stateUntilFinished$ = mutation.state$.pipe(
762
+ observeUntilFinished,
763
+ rxjs.skip(1)
764
+ );
765
+ const observeUntil$ = rxjs.merge(
766
+ noMoreObservers$,
767
+ mergeTrigger$,
768
+ switchTrigger$,
769
+ mutation.cancelled$
770
+ );
771
+ return rxjs.merge(
772
+ stateUntilFinished$,
773
+ resetState$,
774
+ /**
775
+ * We defer execution so that we return at least
776
+ * the current state first (same mechanism is used for query)
777
+ */
778
+ deferExecution$
779
+ ).pipe(
780
+ rxjs.map((state) => ({ state, mutation })),
781
+ __queryFinalizeHook ?? rxjs.identity,
782
+ rxjs.takeUntil(observeUntil$)
783
+ );
784
+ }),
785
+ rxjs.shareReplay({
786
+ refCount: true,
787
+ bufferSize: 1
788
+ }),
789
+ trackSubscriptions((count) => {
790
+ refCountSubject.next(count);
791
+ })
792
+ );
793
+ }
794
+ trigger({
795
+ args,
796
+ options,
797
+ mutation
798
+ }) {
799
+ __privateGet(this, _trigger$).next({ args, options, mutation });
800
+ }
801
+ }
802
+ _trigger$ = new WeakMap();
803
+ function partialMatchKey(a, b) {
804
+ if (a === b) {
805
+ return true;
806
+ }
807
+ if (typeof a !== typeof b) {
808
+ return false;
809
+ }
810
+ if (a && b && typeof a === "object" && typeof b === "object") {
811
+ return !Object.keys(b).some((key) => !partialMatchKey(a[key], b[key]));
812
+ }
813
+ return false;
814
+ }
815
+ const matchKey = (keyA, keyB, { exact = false } = {}) => {
816
+ if (exact) {
817
+ return hashKey(keyA) === hashKey(keyB);
818
+ }
819
+ return partialMatchKey(keyA, keyB);
820
+ };
821
+ const distinctUntilStateChanged = (stream) => stream.pipe(
822
+ rxjs.distinctUntilChanged(
823
+ ({ data: prevData, ...prev }, { data: currData, ...curr }) => shallowEqual(prev, curr) && shallowEqual(prevData, currData)
824
+ )
825
+ );
826
+ class MutationObserver {
827
+ constructor(client, options = {}, mutationRunner) {
828
+ __privateAdd(this, _mutationRunner);
829
+ __privateAdd(this, _currentMutationSubject, new rxjs.BehaviorSubject(void 0));
830
+ /**
831
+ * @important
832
+ * Used to maintain persistance to latest mutation. This ensure
833
+ * - mutation does not get garbage collected
834
+ * - mutation mutate options are run on finish
835
+ */
836
+ __publicField(this, "observed$");
837
+ __publicField(this, "getObserverResultFromState", (state) => {
838
+ return {
839
+ ...getDefaultMutationState(),
840
+ ...state,
841
+ isSuccess: state.status === "success",
842
+ isPending: state.status === "pending",
843
+ isIdle: state.status === "idle",
844
+ isError: state.status === "error",
845
+ // eslint-disable-next-line @typescript-eslint/unbound-method
846
+ mutate: this.mutate,
847
+ // eslint-disable-next-line @typescript-eslint/unbound-method
848
+ reset: this.reset
849
+ };
850
+ });
851
+ var _a;
852
+ this.client = client;
853
+ this.options = options;
854
+ this.options.mutationKey = ((_a = this.options) == null ? void 0 : _a.mutationKey) ?? [nanoid()];
855
+ __privateSet(this, _mutationRunner, mutationRunner ?? new MutationRunner(this.options));
856
+ this.mutate = this.mutate.bind(this);
857
+ this.reset = this.reset.bind(this);
858
+ __privateGet(this, _currentMutationSubject).pipe(
859
+ rxjs.filter(isDefined),
860
+ rxjs.mergeMap(
861
+ (mutation) => __privateGet(this, _mutationRunner).state$.pipe(
862
+ rxjs.takeUntil(
863
+ mutation.mutation.state$.pipe(observeUntilFinished, rxjs.last())
864
+ )
865
+ )
866
+ )
867
+ ).subscribe();
868
+ this.observed$ = __privateGet(this, _currentMutationSubject).pipe(
869
+ rxjs.switchMap((maybeMutation) => {
870
+ return (maybeMutation == null ? void 0 : maybeMutation.mutation.state$.pipe(
871
+ // last(),
872
+ rxjs.map((state) => ({
873
+ state,
874
+ options: maybeMutation.options
875
+ }))
876
+ )) ?? rxjs.EMPTY;
877
+ }),
878
+ rxjs.tap(({ state, options: options2 }) => {
879
+ if (state.status === "error") {
880
+ (options2 == null ? void 0 : options2.onError) && (options2 == null ? void 0 : options2.onError(
881
+ state.error,
882
+ state.variables,
883
+ state.context
884
+ ));
885
+ (options2 == null ? void 0 : options2.onSettled) && (options2 == null ? void 0 : options2.onSettled(
886
+ state.data,
887
+ state.error,
888
+ state.variables,
889
+ state.context
890
+ ));
891
+ }
892
+ if (state.status === "success") {
893
+ (options2 == null ? void 0 : options2.onSuccess) && (options2 == null ? void 0 : options2.onSuccess(
894
+ state.data,
895
+ state.variables,
896
+ state.context
897
+ ));
898
+ (options2 == null ? void 0 : options2.onSettled) && (options2 == null ? void 0 : options2.onSettled(
899
+ state.data,
900
+ state.error,
901
+ state.variables,
902
+ state.context
903
+ ));
904
+ }
905
+ }),
906
+ rxjs.ignoreElements()
907
+ );
908
+ }
909
+ setOptions(options) {
910
+ var _a;
911
+ const prevOptions = this.options;
912
+ this.options = this.client.defaultMutationOptions({
913
+ mutationKey: this.options.mutationKey,
914
+ ...options
915
+ });
916
+ const currentMutation = (_a = __privateGet(this, _currentMutationSubject).getValue()) == null ? void 0 : _a.mutation;
917
+ if (this.options.mutationKey && prevOptions.mutationKey && !matchKey(this.options.mutationKey, prevOptions.mutationKey, {
918
+ exact: true
919
+ })) {
920
+ this.reset();
921
+ } else {
922
+ currentMutation == null ? void 0 : currentMutation.setOptions(this.options);
923
+ }
924
+ }
925
+ observe() {
926
+ var _a;
927
+ const lastValue = this.getObserverResultFromState(
928
+ ((_a = __privateGet(this, _currentMutationSubject).getValue()) == null ? void 0 : _a.mutation.state) ?? getDefaultMutationState()
929
+ );
930
+ const mutationResult$ = __privateGet(this, _mutationRunner).state$.pipe(
931
+ rxjs.distinctUntilChanged(
932
+ ({ mutation: prevMutation, state: { data: prevData, ...prev } }, { mutation: currentMutation, state: { data: currData, ...curr } }) => prevMutation === currentMutation && shallowEqual(prev, curr) && shallowEqual(prevData, currData)
933
+ ),
934
+ rxjs.map(({ state }) => state),
935
+ rxjs.scan((acc, current) => {
936
+ return {
937
+ ...acc,
938
+ ...current,
939
+ ...current.status === "pending" && {
940
+ data: current.data ?? acc.data
941
+ },
942
+ ...current.status === "pending" && {
943
+ error: current.error ?? acc.error
944
+ }
945
+ };
946
+ }),
947
+ rxjs.map((state) => this.getObserverResultFromState(state))
948
+ );
949
+ const defaultStateOnMutationCancel$ = __privateGet(this, _currentMutationSubject).pipe(
950
+ rxjs.filter(isDefined),
951
+ rxjs.switchMap((mutation) => mutation.mutation.cancelled$),
952
+ rxjs.map(() => this.getObserverResultFromState(getDefaultMutationState()))
953
+ );
954
+ const result$ = rxjs.merge(
955
+ this.observed$,
956
+ mutationResult$,
957
+ defaultStateOnMutationCancel$
958
+ ).pipe(distinctUntilStateChanged);
959
+ return { result$, lastValue };
960
+ }
961
+ /**
962
+ * @important
963
+ * Compliance react-query only
964
+ */
965
+ subscribe(subscription) {
966
+ const sub = this.observe().result$.subscribe((result) => {
967
+ subscription(result);
968
+ });
969
+ return () => {
970
+ sub.unsubscribe();
971
+ };
972
+ }
973
+ async mutate(variables, options = {}) {
974
+ const mutation = this.client.getMutationCache().build(this.client, this.options);
975
+ __privateGet(this, _currentMutationSubject).next({ mutation, options });
976
+ __privateGet(this, _mutationRunner).trigger({
977
+ args: variables,
978
+ options: this.options,
979
+ mutation
980
+ });
981
+ return await new Promise((resolve, reject) => {
982
+ mutation.state$.pipe(observeUntilFinished, rxjs.last()).subscribe({
983
+ error: (error) => {
984
+ reject(error);
985
+ },
986
+ next: (data) => {
987
+ if (data.error) {
988
+ reject(data.error);
989
+ } else {
990
+ resolve(data.data);
991
+ }
992
+ }
993
+ });
994
+ });
995
+ }
996
+ getCurrentResult() {
997
+ var _a;
998
+ const mutation = this.client.getMutationCache().find({ exact: true, mutationKey: (_a = this.options) == null ? void 0 : _a.mutationKey });
999
+ return this.getObserverResultFromState(
1000
+ (mutation == null ? void 0 : mutation.state) ?? getDefaultMutationState()
1001
+ );
1002
+ }
1003
+ reset() {
1004
+ const { mutation } = __privateGet(this, _currentMutationSubject).getValue() ?? {};
1005
+ __privateGet(this, _currentMutationSubject).next(void 0);
1006
+ mutation == null ? void 0 : mutation.cancel();
1007
+ }
1008
+ }
1009
+ _mutationRunner = new WeakMap();
1010
+ _currentMutationSubject = new WeakMap();
1011
+ const Context = React.createContext(void 0);
1012
+ const ClientEffect = ({ client }) => {
1013
+ React.useEffect(() => {
1014
+ client.mount();
1015
+ return () => {
1016
+ client.unmount();
1017
+ };
1018
+ }, [client]);
1019
+ return null;
1020
+ };
1021
+ const QueryClientProvider = React.memo(
1022
+ ({ children, client }) => {
1023
+ const value = React.useMemo(() => client, [client]);
1024
+ return /* @__PURE__ */ jsxRuntime.jsxs(Context.Provider, { value, children: [
1025
+ /* @__PURE__ */ jsxRuntime.jsx(ClientEffect, { client }),
1026
+ children
1027
+ ] });
1028
+ }
1029
+ );
1030
+ const useQueryClient = (queryClient) => {
1031
+ const client = React.useContext(Context);
1032
+ if (queryClient) {
1033
+ return queryClient;
1034
+ }
1035
+ if (!client) {
1036
+ throw new Error("No QueryClient set, use QueryClientProvider to set one");
1037
+ }
1038
+ return client;
1039
+ };
1040
+ function noop() {
1041
+ }
1042
+ function useMutation(options, queryClient) {
1043
+ const defaultQueryClient = useQueryClient(queryClient);
1044
+ const optionsRef = useLiveRef(options);
1045
+ const defaultKey = useConstant(() => [nanoid()]);
1046
+ const serializedKey = hashKey(options.mutationKey ?? defaultKey.current);
1047
+ const [mutationObserver] = React.useState(
1048
+ () => new MutationObserver(
1049
+ defaultQueryClient,
1050
+ options
1051
+ )
1052
+ );
1053
+ React.useEffect(() => {
1054
+ mutationObserver.setOptions(options);
1055
+ }, [mutationObserver, options]);
1056
+ const observedMutation = React.useMemo(() => {
1057
+ return mutationObserver.observe();
1058
+ }, [serializedKey, mutationObserver]);
1059
+ const result = useObserve(observedMutation.result$) ?? observedMutation.lastValue;
1060
+ const mutate = React.useCallback(
1061
+ (variables, mutateOptions) => {
1062
+ mutationObserver.mutate(variables, mutateOptions).catch(noop);
1063
+ },
1064
+ [mutationObserver]
1065
+ );
1066
+ React.useEffect(() => {
1067
+ return () => {
1068
+ if (optionsRef.current.cancelOnUnMount) {
1069
+ mutationObserver.reset();
1070
+ }
1071
+ };
1072
+ }, [mutationObserver, optionsRef]);
1073
+ return { ...result, mutate, mutateAsync: result.mutate };
1074
+ }
1075
+ function emitToSubject(subject) {
1076
+ return (source$) => source$.pipe(
1077
+ operators.tap((value) => {
1078
+ subject.next(value);
1079
+ })
1080
+ );
1081
+ }
1082
+ class OnlineManager {
1083
+ constructor() {
1084
+ __publicField(this, "isOnlineSubject", new rxjs.BehaviorSubject(true));
1085
+ __publicField(this, "online$", this.isOnlineSubject.pipe(rxjs.distinctUntilChanged()));
1086
+ __publicField(this, "backToOnline$", this.online$.pipe(
1087
+ rxjs.filter((isOnline) => isOnline),
1088
+ rxjs.first()
1089
+ ));
1090
+ rxjs.merge(
1091
+ isServer ? rxjs.EMPTY : rxjs.fromEvent(window, "offline").pipe(rxjs.map(() => false)),
1092
+ isServer ? rxjs.EMPTY : rxjs.fromEvent(window, "online").pipe(rxjs.map(() => true))
1093
+ ).pipe(emitToSubject(this.isOnlineSubject)).subscribe();
1094
+ }
1095
+ isOnline() {
1096
+ return this.isOnlineSubject.getValue();
1097
+ }
1098
+ setOnline(online) {
1099
+ const changed = this.isOnlineSubject.getValue() !== online;
1100
+ if (changed) {
1101
+ this.isOnlineSubject.next(online);
1102
+ }
1103
+ }
1104
+ }
1105
+ const onlineManager = new OnlineManager();
1106
+ function isStale(query, options) {
1107
+ return query.isStaleByTime(options.staleTime);
1108
+ }
1109
+ function shouldLoadOnMount(query, options) {
1110
+ return options.enabled !== false && !query.state.dataUpdatedAt && !(query.state.status === "error" && options.retryOnMount === false) && query.state.fetchStatus !== "fetching";
1111
+ }
1112
+ function shouldFetchOnMount(query, options) {
1113
+ return shouldLoadOnMount(query, options) || query.state.dataUpdatedAt > 0 && shouldFetchOn(query, options, options.refetchOnMount);
1114
+ }
1115
+ function shouldFetchOptionally(query, prevQuery, options, prevOptions) {
1116
+ return query.state.fetchStatus !== "fetching" && options.enabled !== false && (query !== prevQuery || prevOptions.enabled === false) && (!options.suspense || query.state.status !== "error") && isStale(query, options);
1117
+ }
1118
+ function shouldFetchOnWindowFocus(query, options) {
1119
+ return shouldFetchOn(query, options, options.refetchOnWindowFocus);
1120
+ }
1121
+ function shouldFetchOn(query, options, field) {
1122
+ if (options.enabled !== false) {
1123
+ const value = typeof field === "function" ? field(query) : field;
1124
+ if (value === "idle") {
1125
+ return query.state.fetchStatus === "idle";
1126
+ }
1127
+ return value === "always" || value !== false && isStale(query, options);
1128
+ }
1129
+ return false;
1130
+ }
1131
+ function canFetch(networkMode) {
1132
+ return (networkMode ?? "online") === "online" ? onlineManager.isOnline() : true;
1133
+ }
1134
+ function filterObjectByKey(obj, keys) {
1135
+ return keys.reduce(
1136
+ (acc, key) => {
1137
+ if (key in obj) {
1138
+ return { ...acc, [key]: obj[key] };
1139
+ }
1140
+ return acc;
1141
+ },
1142
+ {}
1143
+ );
1144
+ }
1145
+ function isPlainArray(value) {
1146
+ return Array.isArray(value) && value.length === Object.keys(value).length;
1147
+ }
1148
+ function replaceEqualDeep(a, b) {
1149
+ if (a === b) {
1150
+ return a;
1151
+ }
1152
+ const array = isPlainArray(a) && isPlainArray(b);
1153
+ if (array || isPlainObject(a) && isPlainObject(b)) {
1154
+ const aItems = array ? a : Object.keys(a);
1155
+ const aSize = aItems.length;
1156
+ const bItems = array ? b : Object.keys(b);
1157
+ const bSize = bItems.length;
1158
+ const copy = array ? [] : {};
1159
+ let equalItems = 0;
1160
+ for (let i = 0; i < bSize; i++) {
1161
+ const key = array ? i : bItems[i];
1162
+ if (!array && a[key] === void 0 && b[key] === void 0 && aItems.includes(key)) {
1163
+ copy[key] = void 0;
1164
+ equalItems++;
1165
+ } else {
1166
+ copy[key] = replaceEqualDeep(a[key], b[key]);
1167
+ if (copy[key] === a[key] && a[key] !== void 0) {
1168
+ equalItems++;
1169
+ }
1170
+ }
1171
+ }
1172
+ return aSize === bSize && equalItems === aSize ? a : copy;
1173
+ }
1174
+ return b;
1175
+ }
1176
+ function hashQueryKeyByOptions(queryKey, options) {
1177
+ const hashFn = (options == null ? void 0 : options.queryKeyHashFn) ?? hashKey;
1178
+ return hashFn(queryKey);
1179
+ }
1180
+ function matchQuery(filters, query) {
1181
+ const {
1182
+ type = "all",
1183
+ exact,
1184
+ fetchStatus,
1185
+ predicate,
1186
+ queryKey,
1187
+ stale
1188
+ } = filters;
1189
+ if (queryKey) {
1190
+ if (exact) {
1191
+ if (query.queryHash !== hashQueryKeyByOptions(queryKey, query.options)) {
1192
+ return false;
1193
+ }
1194
+ } else if (!partialMatchKey(query.queryKey, queryKey)) {
1195
+ return false;
1196
+ }
1197
+ }
1198
+ if (type !== "all") {
1199
+ const isActive = query.isActive();
1200
+ if (type === "active" && !isActive) {
1201
+ return false;
1202
+ }
1203
+ if (type === "inactive" && isActive) {
1204
+ return false;
1205
+ }
1206
+ }
1207
+ if (typeof stale === "boolean" && query.isStale() !== stale) {
1208
+ return false;
1209
+ }
1210
+ if (typeof fetchStatus !== "undefined" && fetchStatus !== query.state.fetchStatus) {
1211
+ return false;
1212
+ }
1213
+ if (predicate && !predicate(query)) {
1214
+ return false;
1215
+ }
1216
+ return true;
1217
+ }
1218
+ function timeUntilStale(updatedAt, staleTime) {
1219
+ return Math.max(updatedAt + (staleTime ?? 0) - Date.now(), 0);
1220
+ }
1221
+ function functionalUpdate(updater, input) {
1222
+ return typeof updater === "function" ? updater(input) : updater;
1223
+ }
1224
+ function replaceData(prevData, data, options) {
1225
+ if (typeof options.structuralSharing === "function") {
1226
+ return options.structuralSharing(prevData, data);
1227
+ } else if (options.structuralSharing !== false) {
1228
+ return replaceEqualDeep(prevData, data);
1229
+ }
1230
+ return data;
1231
+ }
1232
+ const skipToken = Symbol();
1233
+ const reduceState = ({
1234
+ getOptions,
1235
+ getState,
1236
+ initialState
1237
+ }) => (source) => source.pipe(
1238
+ rxjs.scan((acc, { command, state: current }) => {
1239
+ if (command === "reset") return { ...acc, ...current };
1240
+ if (command === "cancel") {
1241
+ const status2 = acc.status === "pending" ? "pending" : current.status ?? acc.status;
1242
+ return { ...acc, ...current, status: status2 };
1243
+ }
1244
+ const currentData = current.data;
1245
+ const weHaveNewData = currentData !== void 0 && currentData !== acc.data;
1246
+ const weHaveDataKeyInCurrent = "data" in current;
1247
+ const newSuccessStatus = current.status === "success";
1248
+ const hasData = acc.data !== void 0;
1249
+ const hasError = acc.error !== void 0 || acc.error !== null;
1250
+ const status = current.status ?? acc.status;
1251
+ const newData = weHaveNewData ? replaceData(getState().data, currentData, getOptions()) : weHaveDataKeyInCurrent ? current.data : acc.data;
1252
+ const previousStatusIsSuccessOrError = acc.status === "error" || acc.status === "success";
1253
+ const errorUpdateCount = current.status === "error" && (acc.status === "error" && acc.fetchStatus === "fetching" || acc.status !== "error") ? acc.errorUpdateCount + 1 : acc.errorUpdateCount;
1254
+ const dataUpdateCount = weHaveNewData ? acc.dataUpdateCount + 1 : current.dataUpdateCount ?? acc.dataUpdateCount;
1255
+ const newPendingStatusOnHold = current.status === "pending" && previousStatusIsSuccessOrError && // (dataUpdateCount !== 0 || errorUpdateCount !== 0)
1256
+ (hasData || hasError);
1257
+ const error = status === "pending" ? null : current.error ?? acc.error;
1258
+ return {
1259
+ ...acc,
1260
+ ...current,
1261
+ status,
1262
+ error,
1263
+ errorUpdateCount,
1264
+ ...newSuccessStatus && {
1265
+ isInvalidated: false
1266
+ },
1267
+ data: newData,
1268
+ dataUpdateCount,
1269
+ ...newPendingStatusOnHold && {
1270
+ status: acc.status
1271
+ }
1272
+ };
1273
+ }, initialState)
1274
+ );
1275
+ const isQueryFinished = (source) => source.pipe(
1276
+ rxjs.map(
1277
+ ({ status, fetchStatus }) => fetchStatus === "idle" && (status === "success" || status === "error")
1278
+ )
1279
+ );
1280
+ const takeUntilFinished = (source) => source.pipe(
1281
+ rxjs.takeWhile((result) => {
1282
+ const isFetchingOrPaused = result.fetchStatus !== "idle";
1283
+ return isFetchingOrPaused;
1284
+ }, true)
1285
+ );
1286
+ class FocusManager {
1287
+ constructor() {
1288
+ __privateAdd(this, _visibility$, rxjs.merge(
1289
+ isServer ? rxjs.EMPTY : rxjs.fromEvent(document, "visibilitychange"),
1290
+ isServer ? rxjs.EMPTY : rxjs.fromEvent(window, "visibilitychange")
1291
+ ).pipe(rxjs.map(() => document.visibilityState)));
1292
+ __privateAdd(this, _focusedSubject, new rxjs.BehaviorSubject(
1293
+ isServer ? true : document.visibilityState === "visible"
1294
+ ));
1295
+ // public readonly focused$ = this.#focusedSubject.pipe(distinctUntilChanged())
1296
+ __publicField(this, "focused$", __privateGet(this, _focusedSubject));
1297
+ __publicField(this, "focusRegained$", this.focused$.pipe(
1298
+ rxjs.skip(1),
1299
+ rxjs.filter((visibility) => visibility)
1300
+ ));
1301
+ __privateGet(this, _visibility$).pipe(
1302
+ rxjs.tap((value) => {
1303
+ __privateGet(this, _focusedSubject).next(value === "visible");
1304
+ })
1305
+ ).subscribe();
1306
+ }
1307
+ isFocused() {
1308
+ return __privateGet(this, _focusedSubject).getValue();
1309
+ }
1310
+ setFocused(focused) {
1311
+ const changed = __privateGet(this, _focusedSubject).getValue() !== (focused ?? true);
1312
+ if (changed) {
1313
+ __privateGet(this, _focusedSubject).next(focused ?? true);
1314
+ }
1315
+ }
1316
+ subscribe(fn) {
1317
+ const sub = this.focused$.subscribe(fn);
1318
+ return () => {
1319
+ sub.unsubscribe();
1320
+ };
1321
+ }
1322
+ /**
1323
+ * @important
1324
+ * You do not need that outside of testing. This is bad practice but necessary in order
1325
+ * to not mess too much with rq tests files.
1326
+ *
1327
+ * Use it after mocking to force the manager to hold mocked value.
1328
+ */
1329
+ refresh() {
1330
+ document.dispatchEvent(new Event("visibilitychange"));
1331
+ }
1332
+ }
1333
+ _visibility$ = new WeakMap();
1334
+ _focusedSubject = new WeakMap();
1335
+ const focusManager = new FocusManager();
1336
+ const whenNewData = (source) => source.pipe(
1337
+ rxjs.filter((state) => state.status === "success"),
1338
+ rxjs.map((state) => ({
1339
+ data: state.data,
1340
+ status: state.status,
1341
+ dataUpdatedAt: state.dataUpdatedAt
1342
+ })),
1343
+ rxjs.distinctUntilChanged(shallowEqual)
1344
+ );
1345
+ class QueryObserver {
1346
+ constructor(client, options) {
1347
+ __privateAdd(this, _client);
1348
+ __privateAdd(this, _currentQuery);
1349
+ __privateAdd(this, _fetchSubject, new rxjs.Subject());
1350
+ /**
1351
+ * Used to subscribe to changes in either query or options (or both).
1352
+ * We need to be able to track change to both of them at the same time
1353
+ * in order to react accordingly and in order (such as refetch on options change)
1354
+ */
1355
+ __publicField(this, "queryUpdateSubject", new rxjs.Subject());
1356
+ /**
1357
+ * Mostly used to compare the state before and after mount
1358
+ */
1359
+ __privateAdd(this, _currentQueryInitialState);
1360
+ /**
1361
+ * Mostly used for internal optimization such as not
1362
+ * running selectors twice, etc
1363
+ */
1364
+ __privateAdd(this, _lastResult);
1365
+ // This property keeps track of the last query with defined data.
1366
+ // It will be used to pass the previous data and query to the placeholder function between renders.
1367
+ __privateAdd(this, _lastQueryWithDefinedData);
1368
+ __privateAdd(this, _observers, 0);
1369
+ __publicField(this, "getObserverResultFromQuery", ({
1370
+ options,
1371
+ query,
1372
+ optimisticResult,
1373
+ prevResult: {
1374
+ result: prevResult,
1375
+ options: prevResultOptions,
1376
+ state: prevResultState,
1377
+ select: prevSelect,
1378
+ selectError: prevSelectError,
1379
+ selectResult: prevSelectResult
1380
+ }
1381
+ }) => {
1382
+ var _a;
1383
+ const state = query.state;
1384
+ const isPending = query.state.status === "pending";
1385
+ const prevQuery = __privateGet(this, _currentQuery);
1386
+ const prevOptions = this.options;
1387
+ const queryChange = query !== prevQuery;
1388
+ const queryInitialState = queryChange ? query.state : __privateGet(this, _currentQueryInitialState);
1389
+ let { errorUpdatedAt, fetchStatus, error } = state;
1390
+ if (optimisticResult) {
1391
+ const mounted = !!__privateGet(this, _observers);
1392
+ const fetchOnMount = !mounted && shouldFetchOnMount(query, options);
1393
+ const fetchOptionally = mounted && shouldFetchOptionally(query, prevQuery, options, prevOptions);
1394
+ if (fetchOnMount || fetchOptionally) {
1395
+ fetchStatus = canFetch(query.options.networkMode) ? "fetching" : "paused";
1396
+ }
1397
+ }
1398
+ const isLoading = isPending && fetchStatus === "fetching";
1399
+ let data;
1400
+ let selectError = prevSelectError;
1401
+ let selectFn = prevSelect ?? null;
1402
+ let selectResult = prevSelectResult;
1403
+ if (options.select && typeof state.data !== "undefined") {
1404
+ if (prevResult && state.data === (prevResultState == null ? void 0 : prevResultState.data) && options.select === prevSelect) {
1405
+ data = prevSelectResult;
1406
+ } else {
1407
+ try {
1408
+ selectFn = options.select;
1409
+ data = options.select(state.data);
1410
+ data = replaceData(prevResult == null ? void 0 : prevResult.data, data, options);
1411
+ selectResult = data;
1412
+ selectError = null;
1413
+ } catch (error2) {
1414
+ data = prevSelectResult;
1415
+ selectError = error2;
1416
+ }
1417
+ }
1418
+ } else {
1419
+ data = state.data;
1420
+ selectError = null;
1421
+ }
1422
+ let status = fetchStatus !== "idle" && !state.dataUpdatedAt ? "pending" : state.status;
1423
+ if (selectError) {
1424
+ error = selectError;
1425
+ data = prevSelectResult;
1426
+ errorUpdatedAt = (prevResult == null ? void 0 : prevResult.errorUpdatedAt) ?? errorUpdatedAt;
1427
+ status = "error";
1428
+ }
1429
+ const isError = status === "error";
1430
+ let isPlaceholderData = false;
1431
+ if (typeof options.placeholderData !== "undefined" && typeof data === "undefined" && status === "pending") {
1432
+ let placeholderData;
1433
+ if ((prevResult == null ? void 0 : prevResult.isPlaceholderData) && options.placeholderData === (prevResultOptions == null ? void 0 : prevResultOptions.placeholderData)) {
1434
+ placeholderData = prevResult.data;
1435
+ } else {
1436
+ placeholderData = typeof options.placeholderData === "function" ? options.placeholderData(
1437
+ (_a = __privateGet(this, _lastQueryWithDefinedData)) == null ? void 0 : _a.state.data,
1438
+ __privateGet(this, _lastQueryWithDefinedData)
1439
+ ) : options.placeholderData;
1440
+ if (options.select && typeof placeholderData !== "undefined") {
1441
+ try {
1442
+ placeholderData = options.select(placeholderData);
1443
+ } catch (selectError2) {
1444
+ }
1445
+ }
1446
+ }
1447
+ if (typeof placeholderData !== "undefined") {
1448
+ status = "success";
1449
+ data = replaceData(
1450
+ prevResult == null ? void 0 : prevResult.data,
1451
+ placeholderData,
1452
+ options
1453
+ );
1454
+ isPlaceholderData = true;
1455
+ }
1456
+ }
1457
+ const isFetching = fetchStatus === "fetching";
1458
+ const result = {
1459
+ status,
1460
+ fetchStatus,
1461
+ isPending,
1462
+ isSuccess: status === "success",
1463
+ isError,
1464
+ isInitialLoading: isLoading,
1465
+ isLoading,
1466
+ data,
1467
+ dataUpdatedAt: state.dataUpdatedAt,
1468
+ error,
1469
+ errorUpdatedAt,
1470
+ failureCount: state.fetchFailureCount,
1471
+ failureReason: state.fetchFailureReason,
1472
+ errorUpdateCount: state.errorUpdateCount,
1473
+ isFetched: state.dataUpdateCount > 0 || state.errorUpdateCount > 0,
1474
+ isFetchedAfterMount: state.dataUpdateCount > queryInitialState.dataUpdateCount || state.errorUpdateCount > queryInitialState.errorUpdateCount,
1475
+ isFetching,
1476
+ isRefetching: isFetching && !isPending,
1477
+ isLoadingError: isError && state.dataUpdatedAt === 0,
1478
+ isPaused: fetchStatus === "paused",
1479
+ isPlaceholderData,
1480
+ isRefetchError: isError && state.dataUpdatedAt !== 0,
1481
+ isStale: isStale(query, options),
1482
+ // eslint-disable-next-line @typescript-eslint/unbound-method
1483
+ refetch: this.refetch
1484
+ };
1485
+ return {
1486
+ result,
1487
+ selectError,
1488
+ select: selectFn,
1489
+ selectResult
1490
+ };
1491
+ });
1492
+ this.options = options;
1493
+ __privateSet(this, _client, client);
1494
+ this.bindMethods();
1495
+ __privateSet(this, _currentQuery, this.setOptions(options));
1496
+ const query = __privateGet(this, _currentQuery);
1497
+ __privateSet(this, _currentQueryInitialState, query.state);
1498
+ const { result, select } = this.getObserverResultFromQuery({
1499
+ query,
1500
+ options: this.options,
1501
+ prevResult: {
1502
+ options: this.options,
1503
+ state: query.state
1504
+ }
1505
+ });
1506
+ __privateSet(this, _lastResult, {
1507
+ state: query.state,
1508
+ options,
1509
+ result,
1510
+ select
1511
+ });
1512
+ }
1513
+ bindMethods() {
1514
+ this.refetch = this.refetch.bind(this);
1515
+ }
1516
+ setOptions(options) {
1517
+ const prevOptions = this.options;
1518
+ this.options = __privateGet(this, _client).defaultQueryOptions(options);
1519
+ if (!shallowEqual(this.options, prevOptions)) {
1520
+ __privateGet(this, _client).getQueryCache().notify({
1521
+ type: "observerOptionsUpdated",
1522
+ query: __privateGet(this, _currentQuery),
1523
+ observer: this
1524
+ });
1525
+ }
1526
+ if (typeof this.options.enabled !== "undefined" && typeof this.options.enabled !== "boolean") {
1527
+ throw new Error("Expected enabled to be a boolean");
1528
+ }
1529
+ const query = this.buildQuery(this.options);
1530
+ if (query !== __privateGet(this, _currentQuery)) {
1531
+ __privateSet(this, _currentQueryInitialState, query.state);
1532
+ __privateSet(this, _currentQuery, query);
1533
+ }
1534
+ this.queryUpdateSubject.next({
1535
+ options: this.options,
1536
+ query
1537
+ });
1538
+ return query;
1539
+ }
1540
+ buildQuery(options) {
1541
+ const query = __privateGet(this, _client).getQueryCache().build(__privateGet(this, _client), options);
1542
+ if (!query.options.queryFn && this.options.queryFn) {
1543
+ query.setOptions(options);
1544
+ }
1545
+ return query;
1546
+ }
1547
+ getCurrentResult() {
1548
+ const result = this.getObserverResultFromQuery({
1549
+ options: this.options,
1550
+ prevResult: __privateGet(this, _lastResult),
1551
+ query: __privateGet(this, _currentQuery)
1552
+ });
1553
+ return result.result;
1554
+ }
1555
+ getCurrentQuery() {
1556
+ return __privateGet(this, _currentQuery);
1557
+ }
1558
+ getOptimisticResult(options) {
1559
+ const query = this.buildQuery(options);
1560
+ const observedResult = this.getObserverResultFromQuery({
1561
+ query,
1562
+ options,
1563
+ optimisticResult: true,
1564
+ prevResult: __privateGet(this, _lastResult)
1565
+ });
1566
+ if (shouldAssignObserverCurrentProperties(this, observedResult.result)) {
1567
+ this.updateResult({ query, ...observedResult });
1568
+ }
1569
+ return observedResult.result;
1570
+ }
1571
+ updateResult({
1572
+ query,
1573
+ result,
1574
+ selectError,
1575
+ select,
1576
+ selectResult
1577
+ }) {
1578
+ __privateGet(this, _lastResult).state = query.state;
1579
+ __privateGet(this, _lastResult).result = result;
1580
+ __privateGet(this, _lastResult).selectResult = selectResult;
1581
+ if (selectError !== void 0) {
1582
+ __privateGet(this, _lastResult).selectError = selectError;
1583
+ }
1584
+ if (select !== void 0) {
1585
+ __privateGet(this, _lastResult).select = select;
1586
+ }
1587
+ __privateGet(this, _lastResult).options = this.options;
1588
+ if (query.state.data !== void 0) {
1589
+ __privateSet(this, _lastQueryWithDefinedData, query);
1590
+ }
1591
+ __privateGet(this, _client).getQueryCache().notify({
1592
+ query: __privateGet(this, _currentQuery),
1593
+ type: "observerResultsUpdated"
1594
+ });
1595
+ }
1596
+ async refetch({ ...options } = {}) {
1597
+ return await this.fetch({
1598
+ ...options
1599
+ });
1600
+ }
1601
+ async fetch(fetchOptions) {
1602
+ const query = this.buildQuery(this.options);
1603
+ if (query !== __privateGet(this, _currentQuery)) {
1604
+ __privateSet(this, _currentQuery, query);
1605
+ __privateSet(this, _currentQueryInitialState, query.state);
1606
+ this.queryUpdateSubject.next({
1607
+ options: this.options,
1608
+ query
1609
+ });
1610
+ }
1611
+ const finalFetchOptions = {
1612
+ ...fetchOptions,
1613
+ cancelRefetch: (fetchOptions == null ? void 0 : fetchOptions.cancelRefetch) ?? true
1614
+ };
1615
+ __privateGet(this, _currentQuery).fetch(this.options, finalFetchOptions).catch(rxjs.noop);
1616
+ __privateGet(this, _fetchSubject).next({
1617
+ query,
1618
+ fetchOptions: finalFetchOptions
1619
+ });
1620
+ await query.getFetchResultAsPromise();
1621
+ const { result } = this.getObserverResultFromQuery({
1622
+ query,
1623
+ options: this.options,
1624
+ prevResult: __privateGet(this, _lastResult)
1625
+ });
1626
+ return result;
1627
+ }
1628
+ /**
1629
+ * feature parity with rq, not used internally
1630
+ */
1631
+ subscribe(listener) {
1632
+ const sub = this.observe().subscribe(listener);
1633
+ return () => {
1634
+ sub.unsubscribe();
1635
+ };
1636
+ }
1637
+ observe() {
1638
+ const observedQuery = __privateGet(this, _currentQuery);
1639
+ const currentQuery$ = this.queryUpdateSubject.pipe(
1640
+ rxjs.map(({ query }) => query),
1641
+ rxjs.startWith(__privateGet(this, _currentQuery)),
1642
+ rxjs.distinctUntilChanged()
1643
+ );
1644
+ const watchForImplicitRefetch$ = this.queryUpdateSubject.pipe(
1645
+ rxjs.startWith({
1646
+ query: __privateGet(this, _currentQuery),
1647
+ options: this.options
1648
+ }),
1649
+ rxjs.pairwise(),
1650
+ rxjs.tap(
1651
+ ([{ options: prevOptions, query: prevQuery }, { options, query }]) => {
1652
+ if (shouldFetchOptionally(query, prevQuery, options, prevOptions)) {
1653
+ this.fetch().catch(rxjs.noop);
1654
+ }
1655
+ }
1656
+ ),
1657
+ rxjs.ignoreElements()
1658
+ );
1659
+ const observedQuery$ = currentQuery$.pipe(
1660
+ rxjs.switchMap((query) => query.observe(this)),
1661
+ rxjs.ignoreElements()
1662
+ );
1663
+ const result$ = rxjs.merge(
1664
+ /**
1665
+ * It's important to observe the query before we subscribe to its result
1666
+ * later in the chain of merge to get the first result right after fetch
1667
+ */
1668
+ observedQuery$,
1669
+ watchForImplicitRefetch$,
1670
+ currentQuery$.pipe(
1671
+ rxjs.switchMap((query) => {
1672
+ const options = this.options;
1673
+ const options$ = this.queryUpdateSubject.pipe(
1674
+ rxjs.startWith({ query, options }),
1675
+ rxjs.filter((update) => update.query === query),
1676
+ rxjs.map((update) => update.options),
1677
+ rxjs.distinctUntilChanged(),
1678
+ rxjs.shareReplay(1)
1679
+ );
1680
+ const queryFetch$ = __privateGet(this, _fetchSubject).pipe(
1681
+ rxjs.filter((update) => update.query === query)
1682
+ );
1683
+ const currentQueryIsStale$ = query.state$.pipe(
1684
+ whenNewData,
1685
+ rxjs.switchMap(
1686
+ (state) => this.options.staleTime === Infinity ? rxjs.NEVER : (this.options.staleTime ?? 0) <= 0 ? rxjs.of(state).pipe(rxjs.delay(1)) : rxjs.timer(this.options.staleTime ?? 1)
1687
+ ),
1688
+ rxjs.takeWhile(() => this.options.enabled ?? true)
1689
+ );
1690
+ const comparisonFunction = (objA, objB) => {
1691
+ const notifyOnChangeProps = options.notifyOnChangeProps;
1692
+ const notifyOnChangePropsValue = typeof notifyOnChangeProps === "function" ? notifyOnChangeProps() : notifyOnChangeProps;
1693
+ const reducedFunction = Array.isArray(notifyOnChangePropsValue) ? notifyOnChangePropsValue.length === 0 ? () => true : (objA2, objB2) => {
1694
+ const reducedObjA = filterObjectByKey(
1695
+ objA2,
1696
+ notifyOnChangePropsValue
1697
+ );
1698
+ const reducedObjB = filterObjectByKey(
1699
+ objB2,
1700
+ notifyOnChangePropsValue
1701
+ );
1702
+ return shallowEqual(reducedObjA, reducedObjB);
1703
+ } : shallowEqual;
1704
+ return reducedFunction(objA, objB);
1705
+ };
1706
+ const queryInternallyFetchedUpdate$ = queryFetch$.pipe(
1707
+ rxjs.switchMap(() => query.state$),
1708
+ takeUntilFinished
1709
+ );
1710
+ const refetchInterval$ = options$.pipe(
1711
+ rxjs.map(({ refetchInterval, refetchIntervalInBackground }) => {
1712
+ const computedRefetchInterval = (typeof refetchInterval === "function" ? refetchInterval(__privateGet(this, _currentQuery)) : refetchInterval) ?? false;
1713
+ return {
1714
+ refetchInterval: computedRefetchInterval,
1715
+ refetchIntervalInBackground
1716
+ };
1717
+ }),
1718
+ rxjs.distinctUntilChanged(shallowEqual),
1719
+ rxjs.switchMap(({ refetchInterval, refetchIntervalInBackground }) => {
1720
+ return !refetchInterval ? rxjs.NEVER : rxjs.interval(refetchInterval).pipe(
1721
+ rxjs.tap(() => {
1722
+ if (
1723
+ // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
1724
+ refetchIntervalInBackground || focusManager.isFocused()
1725
+ ) {
1726
+ this.fetch({ cancelRefetch: false }).catch(rxjs.noop);
1727
+ }
1728
+ })
1729
+ );
1730
+ }),
1731
+ rxjs.ignoreElements()
1732
+ );
1733
+ const isMaybeEnabled$ = options$.pipe(
1734
+ rxjs.map(({ enabled }) => enabled ?? true),
1735
+ rxjs.distinctUntilChanged()
1736
+ );
1737
+ const disabled$ = isMaybeEnabled$.pipe(
1738
+ rxjs.filter((enabled) => !enabled),
1739
+ rxjs.map(() => query.state)
1740
+ );
1741
+ const onFocusRegain$ = isMaybeEnabled$.pipe(
1742
+ rxjs.filter((enabled) => enabled),
1743
+ rxjs.switchMap(() => focusManager.focusRegained$),
1744
+ rxjs.withLatestFrom(options$),
1745
+ rxjs.tap(([, options2]) => {
1746
+ if (shouldFetchOnWindowFocus(query, options2)) {
1747
+ this.fetch({ cancelRefetch: false }).catch(rxjs.noop);
1748
+ }
1749
+ }),
1750
+ rxjs.ignoreElements()
1751
+ );
1752
+ const stateObservedOnDisabled$ = disabled$.pipe(
1753
+ rxjs.map(() => query.state)
1754
+ );
1755
+ const updateResult = (source) => {
1756
+ return source.pipe(
1757
+ rxjs.withLatestFrom(options$),
1758
+ rxjs.map(([, currentOptions]) => {
1759
+ const result = this.getObserverResultFromQuery({
1760
+ query,
1761
+ options: currentOptions,
1762
+ prevResult: __privateGet(this, _lastResult)
1763
+ });
1764
+ this.updateResult({ query, ...result });
1765
+ return result.result;
1766
+ })
1767
+ );
1768
+ };
1769
+ const stateUpdate$ = rxjs.merge(
1770
+ stateObservedOnDisabled$,
1771
+ queryInternallyFetchedUpdate$,
1772
+ query.state$,
1773
+ // options$,
1774
+ currentQueryIsStale$
1775
+ );
1776
+ const observedResult$ = stateUpdate$.pipe(
1777
+ updateResult,
1778
+ // This one ensure we don't re-trigger same state
1779
+ rxjs.distinctUntilChanged(shallowEqual),
1780
+ // This one make sure we dispatch based on user preference
1781
+ rxjs.distinctUntilChanged(comparisonFunction)
1782
+ );
1783
+ return rxjs.merge(refetchInterval$, onFocusRegain$, observedResult$);
1784
+ })
1785
+ ).pipe(
1786
+ trackSubscriptions((count) => __privateSet(this, _observers, count)),
1787
+ rxjs.tap({
1788
+ subscribe: () => {
1789
+ if (shouldFetchOnMount(observedQuery, this.options)) {
1790
+ this.fetch().catch(rxjs.noop);
1791
+ }
1792
+ }
1793
+ })
1794
+ )
1795
+ );
1796
+ return result$;
1797
+ }
1798
+ destroy() {
1799
+ }
1800
+ }
1801
+ _client = new WeakMap();
1802
+ _currentQuery = new WeakMap();
1803
+ _fetchSubject = new WeakMap();
1804
+ _currentQueryInitialState = new WeakMap();
1805
+ _lastResult = new WeakMap();
1806
+ _lastQueryWithDefinedData = new WeakMap();
1807
+ _observers = new WeakMap();
1808
+ function shouldAssignObserverCurrentProperties(observer, optimisticResult) {
1809
+ if (!shallowEqual(observer.getCurrentResult(), optimisticResult)) {
1810
+ return true;
1811
+ }
1812
+ return false;
1813
+ }
1814
+ const IsRestoringContext = React__namespace.createContext(false);
1815
+ const useIsRestoring = () => React__namespace.useContext(IsRestoringContext);
1816
+ IsRestoringContext.Provider;
1817
+ function createValue() {
1818
+ let isReset = false;
1819
+ return {
1820
+ clearReset: () => {
1821
+ isReset = false;
1822
+ },
1823
+ reset: () => {
1824
+ isReset = true;
1825
+ },
1826
+ isReset: () => {
1827
+ return isReset;
1828
+ }
1829
+ };
1830
+ }
1831
+ const QueryErrorResetBoundaryContext = React__namespace.createContext(createValue());
1832
+ const useQueryErrorResetBoundary = () => React__namespace.useContext(QueryErrorResetBoundaryContext);
1833
+ function shouldThrowError(throwError, params) {
1834
+ if (typeof throwError === "function") {
1835
+ return throwError(...params);
1836
+ }
1837
+ return !!throwError;
1838
+ }
1839
+ const getHasError = ({
1840
+ result,
1841
+ errorResetBoundary,
1842
+ throwOnError,
1843
+ query
1844
+ }) => {
1845
+ return result.isError && !errorResetBoundary.isReset() && !result.isFetching && query && shouldThrowError(throwOnError, [result.error, query]);
1846
+ };
1847
+ function useBaseQuery(options, Observer, queryClient) {
1848
+ if (process.env.NODE_ENV !== "production") {
1849
+ if (typeof options !== "object" || Array.isArray(options)) {
1850
+ throw new Error(
1851
+ 'Bad argument type. Starting with v5, only the "Object" form is allowed when calling query related functions. Please use the error stack to find the culprit call. More info here: https://tanstack.com/query/latest/docs/react/guides/migrating-to-v5#supports-a-single-signature-one-object'
1852
+ );
1853
+ }
1854
+ }
1855
+ const client = useQueryClient(queryClient);
1856
+ const isRestoring = useIsRestoring();
1857
+ const errorResetBoundary = useQueryErrorResetBoundary();
1858
+ const defaultedOptions = client.defaultQueryOptions(options);
1859
+ defaultedOptions._optimisticResults = isRestoring ? "isRestoring" : "optimistic";
1860
+ const [observer] = React.useState(
1861
+ () => new Observer(
1862
+ client,
1863
+ defaultedOptions
1864
+ )
1865
+ );
1866
+ const result$ = useConstant(() => observer.observe());
1867
+ const optimisticResult = useLiveRef(
1868
+ observer.getOptimisticResult(defaultedOptions)
1869
+ );
1870
+ const result = optimisticResult.current;
1871
+ useObserve(
1872
+ () => result$.current.pipe(
1873
+ /**
1874
+ * By the time this observer runs the result may have changed (eg: synchronous setData).
1875
+ * It's important to not skip the first result (even tho most of the time they are equal).
1876
+ * We only skip if they are the same.
1877
+ */
1878
+ rxjs.filter((result2) => !shallowEqual(result2, optimisticResult.current))
1879
+ ),
1880
+ []
1881
+ );
1882
+ React.useEffect(() => {
1883
+ observer.setOptions(defaultedOptions);
1884
+ }, [defaultedOptions, observer]);
1885
+ const error = result.error;
1886
+ if (error && getHasError({
1887
+ result,
1888
+ errorResetBoundary,
1889
+ throwOnError: defaultedOptions.throwOnError,
1890
+ query: client.getQueryCache().get(defaultedOptions.queryHash)
1891
+ })) {
1892
+ throw error;
1893
+ }
1894
+ return optimisticResult.current;
1895
+ }
1896
+ function useQuery(options, queryClient) {
1897
+ return useBaseQuery(options, QueryObserver, queryClient);
1898
+ }
1899
+ function useForeverQuery(options, queryClient) {
1900
+ return useBaseQuery(
1901
+ {
1902
+ refetchOnMount: "idle",
1903
+ refetchOnReconnect: false,
1904
+ refetchInterval: false,
1905
+ refetchOnWindowFocus: false,
1906
+ ...options
1907
+ },
1908
+ QueryObserver,
1909
+ queryClient
1910
+ );
1911
+ }
1912
+ function useSubscribeEffect(source, unsafeOptions, deps = []) {
1913
+ const options = unsafeOptions != null && !Array.isArray(unsafeOptions) ? unsafeOptions : {};
1914
+ const retryOption = options.retry ?? true;
1915
+ const onErrorRef = useLiveRef(
1916
+ options.onError ?? ((error) => {
1917
+ console.error(error);
1918
+ })
1919
+ );
1920
+ const sourceAsObservable = React.useCallback(() => makeObservable(source), deps);
1921
+ const enhancerMakeObservable = React.useCallback(
1922
+ () => sourceAsObservable().pipe(
1923
+ rxjs.catchError((error) => {
1924
+ onErrorRef.current(error);
1925
+ throw error;
1926
+ }),
1927
+ retryOption ? rxjs.retry() : rxjs.identity
1928
+ ),
1929
+ [sourceAsObservable, retryOption, onErrorRef]
1930
+ );
1931
+ useSubscribe(enhancerMakeObservable, deps);
1932
+ }
1933
+ const delayWhenNetworkOnline = () => (source) => {
1934
+ return rxjs.merge(
1935
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
1936
+ rxjs.of({ isPaused: true }),
1937
+ onlineManager.backToOnline$.pipe(
1938
+ rxjs.mergeMap(
1939
+ () => (
1940
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
1941
+ rxjs.merge(rxjs.of({ isPaused: false }), source)
1942
+ )
1943
+ )
1944
+ )
1945
+ );
1946
+ };
1947
+ const waitForNetworkOnError = (source) => {
1948
+ let attempt = 0;
1949
+ return source.pipe(
1950
+ rxjs.catchError((error) => {
1951
+ attempt++;
1952
+ if (attempt <= 1 && !onlineManager.isOnline()) {
1953
+ return rxjs.merge(
1954
+ rxjs.of({
1955
+ failureCount: attempt,
1956
+ failureReason: error
1957
+ }),
1958
+ /**
1959
+ * @important
1960
+ * timer needed to be iso RQ, so the state returned by mutation include both previous and next one
1961
+ */
1962
+ rxjs.timer(1).pipe(
1963
+ rxjs.mergeMap(
1964
+ () => rxjs.throwError(() => error).pipe(delayWhenNetworkOnline())
1965
+ )
1966
+ )
1967
+ );
1968
+ } else {
1969
+ return rxjs.throwError(() => error);
1970
+ }
1971
+ })
1972
+ );
1973
+ };
1974
+ const executeMutation = ({
1975
+ variables,
1976
+ state,
1977
+ options
1978
+ }) => {
1979
+ const isPaused = state.isPaused;
1980
+ const defaultFn = async () => await Promise.reject(new Error("No mutationFn found"));
1981
+ const mutationFn = options.mutationFn ?? defaultFn;
1982
+ const onMutateFactory = () => {
1983
+ var _a;
1984
+ return ((_a = options.onMutate) == null ? void 0 : _a.call(options, variables)) ?? void 0;
1985
+ };
1986
+ const contextFromOnMutate$ = makeObservable(onMutateFactory);
1987
+ contextFromOnMutate$.pipe(
1988
+ rxjs.tap((context) => {
1989
+ if (context === void 0) {
1990
+ throw new Error("onMutate returned undefined");
1991
+ }
1992
+ })
1993
+ );
1994
+ const rawContext$ = rxjs.of(state.context);
1995
+ const context$ = rxjs.iif(() => isPaused, rawContext$, contextFromOnMutate$).pipe(
1996
+ rxjs.shareReplay(1)
1997
+ );
1998
+ const onError = (error, context, attempt) => {
1999
+ const onError$ = makeObservable(
2000
+ () => {
2001
+ var _a;
2002
+ return (_a = options.onError) == null ? void 0 : _a.call(options, error, variables, context);
2003
+ }
2004
+ );
2005
+ return onError$.pipe(
2006
+ rxjs.catchError(() => rxjs.of(error)),
2007
+ rxjs.map(
2008
+ () => ({
2009
+ failureCount: attempt,
2010
+ error,
2011
+ failureReason: error,
2012
+ context,
2013
+ status: "error"
2014
+ })
2015
+ )
2016
+ );
2017
+ };
2018
+ const queryRunner$ = context$.pipe(
2019
+ rxjs.switchMap((context) => {
2020
+ const fn$ = typeof mutationFn === "function" ? makeObservable(() => mutationFn(variables)) : mutationFn;
2021
+ const sharedFn$ = fn$.pipe(rxjs.share());
2022
+ const completeWithoutValue$ = sharedFn$.pipe(
2023
+ rxjs.isEmpty(),
2024
+ rxjs.tap((isEmppty) => {
2025
+ if (isEmppty) {
2026
+ throw new Error("Mutation completed without any emission (EMPTY)");
2027
+ }
2028
+ }),
2029
+ rxjs.ignoreElements()
2030
+ );
2031
+ const finalFn$ = rxjs.merge(sharedFn$, completeWithoutValue$).pipe(
2032
+ rxjs.map(
2033
+ (data) => ({
2034
+ result: {
2035
+ data
2036
+ },
2037
+ error: null,
2038
+ context
2039
+ })
2040
+ ),
2041
+ waitForNetworkOnError,
2042
+ retryBackoff({
2043
+ ...options,
2044
+ retry: (attempt, error) => {
2045
+ const retry = options.retry ?? 0;
2046
+ if (typeof retry === "function") return retry(attempt, error);
2047
+ if (typeof retry === "boolean") return retry;
2048
+ return attempt < retry;
2049
+ },
2050
+ caughtError: (attempt, error) => (
2051
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
2052
+ rxjs.of({
2053
+ failureCount: attempt,
2054
+ failureReason: error
2055
+ })
2056
+ ),
2057
+ catchError: (attempt, error) => onError(error, context, attempt).pipe(
2058
+ rxjs.map((data) => ({
2059
+ ...data,
2060
+ result: void 0
2061
+ }))
2062
+ )
2063
+ }),
2064
+ rxjs.takeWhile(
2065
+ ({ result, error }) => (result == null ? void 0 : result.data) === void 0 && error === void 0,
2066
+ true
2067
+ )
2068
+ );
2069
+ if (onlineManager.isOnline() || options.networkMode === "offlineFirst" || options.networkMode === "always") {
2070
+ return finalFn$;
2071
+ } else {
2072
+ return finalFn$.pipe(delayWhenNetworkOnline());
2073
+ }
2074
+ })
2075
+ );
2076
+ const initState$ = rxjs.of({
2077
+ ...state,
2078
+ variables,
2079
+ status: "pending",
2080
+ isPaused: false,
2081
+ failureCount: 0,
2082
+ failureReason: null,
2083
+ submittedAt: state.submittedAt ?? (/* @__PURE__ */ new Date()).getTime()
2084
+ });
2085
+ const mutation$ = rxjs.merge(
2086
+ initState$,
2087
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
2088
+ context$.pipe(rxjs.map((context) => ({ context }))),
2089
+ queryRunner$.pipe(
2090
+ rxjs.switchMap(({ result: mutationData, error, ...restState }) => {
2091
+ if (!mutationData && !error)
2092
+ return rxjs.of({
2093
+ ...restState
2094
+ });
2095
+ const success$ = error ? rxjs.of(null) : makeObservable(
2096
+ () => {
2097
+ var _a;
2098
+ return (_a = options.onSuccess) == null ? void 0 : _a.call(
2099
+ options,
2100
+ mutationData == null ? void 0 : mutationData.data,
2101
+ variables,
2102
+ restState.context
2103
+ );
2104
+ }
2105
+ );
2106
+ const onOptionSettled$ = makeObservable(
2107
+ () => {
2108
+ var _a;
2109
+ return (_a = options.onSettled) == null ? void 0 : _a.call(
2110
+ options,
2111
+ mutationData == null ? void 0 : mutationData.data,
2112
+ error,
2113
+ variables,
2114
+ restState.context
2115
+ );
2116
+ }
2117
+ );
2118
+ const settled$ = onOptionSettled$.pipe(
2119
+ rxjs.catchError((error2) => mutationData ? rxjs.of(mutationData) : rxjs.of(error2))
2120
+ );
2121
+ const result$ = rxjs.concat(success$, settled$).pipe(
2122
+ rxjs.toArray(),
2123
+ rxjs.map(
2124
+ () => error ? {
2125
+ error,
2126
+ data: void 0,
2127
+ variables,
2128
+ ...restState
2129
+ } : {
2130
+ status: "success",
2131
+ error,
2132
+ data: mutationData == null ? void 0 : mutationData.data,
2133
+ variables,
2134
+ failureCount: 0,
2135
+ failureReason: null,
2136
+ ...restState
2137
+ }
2138
+ ),
2139
+ rxjs.catchError(
2140
+ (error2) => onError(error2, restState.context, 0).pipe(
2141
+ rxjs.map((data) => ({
2142
+ ...data,
2143
+ data: void 0
2144
+ }))
2145
+ )
2146
+ )
2147
+ );
2148
+ return result$;
2149
+ })
2150
+ )
2151
+ ).pipe(
2152
+ rxjs.scan((acc, current) => {
2153
+ return {
2154
+ ...acc,
2155
+ ...current,
2156
+ data: current.data ?? acc.data,
2157
+ error: current.error ?? acc.error
2158
+ };
2159
+ }, getDefaultMutationState())
2160
+ );
2161
+ return mutation$;
2162
+ };
2163
+ class Mutation {
2164
+ constructor({
2165
+ options,
2166
+ mutationCache,
2167
+ state
2168
+ }) {
2169
+ __privateAdd(this, _observerCount, new rxjs.BehaviorSubject(0));
2170
+ __privateAdd(this, _cancelSubject, new rxjs.Subject());
2171
+ __privateAdd(this, _executeSubject, new rxjs.Subject());
2172
+ __publicField(this, "state", getDefaultMutationState());
2173
+ __publicField(this, "state$");
2174
+ __publicField(this, "options");
2175
+ __publicField(this, "observerCount$", __privateGet(this, _observerCount).asObservable());
2176
+ __publicField(this, "cancelled$", __privateGet(this, _cancelSubject).asObservable());
2177
+ this.options = options;
2178
+ this.state = state ?? this.state;
2179
+ const resetPendingState$ = __privateGet(this, _cancelSubject).pipe(
2180
+ rxjs.filter(() => this.state.status === "pending"),
2181
+ rxjs.map(() => ({
2182
+ status: "idle"
2183
+ }))
2184
+ );
2185
+ const executionState$ = __privateGet(this, _executeSubject).pipe(
2186
+ rxjs.switchMap(
2187
+ (variables) => executeMutation({
2188
+ options: {
2189
+ ...this.options,
2190
+ onMutate: (variables2) => {
2191
+ const onCacheMutate$ = makeObservable(
2192
+ () => {
2193
+ var _a, _b;
2194
+ return (_b = (_a = mutationCache.config).onMutate) == null ? void 0 : _b.call(
2195
+ _a,
2196
+ variables2,
2197
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
2198
+ this
2199
+ );
2200
+ }
2201
+ );
2202
+ const optionsOnMutate = () => {
2203
+ var _a, _b;
2204
+ return (_b = (_a = this.options).onMutate) == null ? void 0 : _b.call(_a, variables2);
2205
+ };
2206
+ const onOptionMutate$ = makeObservable(optionsOnMutate);
2207
+ const context$ = onCacheMutate$.pipe(
2208
+ rxjs.mergeMap(() => onOptionMutate$)
2209
+ );
2210
+ return context$;
2211
+ },
2212
+ onError: (error, variables2, context) => {
2213
+ const onCacheError$ = makeObservable(
2214
+ () => {
2215
+ var _a, _b;
2216
+ return (_b = (_a = mutationCache.config).onError) == null ? void 0 : _b.call(
2217
+ _a,
2218
+ error,
2219
+ variables2,
2220
+ context,
2221
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
2222
+ this
2223
+ );
2224
+ }
2225
+ );
2226
+ const onOptionError$ = makeObservable(
2227
+ () => {
2228
+ var _a, _b;
2229
+ return (_b = (_a = this.options).onError) == null ? void 0 : _b.call(_a, error, variables2, context);
2230
+ }
2231
+ );
2232
+ return rxjs.concat(onCacheError$, onOptionError$).pipe(rxjs.toArray());
2233
+ },
2234
+ onSettled: (data, error, variables2, context) => {
2235
+ const onCacheSuccess$ = makeObservable(
2236
+ () => {
2237
+ var _a, _b;
2238
+ return (_b = (_a = mutationCache.config).onSettled) == null ? void 0 : _b.call(
2239
+ _a,
2240
+ data,
2241
+ error,
2242
+ variables2,
2243
+ context,
2244
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
2245
+ this
2246
+ );
2247
+ }
2248
+ );
2249
+ const onOptionSettled$ = makeObservable(
2250
+ () => {
2251
+ var _a, _b;
2252
+ return (_b = (_a = this.options).onSettled) == null ? void 0 : _b.call(_a, data, error, variables2, context);
2253
+ }
2254
+ );
2255
+ return rxjs.concat(onCacheSuccess$, onOptionSettled$).pipe(rxjs.toArray());
2256
+ },
2257
+ onSuccess: (data, variables2, context) => {
2258
+ const onCacheSuccess$ = makeObservable(
2259
+ () => {
2260
+ var _a, _b;
2261
+ return (_b = (_a = mutationCache.config).onSuccess) == null ? void 0 : _b.call(
2262
+ _a,
2263
+ data,
2264
+ variables2,
2265
+ context,
2266
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
2267
+ this
2268
+ );
2269
+ }
2270
+ );
2271
+ const onOptionSuccess$ = makeObservable(
2272
+ () => {
2273
+ var _a, _b;
2274
+ return (_b = (_a = this.options).onSuccess) == null ? void 0 : _b.call(_a, data, variables2, context);
2275
+ }
2276
+ );
2277
+ return rxjs.concat(onCacheSuccess$, onOptionSuccess$).pipe(rxjs.toArray());
2278
+ }
2279
+ },
2280
+ state: this.state,
2281
+ variables
2282
+ }).pipe(rxjs.takeUntil(__privateGet(this, _cancelSubject)))
2283
+ )
2284
+ );
2285
+ const stateChange$ = rxjs.merge(resetPendingState$, executionState$);
2286
+ this.state$ = stateChange$.pipe(
2287
+ rxjs.startWith(this.state),
2288
+ rxjs.scan(
2289
+ (acc, partialState) => ({
2290
+ ...acc,
2291
+ ...partialState
2292
+ }),
2293
+ this.state
2294
+ ),
2295
+ distinctUntilStateChanged,
2296
+ rxjs.tap((value) => {
2297
+ this.state = value;
2298
+ }),
2299
+ rxjs.shareReplay(1),
2300
+ trackSubscriptions((count) => {
2301
+ __privateGet(this, _observerCount).next(count);
2302
+ })
2303
+ );
2304
+ }
2305
+ get meta() {
2306
+ return this.options.meta;
2307
+ }
2308
+ setOptions(options) {
2309
+ this.options = { ...this.options, ...options };
2310
+ }
2311
+ /**
2312
+ * @important
2313
+ * The resulting observable will complete as soon as the mutation
2314
+ * is over, unlike the state which can be re-subscribed later.
2315
+ */
2316
+ execute(variables) {
2317
+ __privateGet(this, _executeSubject).next(variables);
2318
+ __privateGet(this, _executeSubject).complete();
2319
+ return this.state$.pipe(observeUntilFinished);
2320
+ }
2321
+ continue() {
2322
+ return this.execute(this.state.variables);
2323
+ }
2324
+ /**
2325
+ * Cancel if needed and finalize the mutation.
2326
+ * The mutation will be garbage collected automatically
2327
+ * when no more observers are listening
2328
+ */
2329
+ cancel() {
2330
+ __privateGet(this, _cancelSubject).next();
2331
+ __privateGet(this, _cancelSubject).complete();
2332
+ }
2333
+ }
2334
+ _observerCount = new WeakMap();
2335
+ _cancelSubject = new WeakMap();
2336
+ _executeSubject = new WeakMap();
2337
+ const createPredicateForFilters = ({
2338
+ mutationKey,
2339
+ status,
2340
+ predicate,
2341
+ exact = true
2342
+ } = {}) => {
2343
+ const finalPredicate = (mutation) => {
2344
+ if (exact && mutationKey !== void 0 && mutation.options.mutationKey !== void 0 && !matchKey(mutation.options.mutationKey, mutationKey, { exact })) {
2345
+ return false;
2346
+ }
2347
+ if (!exact && mutationKey !== void 0 && mutation.options.mutationKey !== void 0 && !matchKey(mutation.options.mutationKey, mutationKey, { exact })) {
2348
+ return false;
2349
+ }
2350
+ if (status && mutation.state.status !== status) return false;
2351
+ if (predicate) {
2352
+ return predicate(mutation);
2353
+ }
2354
+ return true;
2355
+ };
2356
+ return finalPredicate;
2357
+ };
2358
+ class Store {
2359
+ constructor() {
2360
+ /**
2361
+ * @important
2362
+ * Query store. Could be turned into a map for more performance.
2363
+ */
2364
+ __publicField(this, "entriesSubject", new rxjs.BehaviorSubject([]));
2365
+ __publicField(this, "changeSubject", new rxjs.Subject());
2366
+ __publicField(this, "entries$", this.entriesSubject.pipe(rxjs.share()));
2367
+ __publicField(this, "added$", this.changeSubject.pipe(
2368
+ rxjs.filter(({ type }) => type === "added"),
2369
+ rxjs.map(({ entity }) => entity),
2370
+ rxjs.share()
2371
+ ));
2372
+ __publicField(this, "removed$", this.changeSubject.pipe(
2373
+ rxjs.filter(({ type }) => type === "removed"),
2374
+ rxjs.map(({ entity }) => entity),
2375
+ rxjs.share()
2376
+ ));
2377
+ __publicField(this, "stateChange$", rxjs.merge(
2378
+ this.entriesSubject.pipe(
2379
+ rxjs.first(),
2380
+ rxjs.mergeMap((entities) => rxjs.from(entities))
2381
+ ),
2382
+ this.added$
2383
+ ).pipe(
2384
+ rxjs.mergeMap(
2385
+ (entity) => entity.state$.pipe(
2386
+ rxjs.map(() => entity),
2387
+ rxjs.takeUntil(
2388
+ this.removed$.pipe(
2389
+ rxjs.filter((removedMutation) => removedMutation === entity)
2390
+ )
2391
+ )
2392
+ )
2393
+ ),
2394
+ rxjs.share()
2395
+ ));
2396
+ }
2397
+ getValues() {
2398
+ return this.entriesSubject.getValue();
2399
+ }
2400
+ remove(entity) {
2401
+ this.entriesSubject.next(
2402
+ this.entriesSubject.getValue().filter((toRemove) => entity !== toRemove)
2403
+ );
2404
+ this.changeSubject.next({ type: "removed", entity });
2405
+ }
2406
+ add(entity) {
2407
+ this.entriesSubject.next([...this.entriesSubject.getValue(), entity]);
2408
+ this.changeSubject.next({ type: "added", entity });
2409
+ }
2410
+ find(predicate) {
2411
+ return this.entriesSubject.getValue().find(predicate);
2412
+ }
2413
+ }
2414
+ class MutationCache {
2415
+ constructor(config = {}) {
2416
+ __privateAdd(this, _store, new Store());
2417
+ this.config = config;
2418
+ }
2419
+ build(client, options, state) {
2420
+ const mutation = new Mutation({
2421
+ mutationCache: this,
2422
+ options: client.defaultMutationOptions(options),
2423
+ state
2424
+ });
2425
+ mutation.state$.pipe(
2426
+ /**
2427
+ * Once a mutation is finished and there are no more observers than us
2428
+ * we start the process of cleaning it up based on gc settings
2429
+ */
2430
+ rxjs.filter(({ status }) => status === "success" || status === "error"),
2431
+ rxjs.switchMap(
2432
+ () => mutation.observerCount$.pipe(
2433
+ rxjs.filter((count) => count <= 1),
2434
+ rxjs.take(1)
2435
+ )
2436
+ ),
2437
+ // defaults to 5mn
2438
+ rxjs.switchMap(() => {
2439
+ return rxjs.timer(mutation.options.gcTime ?? 5 * 60 * 1e3);
2440
+ }),
2441
+ rxjs.take(1)
2442
+ ).subscribe({
2443
+ complete: () => {
2444
+ this.remove(mutation);
2445
+ }
2446
+ });
2447
+ __privateGet(this, _store).add(mutation);
2448
+ return mutation;
2449
+ }
2450
+ getAll() {
2451
+ return this.findAll();
2452
+ }
2453
+ remove(mutationToRemove) {
2454
+ const toRemove = __privateGet(this, _store).getValues().find((mutation) => {
2455
+ return mutation === mutationToRemove;
2456
+ });
2457
+ toRemove == null ? void 0 : toRemove.cancel();
2458
+ __privateGet(this, _store).remove(mutationToRemove);
2459
+ }
2460
+ find(filters) {
2461
+ const defaultedFilters = { exact: true, ...filters };
2462
+ const predicate = createPredicateForFilters(defaultedFilters);
2463
+ return __privateGet(this, _store).getValues().find((mutation) => predicate(mutation));
2464
+ }
2465
+ findAll(filters = {}) {
2466
+ const defaultedFilters = { exact: true, ...filters };
2467
+ const predicate = createPredicateForFilters(defaultedFilters);
2468
+ return __privateGet(this, _store).getValues().filter((mutation) => predicate(mutation)).map((mutation) => mutation);
2469
+ }
2470
+ observe() {
2471
+ const value$ = __privateGet(this, _store).stateChange$.pipe(rxjs.startWith());
2472
+ return value$;
2473
+ }
2474
+ /**
2475
+ * @important
2476
+ * ISO api react-query
2477
+ */
2478
+ subscribe(listener) {
2479
+ const sub = rxjs.merge(
2480
+ __privateGet(this, _store).added$.pipe(
2481
+ rxjs.tap((mutation) => {
2482
+ listener({
2483
+ type: "added",
2484
+ mutation
2485
+ });
2486
+ })
2487
+ ),
2488
+ __privateGet(this, _store).removed$.pipe(
2489
+ rxjs.tap((mutation) => {
2490
+ listener({
2491
+ type: "removed",
2492
+ mutation
2493
+ });
2494
+ })
2495
+ ),
2496
+ __privateGet(this, _store).stateChange$.pipe(
2497
+ rxjs.tap((mutation) => {
2498
+ listener({
2499
+ type: "updated",
2500
+ action: {
2501
+ ...mutation.state,
2502
+ type: "success"
2503
+ },
2504
+ mutation
2505
+ });
2506
+ })
2507
+ )
2508
+ ).subscribe();
2509
+ return () => {
2510
+ sub.unsubscribe();
2511
+ };
2512
+ }
2513
+ resumePausedMutations() {
2514
+ const pausedMutations = this.findAll({
2515
+ predicate: (mutation) => mutation.state.isPaused
2516
+ });
2517
+ if (!pausedMutations.length) return rxjs.EMPTY;
2518
+ const mutations$ = pausedMutations.map((mutation) => mutation.continue());
2519
+ return rxjs.combineLatest(mutations$);
2520
+ }
2521
+ clear() {
2522
+ this.getAll().forEach((mutation) => {
2523
+ this.remove(mutation);
2524
+ });
2525
+ }
2526
+ }
2527
+ _store = new WeakMap();
2528
+ function getDefaultState(options) {
2529
+ const data = typeof options.initialData === "function" ? options.initialData() : options.initialData;
2530
+ const hasData = typeof data !== "undefined";
2531
+ const initialDataUpdatedAt = hasData ? typeof options.initialDataUpdatedAt === "function" ? options.initialDataUpdatedAt() : options.initialDataUpdatedAt : 0;
2532
+ return {
2533
+ data,
2534
+ dataUpdateCount: 0,
2535
+ dataUpdatedAt: hasData ? initialDataUpdatedAt ?? Date.now() : 0,
2536
+ error: null,
2537
+ errorUpdateCount: 0,
2538
+ errorUpdatedAt: 0,
2539
+ fetchFailureCount: 0,
2540
+ fetchFailureReason: null,
2541
+ fetchMeta: null,
2542
+ isInvalidated: false,
2543
+ status: hasData ? "success" : "pending",
2544
+ fetchStatus: "idle"
2545
+ };
2546
+ }
2547
+ const delayUntilFocus = (source) => {
2548
+ return rxjs.defer(() => {
2549
+ if (!focusManager.isFocused()) {
2550
+ return focusManager.focusRegained$.pipe(rxjs.mergeMap(() => source));
2551
+ }
2552
+ return source;
2553
+ });
2554
+ };
2555
+ const delayOnNetworkMode = (options) => {
2556
+ let attempts = 0;
2557
+ return (source) => {
2558
+ const runWhenOnline$ = onlineManager.backToOnline$.pipe(
2559
+ rxjs.mergeMap(
2560
+ () => rxjs.merge(
2561
+ rxjs.of({ fetchStatus: "fetching" }),
2562
+ source
2563
+ )
2564
+ )
2565
+ );
2566
+ return rxjs.defer(() => {
2567
+ attempts++;
2568
+ if (!onlineManager.isOnline() && options.networkMode === "offlineFirst" && attempts > 1) {
2569
+ return rxjs.merge(
2570
+ rxjs.of({ fetchStatus: "paused" }),
2571
+ runWhenOnline$
2572
+ );
2573
+ }
2574
+ if (!onlineManager.isOnline() && options.networkMode !== "always" && options.networkMode !== "offlineFirst") {
2575
+ return rxjs.merge(
2576
+ rxjs.of({ fetchStatus: "paused" }),
2577
+ runWhenOnline$
2578
+ );
2579
+ }
2580
+ return source;
2581
+ });
2582
+ };
2583
+ };
2584
+ const completeFnIfNotMoreObservers = (observers$) => (source) => {
2585
+ const hasDataSubject = new rxjs.Subject();
2586
+ const hasDataAndNoObservers$ = hasDataSubject.pipe(
2587
+ rxjs.first(),
2588
+ /**
2589
+ * Since we set hasDataSubject synchronously, we need to wait
2590
+ * for the next tick to make sure observable chain received this data at least
2591
+ */
2592
+ rxjs.delay(1),
2593
+ rxjs.mergeMap(() => observers$.pipe(rxjs.filter((value) => value === 0)))
2594
+ );
2595
+ return source.pipe(
2596
+ rxjs.tap(() => {
2597
+ hasDataSubject.next();
2598
+ }),
2599
+ rxjs.takeUntil(hasDataAndNoObservers$)
2600
+ );
2601
+ };
2602
+ const executeQuery = (options) => {
2603
+ const defaultFn = async () => await Promise.reject(new Error("No query found"));
2604
+ if (process.env.NODE_ENV !== "production") {
2605
+ if (options.queryFn === skipToken) {
2606
+ console.error(
2607
+ `Attempted to invoke queryFn when set to skipToken. This is likely a configuration error. Query hash: '${options.queryHash}'`
2608
+ );
2609
+ }
2610
+ }
2611
+ let fnIsComplete = false;
2612
+ const queryFn = options.queryFn && options.queryFn !== skipToken ? options.queryFn : defaultFn;
2613
+ const abortController = new AbortController();
2614
+ const queryFnContext = {
2615
+ meta: options.meta,
2616
+ queryKey: options.queryKey
2617
+ };
2618
+ const addSignalProperty = (object) => {
2619
+ Object.defineProperty(object, "signal", {
2620
+ enumerable: true,
2621
+ get: () => {
2622
+ options.onSignalConsumed();
2623
+ return abortController.signal;
2624
+ }
2625
+ });
2626
+ };
2627
+ addSignalProperty(queryFnContext);
2628
+ const fn$ = typeof queryFn === "function" ? (
2629
+ // eslint-disable-next-line @typescript-eslint/promise-function-async
2630
+ makeObservable(
2631
+ () => queryFn(queryFnContext)
2632
+ )
2633
+ ) : queryFn;
2634
+ const execution$ = fn$.pipe(
2635
+ completeFnIfNotMoreObservers(options.observers$),
2636
+ rxjs.tap({
2637
+ complete: () => {
2638
+ fnIsComplete = true;
2639
+ }
2640
+ }),
2641
+ rxjs.map(
2642
+ (data) => ({
2643
+ data
2644
+ })
2645
+ ),
2646
+ // takeUntil(hasDataAndNoObservers$),
2647
+ delayOnNetworkMode(options),
2648
+ retryBackoff({
2649
+ ...options,
2650
+ retryAfter: () => rxjs.of(true).pipe(delayUntilFocus),
2651
+ catchError: (attempt, error) => rxjs.of({
2652
+ status: "error",
2653
+ fetchStatus: "idle",
2654
+ fetchFailureCount: attempt,
2655
+ fetchFailureReason: error,
2656
+ error
2657
+ }),
2658
+ caughtError: (attempt, error) => (
2659
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
2660
+ rxjs.of({
2661
+ fetchFailureCount: attempt,
2662
+ fetchFailureReason: error
2663
+ })
2664
+ )
2665
+ }),
2666
+ rxjs.mergeMap((state) => {
2667
+ if (!("data" in state)) return rxjs.of(state);
2668
+ return rxjs.of({
2669
+ ...state,
2670
+ status: "success",
2671
+ fetchStatus: "idle",
2672
+ fetchFailureCount: 0,
2673
+ fetchFailureReason: null,
2674
+ dataUpdatedAt: (/* @__PURE__ */ new Date()).getTime()
2675
+ }).pipe(
2676
+ /**
2677
+ * Because we don't know yet whether the fn is an observable or a promise we wait
2678
+ * for next tick and check if the function has been complete. This prevent having
2679
+ * two dispatch for promise where we would have extra "fetching" & "idle" dispatch
2680
+ *
2681
+ * @important
2682
+ * Another reason why this delay is necessary is to pass RQ tests. This is because
2683
+ * their flow expect a sequence of results to sometimes happens in a specific
2684
+ * way. If we have non promise function, we have results faster than what RQ expect
2685
+ * due to this library architecture and some variables are impossible to determine
2686
+ * correctly (eg: isFetchedAfterMount). There is nothing wrong, it's just a way to
2687
+ * force any function as promise (or more specifically to return in next tick).
2688
+ *
2689
+ * There is in theory no problem associated to that.
2690
+ */
2691
+ rxjs.delay(1),
2692
+ rxjs.map(
2693
+ (state2) => fnIsComplete ? state2 : { ...state2, fetchStatus: "fetching" }
2694
+ )
2695
+ );
2696
+ }),
2697
+ /**
2698
+ * When the fn complete we can release the fetch status, if it was already released
2699
+ * before shallow compare will not update the state, otherwise it's our chance to catch
2700
+ * the end of observable fn.
2701
+ */
2702
+ rxjs.endWith({ fetchStatus: "idle" }),
2703
+ rxjs.share()
2704
+ );
2705
+ const initialResult$ = rxjs.of({
2706
+ status: "pending",
2707
+ fetchStatus: onlineManager.isOnline() ? "fetching" : "paused"
2708
+ });
2709
+ return {
2710
+ state$: rxjs.merge(
2711
+ initialResult$,
2712
+ execution$
2713
+ // emitOnComplete$
2714
+ ).pipe(rxjs.share()),
2715
+ abortController
2716
+ };
2717
+ };
2718
+ class CancelledError {
2719
+ constructor(options) {
2720
+ __publicField(this, "revert");
2721
+ __publicField(this, "silent");
2722
+ this.revert = options == null ? void 0 : options.revert;
2723
+ this.silent = options == null ? void 0 : options.silent;
2724
+ }
2725
+ }
2726
+ const resetStyle = { backgroundColor: "transparent", color: "inherit" };
2727
+ function createLogger(env) {
2728
+ const _logger = {
2729
+ namespaces: [
2730
+ {
2731
+ name: "@reactjrx",
2732
+ style: { backgroundColor: "#d02f4e", color: "white" }
2733
+ }
2734
+ ],
2735
+ namespace(name, style) {
2736
+ const logger = createLogger();
2737
+ logger.namespaces.push({
2738
+ name,
2739
+ style: style ?? resetStyle
2740
+ });
2741
+ return logger;
2742
+ },
2743
+ printNamespaces() {
2744
+ return {
2745
+ namespaces: _logger.namespaces.map(({ name }) => `%c ${name} %c`).join(" "),
2746
+ styles: _logger.namespaces.reduce((acc, { style }) => {
2747
+ acc.push(
2748
+ `background-color: ${style.backgroundColor}; color: ${style.color};`
2749
+ );
2750
+ acc.push("background-color: transparent; color: inherit;");
2751
+ return acc;
2752
+ }, [])
2753
+ };
2754
+ },
2755
+ print(method, ...message) {
2756
+ return _logger;
2757
+ },
2758
+ printWithoutNamespace(method, ...message) {
2759
+ return _logger;
2760
+ },
2761
+ log(...message) {
2762
+ return _logger.print("log", ...message);
2763
+ },
2764
+ warn(...message) {
2765
+ return _logger.print("warn", ...message);
2766
+ },
2767
+ error(...message) {
2768
+ return _logger.print("error", ...message);
2769
+ },
2770
+ group(...message) {
2771
+ return _logger.print("group", ...message);
2772
+ },
2773
+ groupEnd() {
2774
+ return _logger;
2775
+ }
2776
+ };
2777
+ return _logger;
2778
+ }
2779
+ const Logger = createLogger();
2780
+ class Query {
2781
+ constructor(config) {
2782
+ __publicField(this, "queryKey");
2783
+ __publicField(this, "queryHash");
2784
+ __publicField(this, "gcTime");
2785
+ __publicField(this, "options");
2786
+ __privateAdd(this, _defaultOptions);
2787
+ __privateAdd(this, _initialState);
2788
+ __publicField(this, "state");
2789
+ // @todo to share with mutation
2790
+ __publicField(this, "executeSubject", new rxjs.Subject());
2791
+ __publicField(this, "cancelSubject", new rxjs.Subject());
2792
+ __publicField(this, "setDataSubject", new rxjs.Subject());
2793
+ __publicField(this, "invalidatedSubject", new rxjs.Subject());
2794
+ __publicField(this, "resetSubject", new rxjs.Subject());
2795
+ __publicField(this, "destroySubject", new rxjs.Subject());
2796
+ __publicField(this, "observersSubject", new rxjs.BehaviorSubject([]));
2797
+ __publicField(this, "abortSignalConsumed", false);
2798
+ __publicField(this, "observerCount$", this.observersSubject.asObservable().pipe(rxjs.map((observers) => observers.length)));
2799
+ __publicField(this, "observers$", this.observersSubject.asObservable());
2800
+ __publicField(this, "state$");
2801
+ __privateSet(this, _defaultOptions, config.defaultOptions);
2802
+ this.options = this.setOptions(config.options);
2803
+ this.queryKey = config.queryKey;
2804
+ this.queryHash = config.queryHash;
2805
+ __privateSet(this, _initialState, config.state ?? getDefaultState(this.options));
2806
+ this.state = __privateGet(this, _initialState);
2807
+ this.gcTime = this.updateGcTime(this.options.gcTime);
2808
+ this.state$ = rxjs.merge(
2809
+ this.resetSubject.pipe(
2810
+ rxjs.map(() => ({ command: "reset", state: __privateGet(this, _initialState) }))
2811
+ ),
2812
+ this.invalidatedSubject.pipe(
2813
+ rxjs.filter(() => !this.state.isInvalidated),
2814
+ rxjs.map(() => ({
2815
+ command: "invalidate",
2816
+ state: {
2817
+ isInvalidated: true
2818
+ }
2819
+ }))
2820
+ ),
2821
+ this.cancelSubject.pipe(
2822
+ rxjs.filter(() => {
2823
+ const isQueryOnError = this.state.error && this.state.status === "error";
2824
+ return !isQueryOnError;
2825
+ }),
2826
+ rxjs.map((options) => ({
2827
+ command: "cancel",
2828
+ state: {
2829
+ status: (options == null ? void 0 : options.revert) ? this.state.status : "error",
2830
+ fetchStatus: "idle",
2831
+ error: new CancelledError(options)
2832
+ }
2833
+ }))
2834
+ ),
2835
+ this.executeSubject.pipe(
2836
+ rxjs.mergeMap(() => {
2837
+ let noMoreObserversActive = false;
2838
+ const cancelFromNewRefetch$ = this.executeSubject.pipe(
2839
+ // should not be needed since the fetch return current promise
2840
+ // in case we don't cancel
2841
+ rxjs.filter((options) => (options == null ? void 0 : options.cancelRefetch) !== false)
2842
+ );
2843
+ const detectNoMoreObserversActive$ = this.observers$.pipe(
2844
+ rxjs.pairwise(),
2845
+ rxjs.tap(([prevObservers, currentObservers]) => {
2846
+ if (currentObservers.length === 0 && prevObservers.length > 0) {
2847
+ noMoreObserversActive = true;
2848
+ } else {
2849
+ noMoreObserversActive = false;
2850
+ }
2851
+ }),
2852
+ rxjs.ignoreElements()
2853
+ );
2854
+ const { state$: functionExecution$, abortController } = executeQuery({
2855
+ ...this.options,
2856
+ observers$: this.observerCount$,
2857
+ queryKey: this.queryKey,
2858
+ retry: (attempt, error) => {
2859
+ const retry = this.options.retry ?? true;
2860
+ if (typeof retry === "function") return retry(attempt, error);
2861
+ if (typeof retry === "boolean") return retry;
2862
+ return attempt < retry;
2863
+ },
2864
+ retryAfterDelay: () => {
2865
+ if (noMoreObserversActive) return false;
2866
+ return true;
2867
+ },
2868
+ onSignalConsumed: () => {
2869
+ this.abortSignalConsumed = true;
2870
+ }
2871
+ });
2872
+ const executionAbortedFromSignal$ = this.observerCount$.pipe(
2873
+ rxjs.filter((count) => count === 0 && this.abortSignalConsumed),
2874
+ rxjs.tap(() => {
2875
+ this.cancelSubject.next({ revert: true });
2876
+ })
2877
+ );
2878
+ const cancelExecution$ = rxjs.merge(
2879
+ this.cancelSubject,
2880
+ cancelFromNewRefetch$,
2881
+ this.resetSubject,
2882
+ executionAbortedFromSignal$
2883
+ ).pipe(
2884
+ rxjs.tap(() => {
2885
+ if (this.abortSignalConsumed) {
2886
+ abortController.abort();
2887
+ }
2888
+ })
2889
+ );
2890
+ return rxjs.merge(functionExecution$, detectNoMoreObserversActive$).pipe(
2891
+ rxjs.map((state) => ({
2892
+ command: "execute",
2893
+ state
2894
+ })),
2895
+ rxjs.takeUntil(cancelExecution$)
2896
+ );
2897
+ })
2898
+ ),
2899
+ this.setDataSubject.pipe(
2900
+ rxjs.map(({ data, options }) => ({
2901
+ command: "setData",
2902
+ state: {
2903
+ status: "success",
2904
+ data,
2905
+ dataUpdatedAt: (options == null ? void 0 : options.updatedAt) !== void 0 ? options.updatedAt : (/* @__PURE__ */ new Date()).getTime()
2906
+ }
2907
+ }))
2908
+ )
2909
+ ).pipe(
2910
+ reduceState({
2911
+ initialState: this.state,
2912
+ getOptions: () => this.options,
2913
+ getState: () => this.state
2914
+ }),
2915
+ rxjs.startWith(__privateGet(this, _initialState)),
2916
+ rxjs.distinctUntilChanged(shallowEqual),
2917
+ rxjs.tap((state) => {
2918
+ this.state = state;
2919
+ }),
2920
+ rxjs.catchError((e) => {
2921
+ Logger.error(e);
2922
+ throw e;
2923
+ }),
2924
+ rxjs.takeUntil(this.destroySubject),
2925
+ rxjs.shareReplay({ bufferSize: 1, refCount: false })
2926
+ );
2927
+ }
2928
+ setOptions(options) {
2929
+ this.options = { ...__privateGet(this, _defaultOptions), ...options };
2930
+ this.updateGcTime(this.options.gcTime);
2931
+ return this.options;
2932
+ }
2933
+ get meta() {
2934
+ return this.options.meta;
2935
+ }
2936
+ get success$() {
2937
+ return this.state$.pipe(
2938
+ rxjs.map(({ data, status }) => ({ data, status })),
2939
+ rxjs.distinctUntilChanged(shallowEqual),
2940
+ rxjs.filter(({ status }) => status === "success")
2941
+ );
2942
+ }
2943
+ get error$() {
2944
+ return this.state$.pipe(
2945
+ rxjs.map(({ error, status }) => ({ error, status })),
2946
+ rxjs.distinctUntilChanged(shallowEqual),
2947
+ rxjs.filter(({ status }) => status === "error")
2948
+ );
2949
+ }
2950
+ get settled$() {
2951
+ return this.state$.pipe(
2952
+ rxjs.map(({ status }) => ({ status })),
2953
+ rxjs.distinctUntilChanged(shallowEqual),
2954
+ rxjs.filter(({ status }) => status === "success" || status === "error")
2955
+ );
2956
+ }
2957
+ observe(observer) {
2958
+ const state$ = this.state$.pipe(
2959
+ rxjs.tap({
2960
+ subscribe: () => {
2961
+ this.observersSubject.next([
2962
+ observer,
2963
+ ...this.observersSubject.getValue()
2964
+ ]);
2965
+ },
2966
+ unsubscribe: () => {
2967
+ this.observersSubject.next(
2968
+ this.observersSubject.getValue().filter((item) => item !== observer)
2969
+ );
2970
+ }
2971
+ })
2972
+ );
2973
+ return state$;
2974
+ }
2975
+ getObserversCount() {
2976
+ return this.observersSubject.getValue().length;
2977
+ }
2978
+ // @todo this can be shared with mutation
2979
+ updateGcTime(newGcTime) {
2980
+ this.gcTime = Math.max(
2981
+ this.gcTime || 0,
2982
+ newGcTime ?? (isServer ? Infinity : 5 * 60 * 1e3)
2983
+ );
2984
+ return this.gcTime;
2985
+ }
2986
+ isActive() {
2987
+ return this.observersSubject.getValue().some((observer) => observer.options.enabled !== false);
2988
+ }
2989
+ isDisabled() {
2990
+ return this.getObserversCount() > 0 && !this.isActive();
2991
+ }
2992
+ isStale() {
2993
+ return this.state.isInvalidated || !this.state.dataUpdatedAt || this.observersSubject.getValue().some((observer) => observer.getCurrentResult().isStale);
2994
+ }
2995
+ isStaleByTime(staleTime = 0) {
2996
+ return this.state.isInvalidated || !this.state.dataUpdatedAt || !timeUntilStale(this.state.dataUpdatedAt, staleTime);
2997
+ }
2998
+ async getFetchResultAsPromise() {
2999
+ return await new Promise((resolve, reject) => {
3000
+ this.state$.pipe(takeUntilFinished, rxjs.last()).subscribe({
3001
+ error: reject,
3002
+ next: (data) => {
3003
+ if (data.error) {
3004
+ reject(data.error);
3005
+ } else {
3006
+ resolve(data.data);
3007
+ }
3008
+ }
3009
+ });
3010
+ });
3011
+ }
3012
+ async fetch(options, fetchOptions) {
3013
+ const { cancelRefetch } = fetchOptions ?? {};
3014
+ if (this.state.fetchStatus !== "idle") {
3015
+ const shouldCancelRequest = !!this.state.dataUpdatedAt && cancelRefetch;
3016
+ if (!shouldCancelRequest) {
3017
+ return await this.getFetchResultAsPromise();
3018
+ }
3019
+ }
3020
+ if (options) {
3021
+ this.setOptions(options);
3022
+ }
3023
+ this.executeSubject.next(fetchOptions);
3024
+ return await this.getFetchResultAsPromise();
3025
+ }
3026
+ setData(newData, options) {
3027
+ const data = replaceData(this.state.data, newData, this.options);
3028
+ this.setDataSubject.next({ data, options });
3029
+ return data;
3030
+ }
3031
+ invalidate() {
3032
+ this.invalidatedSubject.next();
3033
+ }
3034
+ async cancel(options) {
3035
+ this.cancelSubject.next(options);
3036
+ }
3037
+ // @todo merge with mutation
3038
+ destroy() {
3039
+ this.destroySubject.next();
3040
+ this.destroySubject.complete();
3041
+ this.executeSubject.complete();
3042
+ }
3043
+ // @todo merge with mutation
3044
+ reset() {
3045
+ this.resetSubject.next();
3046
+ }
3047
+ }
3048
+ _defaultOptions = new WeakMap();
3049
+ _initialState = new WeakMap();
3050
+ class QueryCache {
3051
+ // protected mountSubscriptions: Subscription[]
3052
+ constructor(config = {}) {
3053
+ // readonly #queries: QueryStore = new Map<string, Query>()
3054
+ __privateAdd(this, _notifySubject, new rxjs.Subject());
3055
+ __privateAdd(this, _store2, new Store());
3056
+ this.config = config;
3057
+ }
3058
+ mount() {
3059
+ }
3060
+ unmount() {
3061
+ }
3062
+ notify(event) {
3063
+ __privateGet(this, _notifySubject).next(event);
3064
+ }
3065
+ observeIsFetching(filters) {
3066
+ const value$ = __privateGet(this, _store2).stateChange$.pipe(
3067
+ // we force a first result
3068
+ rxjs.startWith(),
3069
+ rxjs.map(() => {
3070
+ const filteredEntities = this.findAll({
3071
+ ...filters,
3072
+ fetchStatus: "fetching"
3073
+ });
3074
+ return filteredEntities.length;
3075
+ }),
3076
+ rxjs.distinctUntilChanged()
3077
+ );
3078
+ return value$;
3079
+ }
3080
+ getAll() {
3081
+ return [...__privateGet(this, _store2).getValues()];
3082
+ }
3083
+ findAll(filters = {}) {
3084
+ const queries = this.getAll();
3085
+ return Object.keys(filters).length > 0 ? queries.filter((query) => matchQuery(filters, query)) : queries;
3086
+ }
3087
+ build(client, options, state) {
3088
+ const queryKey = options.queryKey ?? [nanoid()];
3089
+ const queryHash = options.queryHash ?? hashQueryKeyByOptions(queryKey, options);
3090
+ let query = this.get(queryHash);
3091
+ if (!query) {
3092
+ query = new Query({
3093
+ cache: this,
3094
+ queryKey,
3095
+ queryHash,
3096
+ options: client.defaultQueryOptions(options),
3097
+ state,
3098
+ defaultOptions: client.getQueryDefaults(queryKey)
3099
+ });
3100
+ this.add(query);
3101
+ }
3102
+ return query;
3103
+ }
3104
+ add(query) {
3105
+ if (!__privateGet(this, _store2).find((entity) => entity.queryHash === query.queryHash)) {
3106
+ __privateGet(this, _store2).add(query);
3107
+ const noMoreObservers$ = query.observerCount$.pipe(
3108
+ rxjs.filter((count) => count < 1),
3109
+ rxjs.take(1)
3110
+ );
3111
+ query.success$.subscribe(() => {
3112
+ var _a, _b;
3113
+ (_b = (_a = this.config).onSuccess) == null ? void 0 : _b.call(_a, query.state.data, query);
3114
+ });
3115
+ query.error$.subscribe(() => {
3116
+ var _a, _b;
3117
+ (_b = (_a = this.config).onError) == null ? void 0 : _b.call(_a, query.state.error, query);
3118
+ });
3119
+ query.settled$.subscribe(() => {
3120
+ var _a, _b;
3121
+ (_b = (_a = this.config).onSettled) == null ? void 0 : _b.call(
3122
+ _a,
3123
+ query.state.data,
3124
+ query.state.error,
3125
+ query
3126
+ );
3127
+ });
3128
+ query.state$.pipe(
3129
+ /**
3130
+ * Once a mutation is finished and there are no more observers than us
3131
+ * we start the process of cleaning it up based on gc settings
3132
+ */
3133
+ isQueryFinished,
3134
+ rxjs.switchMap((isFinished) => {
3135
+ return !isFinished ? rxjs.NEVER : noMoreObservers$.pipe(
3136
+ // defaults to 5mn
3137
+ rxjs.switchMap(() => {
3138
+ if (query.gcTime === Infinity) return rxjs.NEVER;
3139
+ setTimeout(rxjs.noop, query.gcTime);
3140
+ return rxjs.timer(query.gcTime);
3141
+ })
3142
+ );
3143
+ }),
3144
+ rxjs.take(1)
3145
+ ).subscribe({
3146
+ complete: () => {
3147
+ this.remove(query);
3148
+ }
3149
+ });
3150
+ }
3151
+ }
3152
+ get(queryHash) {
3153
+ return __privateGet(this, _store2).find((query) => query.queryHash === queryHash);
3154
+ }
3155
+ find(filters) {
3156
+ const defaultedFilters = { exact: true, ...filters };
3157
+ return this.getAll().find(
3158
+ (query) => matchQuery(defaultedFilters, query)
3159
+ );
3160
+ }
3161
+ subscribe(fn) {
3162
+ const sub = rxjs.merge(
3163
+ __privateGet(this, _notifySubject).pipe(rxjs.tap(fn))
3164
+ // this.#store.added$.pipe(
3165
+ // mergeMap((query) => {
3166
+ // fn({
3167
+ // query,
3168
+ // type: "added"
3169
+ // })
3170
+ // return query.observers$.pipe(
3171
+ // tap((observer) => {
3172
+ // fn({
3173
+ // type: "observerAdded",
3174
+ // observer: observer as unknown as QueryObserver<
3175
+ // any,
3176
+ // any,
3177
+ // any,
3178
+ // any,
3179
+ // any
3180
+ // >,
3181
+ // query
3182
+ // })
3183
+ // })
3184
+ // )
3185
+ // })
3186
+ // )
3187
+ ).subscribe();
3188
+ return () => {
3189
+ sub.unsubscribe();
3190
+ };
3191
+ }
3192
+ remove(query) {
3193
+ const queryInMap = __privateGet(this, _store2).find((entity) => entity === query);
3194
+ if (queryInMap) {
3195
+ query.destroy();
3196
+ if (queryInMap === query) {
3197
+ __privateGet(this, _store2).remove(query);
3198
+ }
3199
+ }
3200
+ }
3201
+ clear() {
3202
+ }
3203
+ }
3204
+ _notifySubject = new WeakMap();
3205
+ _store2 = new WeakMap();
3206
+ class QueryClient {
3207
+ // #destroy = () => {}
3208
+ constructor({
3209
+ mutationCache,
3210
+ queryCache,
3211
+ defaultOptions
3212
+ } = {}) {
3213
+ __privateAdd(this, _mutationCache);
3214
+ __privateAdd(this, _queryCache);
3215
+ __privateAdd(this, _mutationDefaults, /* @__PURE__ */ new Map());
3216
+ __privateAdd(this, _queryDefaults, /* @__PURE__ */ new Map());
3217
+ __privateAdd(this, _defaultOptions2);
3218
+ __privateSet(this, _mutationCache, mutationCache ?? new MutationCache());
3219
+ __privateSet(this, _queryCache, queryCache ?? new QueryCache());
3220
+ __privateSet(this, _defaultOptions2, defaultOptions ?? {});
3221
+ }
3222
+ mount() {
3223
+ }
3224
+ unmount() {
3225
+ }
3226
+ getMutationCache() {
3227
+ return __privateGet(this, _mutationCache);
3228
+ }
3229
+ getQueryCache() {
3230
+ return __privateGet(this, _queryCache);
3231
+ }
3232
+ defaultMutationOptions(options) {
3233
+ return {
3234
+ ...__privateGet(this, _defaultOptions2).mutations,
3235
+ ...(options == null ? void 0 : options.mutationKey) && this.getMutationDefaults(options.mutationKey),
3236
+ ...options
3237
+ };
3238
+ }
3239
+ defaultQueryOptions(options) {
3240
+ if (options._defaulted) {
3241
+ return options;
3242
+ }
3243
+ const defaultedOptions = {
3244
+ ...__privateGet(this, _defaultOptions2).queries,
3245
+ ...this.getQueryDefaults(options.queryKey),
3246
+ ...options,
3247
+ _defaulted: true
3248
+ };
3249
+ if (!defaultedOptions.queryHash) {
3250
+ defaultedOptions.queryHash = hashQueryKeyByOptions(
3251
+ defaultedOptions.queryKey,
3252
+ defaultedOptions
3253
+ );
3254
+ }
3255
+ if (defaultedOptions.refetchOnReconnect === void 0) {
3256
+ defaultedOptions.refetchOnReconnect = defaultedOptions.networkMode !== "always";
3257
+ }
3258
+ if (defaultedOptions.throwOnError === void 0) {
3259
+ defaultedOptions.throwOnError = !!defaultedOptions.suspense;
3260
+ }
3261
+ if (!defaultedOptions.networkMode && defaultedOptions.persister) {
3262
+ defaultedOptions.networkMode = "offlineFirst";
3263
+ }
3264
+ if (defaultedOptions.enabled !== true && defaultedOptions.queryFn === skipToken) {
3265
+ defaultedOptions.enabled = false;
3266
+ }
3267
+ return defaultedOptions;
3268
+ }
3269
+ async fetchQuery(options) {
3270
+ const defaultedOptions = this.defaultQueryOptions(options);
3271
+ if (typeof defaultedOptions.retry === "undefined") {
3272
+ defaultedOptions.retry = false;
3273
+ }
3274
+ const query = __privateGet(this, _queryCache).build(this, defaultedOptions);
3275
+ return query.isStaleByTime(defaultedOptions.staleTime) ? await query.fetch(defaultedOptions) : await Promise.resolve(query.state.data);
3276
+ }
3277
+ async prefetchQuery(options) {
3278
+ await this.fetchQuery(options).then(rxjs.noop).catch(rxjs.noop);
3279
+ }
3280
+ async resetQueries(filters, options) {
3281
+ const queryCache = __privateGet(this, _queryCache);
3282
+ const refetchFilters = {
3283
+ type: "active",
3284
+ ...filters
3285
+ };
3286
+ queryCache.findAll(filters).forEach((query) => {
3287
+ query.reset();
3288
+ });
3289
+ await this.refetchQueries(refetchFilters, options);
3290
+ }
3291
+ async refetchQueries(filters = {}, options) {
3292
+ const fetchOptions = {
3293
+ ...options,
3294
+ cancelRefetch: (options == null ? void 0 : options.cancelRefetch) ?? true
3295
+ };
3296
+ const promises = __privateGet(this, _queryCache).findAll(filters).filter((query) => !query.isDisabled()).map(async (query) => {
3297
+ let promise = query.fetch(void 0, fetchOptions);
3298
+ if (!fetchOptions.throwOnError) {
3299
+ promise = promise.catch(rxjs.noop);
3300
+ }
3301
+ return query.state.fetchStatus === "paused" ? void 0 : await promise;
3302
+ });
3303
+ await Promise.all(promises).then(rxjs.noop);
3304
+ }
3305
+ getQueryData(queryKey) {
3306
+ var _a;
3307
+ const options = this.defaultQueryOptions({ queryKey });
3308
+ return (_a = __privateGet(this, _queryCache).get(options.queryHash)) == null ? void 0 : _a.state.data;
3309
+ }
3310
+ setQueryData(queryKey, updater, options) {
3311
+ const defaultedOptions = this.defaultQueryOptions({ queryKey });
3312
+ const query = __privateGet(this, _queryCache).get(
3313
+ defaultedOptions.queryHash
3314
+ );
3315
+ const prevData = query == null ? void 0 : query.state.data;
3316
+ const data = functionalUpdate(updater, prevData);
3317
+ if (data === void 0) {
3318
+ return void 0;
3319
+ }
3320
+ return __privateGet(this, _queryCache).build(this, defaultedOptions).setData(data, { ...options, manual: true });
3321
+ }
3322
+ getMutationDefaults(mutationKey) {
3323
+ const defaults = [...__privateGet(this, _mutationDefaults).values()];
3324
+ let result = {};
3325
+ defaults.forEach((queryDefault) => {
3326
+ if (matchKey(mutationKey, queryDefault.mutationKey)) {
3327
+ result = { ...result, ...queryDefault.defaultOptions };
3328
+ }
3329
+ });
3330
+ return result;
3331
+ }
3332
+ getQueryState(queryKey) {
3333
+ var _a;
3334
+ return (_a = __privateGet(this, _queryCache).find({ queryKey })) == null ? void 0 : _a.state;
3335
+ }
3336
+ setMutationDefaults(mutationKey, options) {
3337
+ __privateGet(this, _mutationDefaults).set(hashKey(mutationKey), {
3338
+ mutationKey,
3339
+ defaultOptions: options
3340
+ });
3341
+ }
3342
+ setQueryDefaults(queryKey, options) {
3343
+ __privateGet(this, _queryDefaults).set(hashKey(queryKey), {
3344
+ queryKey,
3345
+ defaultOptions: options
3346
+ });
3347
+ }
3348
+ getQueryDefaults(queryKey) {
3349
+ const defaults = [...__privateGet(this, _queryDefaults).values()];
3350
+ let result = {};
3351
+ defaults.forEach((queryDefault) => {
3352
+ if (partialMatchKey(queryKey, queryDefault.queryKey)) {
3353
+ result = { ...result, ...queryDefault.defaultOptions };
3354
+ }
3355
+ });
3356
+ return result;
3357
+ }
3358
+ removeQueries(filters) {
3359
+ const queryCache = __privateGet(this, _queryCache);
3360
+ queryCache.findAll(filters).forEach((query) => {
3361
+ queryCache.remove(query);
3362
+ });
3363
+ }
3364
+ async cancelQueries(filters = {}, cancelOptions = {}) {
3365
+ const defaultedCancelOptions = { revert: true, ...cancelOptions };
3366
+ const promises = __privateGet(this, _queryCache).findAll(filters).map(async (query) => {
3367
+ await query.cancel(defaultedCancelOptions);
3368
+ });
3369
+ await Promise.all(promises).then(rxjs.noop).catch(rxjs.noop);
3370
+ }
3371
+ async invalidateQueries(filters = {}, options = {}) {
3372
+ __privateGet(this, _queryCache).findAll(filters).forEach((query) => {
3373
+ query.invalidate();
3374
+ });
3375
+ if (filters.refetchType === "none") {
3376
+ await Promise.resolve();
3377
+ return;
3378
+ }
3379
+ const refetchFilters = {
3380
+ ...filters,
3381
+ type: filters.refetchType ?? filters.type ?? "active"
3382
+ };
3383
+ await this.refetchQueries(refetchFilters, options);
3384
+ }
3385
+ async resumePausedMutations() {
3386
+ return await rxjs.lastValueFrom(__privateGet(this, _mutationCache).resumePausedMutations());
3387
+ }
3388
+ isFetching(filters) {
3389
+ return __privateGet(this, _queryCache).findAll({ ...filters, fetchStatus: "fetching" }).length;
3390
+ }
3391
+ clear() {
3392
+ __privateGet(this, _queryCache).clear();
3393
+ __privateGet(this, _mutationCache).clear();
3394
+ }
3395
+ }
3396
+ _mutationCache = new WeakMap();
3397
+ _queryCache = new WeakMap();
3398
+ _mutationDefaults = new WeakMap();
3399
+ _queryDefaults = new WeakMap();
3400
+ _defaultOptions2 = new WeakMap();
3401
+ exports.MutationCache = MutationCache;
3402
+ exports.QueryCache = QueryCache;
3403
+ exports.QueryClient = QueryClient;
3404
+ exports.QueryClientProvider = QueryClientProvider;
3405
+ exports.SIGNAL_RESET = SIGNAL_RESET;
3406
+ exports.arrayEqual = arrayEqual;
3407
+ exports.createLocalStorageAdapter = createLocalStorageAdapter;
3408
+ exports.createLocalforageAdapter = createLocalforageAdapter;
3409
+ exports.exponentialBackoffDelay = exponentialBackoffDelay;
3410
+ exports.getDelay = getDelay;
3411
+ exports.isDefined = isDefined;
3412
+ exports.isPromiseLike = isPromiseLike;
3413
+ exports.isServer = isServer;
3414
+ exports.retryBackoff = retryBackoff;
3415
+ exports.signal = signal;
3416
+ exports.useBehaviorSubject = useBehaviorSubject;
3417
+ exports.useEffectOnce = useEffectOnce;
3418
+ exports.useForeverQuery = useForeverQuery;
3419
+ exports.useLiveRef = useLiveRef;
3420
+ exports.useMount = useMount;
3421
+ exports.useMutation = useMutation;
3422
+ exports.useObservableState = useObservableState;
3423
+ exports.useObserve = useObserve;
3424
+ exports.useObserveCallback = useObserveCallback;
3425
+ exports.usePersistSignals = usePersistSignals;
3426
+ exports.useQuery = useQuery;
3427
+ exports.useQueryClient = useQueryClient;
3428
+ exports.useSignal = useSignal;
3429
+ exports.useSignalValue = useSignalValue;
3430
+ exports.useSubject = useSubject;
3431
+ exports.useSubscribe = useSubscribe;
3432
+ exports.useSubscribeEffect = useSubscribeEffect;
3433
+ exports.useUnmountObservable = useUnmountObservable;