tsdf 8.0.0-beta.3 → 8.0.0-beta.5

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