tsdf 8.0.0-beta.1 → 8.0.0-beta.3
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.cjs +1 -0
- package/dist/main.d.ts +269 -0
- package/dist/main.js +1 -0
- package/package.json +4 -1
- package/.eslintignore +0 -3
- package/.eslintrc.cjs +0 -119
- package/.gitattributes +0 -22
- package/.prettierrc +0 -6
- package/.vscode/settings.json +0 -3
- package/.vscode/tasks.json +0 -35
- package/fetch-orquestrator-scenarios.excalidraw +0 -10115
- package/scripts/check-if-is-sync.sh +0 -6
- package/src/collectionFetchOrquestrator.ts +0 -23
- package/src/collectionStore.ts +0 -608
- package/src/documentStore.ts +0 -272
- package/src/fetchOrquestrator.ts +0 -335
- package/src/listQueryStore.ts +0 -1190
- package/src/main.ts +0 -22
- package/src/storeShared.ts +0 -5
- package/src/useEnsureIsLoaded.ts +0 -50
- package/src/utils/filterAndMap.ts +0 -20
- package/src/utils/getCacheId.ts +0 -19
- package/src/utils/hooks.ts +0 -110
- package/src/utils/isObject.ts +0 -3
- package/src/utils/math.ts +0 -7
- package/src/utils/serializableClone.ts +0 -3
- package/src/utils/useLatestValue.ts +0 -16
- package/test/__snapshots__/listQueryStore.test.ts.snap +0 -146
- package/test/__snapshots__/listQueryStoreHooks.test.ts.snap +0 -9
- package/test/collectionStore.test.ts +0 -523
- package/test/collectionStoreHooks.test.tsx +0 -651
- package/test/documentStore.test.ts +0 -183
- package/test/documentStoreHooks.test.tsx +0 -857
- package/test/fetchOrquestrator.test.ts +0 -913
- package/test/listQueryStore.test.ts +0 -1158
- package/test/listQueryStoreHooks.test.tsx +0 -662
- package/test/listQueryStoreHooks2.test.tsx +0 -483
- package/test/listQueryStoreHooksMutations.test.tsx +0 -764
- package/test/mocks/fetchMock.ts +0 -296
- package/test/mocks/fetchOrquestratorEnv.ts +0 -370
- package/test/setup/setup.ts +0 -109
- package/test/testHelpers.test.ts +0 -88
- package/test/utils/RenderObjValues.tsx +0 -23
- package/test/utils/arrayUtils.ts +0 -13
- package/test/utils/createDefaultListQueryStore.ts +0 -275
- package/test/utils/createOrVariations.ts +0 -48
- package/test/utils/dedent.ts +0 -50
- package/test/utils/delayCall.ts +0 -25
- package/test/utils/math.ts +0 -3
- package/test/utils/objectUtils.ts +0 -18
- package/test/utils/range.ts +0 -19
- package/test/utils/sleep.ts +0 -3
- package/test/utils/storeUtils.ts +0 -460
- package/tsconfig.json +0 -24
- package/tsconfig.prod.json +0 -9
- package/tsup.config.ts +0 -12
- package/vitest.config.ts +0 -10
package/dist/main.cjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var Ve=Object.create;var Fe=Object.defineProperty;var ke=Object.getOwnPropertyDescriptor;var Ue=Object.getOwnPropertyNames;var We=Object.getPrototypeOf,je=Object.prototype.hasOwnProperty;var ze=(r,c)=>{for(var S in c)Fe(r,S,{get:c[S],enumerable:!0})},Me=(r,c,S,g)=>{if(c&&typeof c=="object"||typeof c=="function")for(let T of Ue(c))!je.call(r,T)&&T!==S&&Fe(r,T,{get:()=>c[T],enumerable:!(g=ke(c,T))||g.enumerable});return r};var me=(r,c,S)=>(S=r!=null?Ve(We(r)):{},Me(c||!r||!r.__esModule?Fe(S,"default",{value:r,enumerable:!0}):S,r)),_e=r=>Me(Fe({},"__esModule",{value:!0}),r);var Ye={};ze(Ye,{newTSDFCollectionStore:()=>Ne,newTSDFDocumentStore:()=>xe,newTSDFListQueryStore:()=>Ke});module.exports=_e(Ye);var Oe=me(require("immer"),1),qe=me(require("mitt"),1),Pe=require("react"),we=require("t-state");function ge({fetchFn:r,on:c,mediumPriorityThrottleMs:S=10,lowPriorityThrottleMs:g=200,dynamicRealtimeThrottleMs:T}){let m={e:null,r:null,t:null},U=0,C=0,O=!1,f=0,M=0,y=[],Q=!1,J=0;function Y(a){M=a}function W(a){f=a}function j(){if(m.r){c?.("scheduled-fetch-started");let a=m.r.params;m.r=null,E(a,Date.now())}}function z(){O=!0,J=C,m.e=null;let a=Qe();return U=a,()=>ae(a)}function ae(a){return a===U?(O=!1,y.length>0&&(y.forEach(s=>s()),y=[]),j(),!0):!1}function ue(){return m}async function E(a,s){if(m.e)throw new Error("[tsdf] Fetch already in progress");let t=Qe();C=t,Q=!1,m.e={startTime:s,onEnd:[]};let F=f;f=s;function b(){let X=t!==C||O||t<=J;return Q=X,X}let p=await r({shouldAbort:b,getStartTime:()=>s},a),P=ue();if(!P.e)return f=F,!1;p&&(M=Date.now()-s),P.t&&(clearTimeout(P.t.timeoutId),m.t=null);let N=P.e.onEnd;return P.e=null,N.length>0&&N.forEach(X=>X()),j(),!0}function v(a,s){let t=Date.now();return T&&a==="realtimeUpdate"&&Z(t,s)?"rt-scheduled":B(a,t)?"skipped":H(a,s)?"scheduled":(E(s,t),"started")}function B(a,s){return!!(a==="highPriority"&&m.e&&s-m.e.startTime<S||a==="lowPriority"&&(m.e||m.r||O||f&&s-f<g))}function H(a,s){let t=(()=>a==="lowPriority"?!1:!!m.e||!!O)();return t&&(m.r={params:s}),t}function G(a,s){if(!T)return!1;let t=a-(f+M),F=T(M);if(t>=F)return!1;let b=F-t;return m.t={timeoutId:window.setTimeout(()=>{m.t=null,c?.("scheduled-rt-fetch-started"),E(s,Date.now())},b)},!0}function Z(a,s){return!M||!f||!T?!1:m.t?!0:m.e?(m.e.onEnd.push(()=>{G(Date.now(),s)}),!0):O?(y.push(()=>{G(Date.now(),s)||(c?.("scheduled-rt-fetch-started"),v("highPriority",s))}),!0):!!G(a,s)}function de(a){m.e&&m.e.onEnd.push(a)}async function l(a){return v("highPriority",a),m.e&&await new Promise(s=>{de(()=>s(!0))}),Q}return{scheduleFetch:v,awaitFetch:l,startMutation:z,get hasPendingFetch(){return!!m.e||!!m.r||!!m.t},get fetchIsInProgress(){return!!m.e},get mutationIsInProgress(){return O},setLastFetchDurantion:Y,setLastFetchStartTime:W}}var Je=0;function Qe(){return++Je}var Le=me(require("mitt"),1),Te=require("react");var A=require("react"),Ie=require("t-state");function Be(r,c=Ie.deepEqual){let S=(0,A.useRef)(),g=(0,A.useRef)(0);return c(r,S.current)||(S.current=r,g.current+=1),[g.current]}function ye(r,c){return(0,A.useMemo)(r,Be(c))}function Ge(r){let c=(0,A.useRef)({insideEffect:r,insideMemo:r});return c.current.insideMemo=r,(0,A.useLayoutEffect)(()=>{c.current.insideEffect=r}),c.current}function oe(r,c,S){let g=Ge(S);(0,A.useLayoutEffect)(()=>{let T=m=>{g.insideEffect(m)};return r.on(c,T),()=>{r.off(c,T)}},[r,c,g])}function He(r,c){let S=(0,A.useRef)(c);return(0,A.useEffect)(()=>{S.current=r}),S.current}function De(r,c,{equalityFn:S=Ie.shallowEqual,callOnMount:g,layoutEffect:T}={}){let m=T?A.useLayoutEffect:A.useEffect,U=He(r,g?void 0:r);m(()=>{if(!S(r,U))return c({prev:U,current:r})})}function be(r){let c=(0,A.useRef)();return c.current===void 0&&(c.current=r()),c.current}function le(r,c,S){let g=be(()=>(0,Le.default)()),[T,m]=(0,Te.useState)(!0);De(r&&T&&c,({current:C})=>{C&&S()},{callOnMount:!0}),oe(g,"isLoaded",C=>{r&&c&&C&&m(!1)});function U(C){return(0,Te.useMemo)(()=>{if(r){let O=c&&T?"loading":C.status;return{...C,isLoading:O==="loading",status:O}}return C},[r,T,C])}return[U,g.emit]}function xe({debugName:r,fetchFn:c,initialData:S,disableRefetchOnWindowFocus:g,disableRefetchOnMount:T,lowPriorityThrottleMs:m,mediumPriorityThrottleMs:U,dynamicRealtimeThrottleMs:C,errorNormalizer:O}){let f=new we.Store({debugName:r,state:{data:S??null,error:null,status:S?"success":"idle",refetchOnMount:!1}});async function M(E,v){f.setPartialState({status:f.state.status==="success"?"refetching":"loading",error:null,refetchOnMount:!1},{action:f.state.status==="success"?"fetch-start-refetching":"fetch-start-loading"});try{let B=await c();return E.shouldAbort()?!1:(f.setPartialState({data:B,status:"success"},{action:"fetch-success"}),!0)}catch(B){return E.shouldAbort()||f.setPartialState({error:O(B),status:"error"},{action:"fetch-error"}),!1}}let y=ge({fetchFn:M,lowPriorityThrottleMs:m,dynamicRealtimeThrottleMs:C,mediumPriorityThrottleMs:U});function Q(E){return y.scheduleFetch(E,null)}async function J(){return await y.awaitFetch(null)?{data:null,error:O(new Error("Aborted"))}:f.state.data?f.state.error?{data:null,error:f.state.error}:{data:f.state.data,error:null}:{data:null,error:O(new Error("No data"))}}let Y=(0,qe.default)(),W=!1;function j(E="highPriority"){f.setKey("refetchOnMount",E,{action:"invalidate-data"}),W=!1,Y.emit("invalidateData",E)}function z({selector:E,disabled:v,returnRefetchingStatus:B,disableRefetchOnMount:H=T,returnIdleStatus:G=!!v,ensureIsLoaded:Z}={}){let de=(0,Pe.useCallback)(t=>{let{error:F}=t,b=E?E(t.data):t.data,p=t.status;return!G&&p==="idle"&&(p="loading"),!B&&p==="refetching"&&(p="success"),{data:b,error:F,status:p,isLoading:p==="loading"}},[B,G,E]),l=f.useSelector(de,{useExternalDeps:!0});oe(Y,"invalidateData",t=>{W||(Q(t),W=!0)}),(0,Pe.useEffect)(()=>{v||(H?(f.state.refetchOnMount||f.state.status==="idle")&&Q(f.state.refetchOnMount||"lowPriority"):Q("lowPriority"))},[H,v]);let[a,s]=le(Z,!v,()=>{Q("highPriority")});return(0,we.useSubscribeToStore)(f,({observe:t})=>{t.ifSelector(F=>F.status).change.then(({current:F})=>{(F==="success"||F==="error")&&s("isLoaded",!0)})}),a(l)}function ae(E){f.setKey("data",v=>v&&(0,Oe.default)(v,E),{action:"update-state"})}if(!g){let E=function(){j("lowPriority")};var ue=E;window.addEventListener("focus",E),window.addEventListener("visibilitychange",E)}return{store:f,awaitFetch:J,scheduleFetch:Q,invalidateData:j,useDocument:z,updateState:ae,startMutation:y.startMutation}}var ve=me(require("mitt"),1),se=require("react"),ce=require("t-state");function he(r){let c=new Map;function S(g){return c.has(g)||c.set(g,ge(r)),c.get(g)}return{get:S}}var Re=Symbol();function re(r,c){let S=[],g=0;for(let T of r){let m=c(T,Re,g);m!==Re&&S.push(m),g++}return S}function Ce(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function Ee(r){return typeof r=="string"?r:JSON.stringify(r&&Ce(r)?Xe(r):r)}function Xe(r){return re(Object.keys(r).sort(),(c,S)=>r[c]===void 0?S:{[c]:r[c]})}function Se(r){return JSON.parse(JSON.stringify(r))}function Ne({debugName:r,fetchFn:c,disableRefetchOnWindowFocus:S,lowPriorityThrottleMs:g,errorNormalizer:T,mediumPriorityThrottleMs:m,disableRefetchOnMount:U,dynamicRealtimeThrottleMs:C,getCollectionItemKey:O}){let f=new ce.Store({debugName:r,state:{}});function M(l){return Ee(O?O(l):l)}async function y(l,a){let s=M(a),t=Se(a),F=f.state[s];f.produceState(b=>{let p=b[s];if(!p){b[s]={data:null,error:null,status:"loading",payload:t,refetchOnMount:!1,wasLoaded:!1};return}p.status=p.data!==null?"refetching":"loading",p.payload=t,p.error=null,p.refetchOnMount=!1},{equalityCheck:ce.deepEqual,action:{type:F?.data?"fetch-start-refetching":"fetch-start-loading",payload:t}});try{let b=await c(t);return l.shouldAbort()?!1:(f.produceState(p=>{let P=p[s];!P||(P.data=b,P.status="success",P.wasLoaded=!0)},{action:{type:"fetch-success",payload:t}}),!0)}catch(b){if(l.shouldAbort())return!1;let p=T(b);return f.produceState(P=>{let N=P[s];!N||(N.error=p,N.status="error")},{action:{type:"fetch-error",payload:t,error:p}}),!1}}let Q=he({fetchFn:y,lowPriorityThrottleMs:g,dynamicRealtimeThrottleMs:C,mediumPriorityThrottleMs:m});function J(l,a){let s=Array.isArray(a),t=s?a:[a],F=[];for(let b of t){let p=M(b);F.push(Q.get(p).scheduleFetch(l,b))}return s?F:F[0]}async function Y(l){let a=M(l);if(await Q.get(a).awaitFetch(l))return{data:null,error:T(new Error("Aborted"))};let t=f.state[a];return t?.data?t.error?{data:null,error:t.error}:{data:t.data,error:null}:{data:null,error:T(new Error("Not found"))}}function W(l){let a=f.state;return Array.isArray(l)?l.map(M):typeof l=="function"?re(Object.entries(a),([s,t],F)=>t&&l(t.payload,t.data)?s:F):[M(l)]}let j=(0,ve.default)(),z=new Set;function ae(l,a="highPriority"){let s=W(l);for(let t of s)f.produceState(F=>{let b=F[t];!b||(b.refetchOnMount=a)},{action:{type:"invalidate-data",itemKey:t}}),z.delete(t),j.emit("invalidateData",{priority:a,itemKey:t})}function ue(l){if(typeof l=="function"||Array.isArray(l)){let a=W(l);return re(a,(s,t)=>f.state[s]||t)}return f.state[M(l)]}function E(l,{selector:a,omitPayload:s,returnIdleStatus:t,returnRefetchingStatus:F,disableRefetchOnMount:b=U}={}){let p=ye(()=>l.map(q=>({itemKey:M(q),payload:q})),[l]),P=(0,se.useCallback)(q=>a?a(q):q,[]),N=(0,se.useCallback)(q=>p.map(({itemKey:K,payload:$})=>{let ee=q[K];if(ee===null)return{itemStateKey:K,status:"deleted",data:P(null),error:null,payload:s?void 0:$,isLoading:!1};if(!ee)return{itemStateKey:K,status:t?"idle":"loading",data:P(null),error:null,payload:s?void 0:$,isLoading:!t};let fe=ee.status;return!F&&ee.status==="refetching"&&(fe="success"),{itemStateKey:K,status:fe,data:P(ee.data),error:ee.error,isLoading:fe==="loading",payload:s?void 0:ee.payload}}),[P,s,p,t,F]),X=f.useSelector(N,{equalityFn:ce.deepEqual,useExternalDeps:!0});return oe(j,"invalidateData",q=>{for(let{itemKey:K,payload:$}of p)K===q.itemKey&&(z.has(K)||(J(q.priority,$),z.add(K)))}),(0,se.useEffect)(()=>{for(let{itemKey:q,payload:K}of p)if(q)if(b){let $=ue(K);if(!$?.wasLoaded||$.refetchOnMount){J($?.refetchOnMount||"lowPriority",K);return}}else J("lowPriority",K)},[b,p]),X}function v(l,a={}){let{selector:s,ensureIsLoaded:t}=a,F=(0,se.useMemo)(()=>l===!1||l===null||l===void 0?[]:[l],[l]),b=E(F,a),p=(0,se.useMemo)(()=>b[0]??{payload:void 0,data:s?s(null):null,error:null,status:"idle",itemStateKey:"",isLoading:!1},[b]),[P,N]=le(t,!!l,()=>{l&&J("highPriority",l)});return(0,ce.useSubscribeToStore)(f,({observe:X})=>{!t||X.ifSelector(q=>q[p.itemStateKey]?.status).change.then(({current:q})=>{(q==="success"||q==="error")&&N("isLoaded",!0)})}),P(p)}function B(l){let a=W(l),s=[];for(let t of a)s.push(Q.get(t).startMutation());return()=>{for(let t of s)t()}}function H(l,a){let s=M(l);f.produceState(t=>{t[s]={data:a,status:"success",wasLoaded:!0,refetchOnMount:!1,error:null,payload:Se(l)}},{action:{type:"create-item-state",payload:l}})}function G(l){let a=W(l);f.produceState(s=>{for(let t of a)s[t]=null},{action:{type:"delete-item-state",payload:l}})}function Z(l,a,s){let t=W(l),F=!1;return f.batch(()=>{f.produceState(b=>{for(let p of t){let P=b[p];if(!!P&&P.data){F=!0;let N=a(P.data,P);N&&(P.data=N)}}}),s&&!F&&s()},{type:"update-item-state",item:t}),F}if(!S){let l=function(){ae(()=>!0,"lowPriority")};var de=l;window.addEventListener("focus",l),window.addEventListener("visibilitychange",l)}return{store:f,scheduleFetch:J,awaitFetch:Y,useMultipleItems:E,useItem:v,getItemKey:M,getItemState:ue,startMutation:B,invalidateItem:ae,updateItemState:Z,addItemToState:H,deleteItemState:G}}var Ae=me(require("mitt"),1),k=require("react"),ne=require("t-state");var pe="No fetchItemFn was provided";function Ke({debugName:r,fetchListFn:c,fetchItemFn:S,errorNormalizer:g,defaultQuerySize:T=50,disableRefetchOnWindowFocus:m,disableRefetchOnMount:U,lowPriorityThrottleMs:C,mediumPriorityThrottleMs:O,dynamicRealtimeThrottleMs:f,syncMutationsAndInvalidations:M}){let y=new ne.Store({debugName:r,state:{items:{},queries:{},itemQueries:{}}});function Q(e){return Ee(e)}async function J(e,[n,u,i=T]){let o=Se(u),d=Q(o),h=y.state.queries[d],x=!h?.wasLoaded;y.produceState(I=>{let L=I.queries[d];if(!L){I.queries[d]={error:null,status:"loading",wasLoaded:!1,payload:o,refetchOnMount:!1,hasMore:!1,items:[]};return}L.status=L.wasLoaded?n==="loadMore"?"loadingMore":"refetching":"loading",L.error=null,L.refetchOnMount=!1},{equalityCheck:ne.deepEqual,action:{type:x?"fetch-query-start-loading":n==="loadMore"?"fetch-query-loading-more":"refetching-query-start",payload:o}});let V=h?.items.length??0,D=(()=>n==="loadMore"?V+i:x?i:Math.max(V,i))();try{let{items:I,hasMore:L}=await c(o,D);if(e.shouldAbort())return!1;y.produceState(R=>{let w=R.queries[d];if(!!w){w.status="success",w.wasLoaded=!0,w.hasMore=L,w.items=[];for(let{data:te,id:_}of I){R.items[_]=te,w.items.push(String(_));let ie=R.itemQueries[_];(!ie||ie.status!=="loading"&&ie.status!=="refetching")&&(R.itemQueries[_]={error:null,refetchOnMount:!1,status:"success",wasLoaded:!0})}}},{action:{type:"fetch-query-success",payload:o}});for(let{id:R}of I){let w=t?.get(String(R));w&&w.setLastFetchStartTime(e.getStartTime())}return!0}catch(I){if(e.shouldAbort())return!1;let L=g(I);return y.produceState(R=>{let w=R.queries[d];!w||(w.status="error",w.error=L)},{action:{type:"fetch-query-error",payload:o,error:L}}),!1}}function Y(e){return y.state.queries[Q(e)]}function W(e){if(typeof e=="string")return y.state.items[e];let n=b(e);return re(n,(u,i)=>{let o=y.state.items[u];return o?{id:u,data:o}:i})}let j=he({fetchFn:J,lowPriorityThrottleMs:C,dynamicRealtimeThrottleMs:f,mediumPriorityThrottleMs:O});function z(e,n,u){let i=Array.isArray(n),d=(i?n:[n]).map(h=>j.get(Q(h)).scheduleFetch(e,["load",h,u]));return i?d:d[0]}function ae(e,n){let u=Y(e);return!u||!u.hasMore?"skipped":j.get(Q(e)).scheduleFetch("highPriority",["loadMore",e,n])}function ue(e,n){return re(e.items,(u,i)=>{let o=y.state.items[u];return o?n(o,u):i})}async function E(e,n=T){let u=Q(e);if(await j.get(u).awaitFetch(["load",e,n]))return{items:[],error:g(new Error("Aborted")),hasMore:!1};let o=y.state.queries[u];return o?o.error?{items:[],error:o.error,hasMore:o.hasMore}:{items:ue(o,(d,h)=>({data:d,id:h})),error:null,hasMore:o.hasMore}:{items:[],error:g(new Error("Not found")),hasMore:!1}}async function v(e){if(!t)throw new Error(pe);if(await t.get(e).awaitFetch(e))return{data:null,error:g(new Error("Aborted"))};let u=y.state.items[e],i=y.state.itemQueries[e];return!i||!u?{data:null,error:g(new Error("Not found"))}:i.error?{data:null,error:i.error}:{data:u,error:null}}function B(e){return Array.isArray(e)?e.map(n=>({key:Q(n),payload:n})):typeof e=="function"?re(Object.entries(y.state.queries),([n,u],i)=>e(u.payload,u,n)?{key:n,payload:u.payload}:i):[{key:Q(e),payload:e}]}let H=(0,Ae.default)(),G=new Set;function Z(e,n="highPriority",u=!1){let i=B(e);for(let{key:o}of i)y.produceState(d=>{let h=d.queries[o];!h||(h.refetchOnMount=n)},{action:{type:"invalidate-data",key:o}}),G.delete(o),H.emit("invalidateQuery",{priority:n,queryKey:o});M&&!u&&(P((o,d)=>i.some(({payload:h})=>M.syncItemAndQuery(d,h)),n,!0),Z((o,d,h)=>i.some(x=>h!==x.key&&M.syncQueries(x.payload,o)),n,!0))}function de(e,n){return{id:n,data:e}}function l(e,{itemSelector:n=de,omitPayload:u,returnIdleStatus:i,returnRefetchingStatus:o,loadSize:d,disableRefetchOnMount:h=U}={}){let x=ye(()=>e.map(R=>({key:Q(R),payload:R})),[e]),V=(0,k.useCallback)(n,[]),D=(0,k.useCallback)(R=>x.map(({key:w,payload:te})=>{let _=R.queries[w];if(!_)return{queryKey:w,status:i?"idle":"loading",items:[],error:null,hasMore:!1,payload:u?void 0:te,isLoading:!i};let ie=_.status;return!o&&_.status==="refetching"&&(ie="success"),{queryKey:w,status:ie,items:ue(_,V),error:_.error,hasMore:_.hasMore,isLoading:ie==="loading",payload:u?void 0:_.payload}}),[V,u,x,i,o]),I=y.useSelector(D,{equalityFn:ne.deepEqual,useExternalDeps:!0});oe(H,"invalidateQuery",R=>{for(let{key:w,payload:te}of x)w===R.queryKey&&(G.has(w)||(z(R.priority,te),G.add(w)))});let L=be(()=>d);return(0,k.useEffect)(()=>{for(let{key:R,payload:w}of x)if(R)if(h){let te=Y(w);if(!te||!te.wasLoaded||te.refetchOnMount){z(te?.refetchOnMount||"lowPriority",w,L);return}}else z("lowPriority",w,L)},[h,L,x]),I}function a(e,n={}){let{ensureIsLoaded:u}=n,i=(0,k.useMemo)(()=>e===!1||e===null||e===void 0?[]:[e],[e]),o=l(i,n),d=(0,k.useMemo)(()=>o[0]??{payload:void 0,error:null,hasMore:!1,isLoading:!1,status:"idle",queryKey:"",items:[]},[o]),[h,x]=le(u,!!e,()=>{e&&z("highPriority",e)});return(0,ne.useSubscribeToStore)(y,({observe:V})=>{!u||V.ifSelector(D=>D.queries[d.queryKey]?.status).change.then(({current:D})=>{(D==="success"||D==="error")&&x("isLoaded",!0)})}),h(d)}async function s(e,n){if(!t)throw new Error(pe);let u=!y.state.itemQueries[n]?.wasLoaded;y.produceState(i=>{let o=i.itemQueries[n];if(!o){i.itemQueries[n]={status:"loading",error:null,wasLoaded:!1,refetchOnMount:!1};return}o.status=o.wasLoaded?"refetching":"loading",o.error=null,o.refetchOnMount=!1},{action:{type:u?"fetch-item-start":"fetch-item-refetch-start",itemId:n}});try{let i=await S(n);return e.shouldAbort()?!1:(y.produceState(o=>{let d=o.itemQueries[n];!d||(d.status="success",d.wasLoaded=!0,o.items[n]=i)},{action:{type:"fetch-item-success",itemId:n}}),!0)}catch(i){if(e.shouldAbort())return!1;let o=g(i);return y.produceState(d=>{let h=d.itemQueries[n];!h||(h.status="error",h.error=o)},{action:{type:"fetch-item-error",itemId:n}}),!1}}let t=S&&he({fetchFn:s,lowPriorityThrottleMs:C,dynamicRealtimeThrottleMs:f,mediumPriorityThrottleMs:O});function F(e,n){if(!t)throw new Error(pe);let u=Array.isArray(n),o=(u?n:[n]).map(d=>t.get(d).scheduleFetch(e,d));return u?o:o[0]}function b(e){return Array.isArray(e)?e:typeof e=="function"?re(Object.entries(y.state.items),([n,u],i)=>u===null?i:e(u,n)?n:i):[e]}let p=new Set;function P(e,n="highPriority",u=!1){if(!t)throw new Error(pe);let i=b(e);for(let o of i)y.produceState(d=>{let h=d.itemQueries[o];!h||(h.refetchOnMount=n)},{action:{type:"invalidate-item",queryKey:o}}),p.delete(o),H.emit("invalidateItem",{priority:n,itemId:o});M&&!u&&Z(o=>i.some(d=>M.syncItemAndQuery(d,o)),n,!0)}function N(e){if(!t)throw new Error(pe);let n=b(e),u=[];for(let i of n)if(u.push(t.get(i).startMutation()),M)for(let[o,d]of Object.entries(y.state.queries))M.syncItemAndQuery(i,d.payload)&&u.push(j.get(o).startMutation());return()=>{for(let i of u)i()}}function X(e){return e}function q(e,{selector:n=X,returnIdleStatus:u,returnRefetchingStatus:i,disableRefetchOnMount:o}={}){let d=(0,k.useCallback)(n,[]),h=ye(()=>e,[e]),x=(0,k.useCallback)(D=>h.map(I=>{let L=D.itemQueries[I],R=D.items[I];if(L===null)return{status:"deleted",error:null,isLoading:!1,itemId:I,data:d(null,I)};if(!L)return{status:u?"idle":"loading",error:null,isLoading:!u,itemId:I,data:d(null,I)};let w=L.status;return!i&&L.status==="refetching"&&(w="success"),{status:w,error:L.error,isLoading:w==="loading",data:d(R??null,I),itemId:I}}),[d,h,u,i]),V=y.useSelector(x,{equalityFn:ne.deepEqual,useExternalDeps:!0});return oe(H,"invalidateItem",D=>{for(let I of h)I===D.itemId&&(p.has(I)||(F(D.priority,I),p.add(I)))}),(0,k.useEffect)(()=>{for(let D of h)if(D)if(o){let I=y.state.itemQueries[D];if(!I||!I.wasLoaded||I.refetchOnMount){F(I?.refetchOnMount||"lowPriority",D);return}}else F("lowPriority",D)},[o,h]),V}function K(e,n={}){let{ensureIsLoaded:u}=n,i=(0,k.useMemo)(()=>e===!1||e===null||e===void 0?[]:[e],[e]),o=q(i,n),d=(0,k.useCallback)(n.selector??X,[]),h=(0,k.useMemo)(()=>o[0]??{error:null,isLoading:!1,status:"idle",data:d(null,e||""),itemId:e||""},[e,d,o]),[x,V]=le(u,!!e,()=>{e&&F("highPriority",e)});return(0,ne.useSubscribeToStore)(y,({observe:D})=>{!u||!e||D.ifSelector(I=>I.itemQueries[e]?.status).change.then(({current:I})=>{(I==="success"||I==="error")&&V("isLoaded",!0)})}),x(h)}function $(e,n,u){let i=b(e),o=!1;return y.batch(()=>{y.produceState(d=>{for(let h of i){let x=d.items[h];if(!x)continue;o=!0;let V=n(x,h);V&&(d.items[h]=V)}}),u&&!o&&u()},{type:"update-item-state",item:i}),o}function ee(e,n){y.produceState(u=>{u.items[e]=n,u.itemQueries[e]={status:"success",wasLoaded:!0,refetchOnMount:!1,error:null}},{action:{type:"create-item-state",itemId:e}})}function fe(e){let n=b(e);y.produceState(u=>{for(let i of n){u.items[i]=null,u.itemQueries[i]=null;for(let o of Object.values(u.queries))o.items.includes(i)&&(o.items=o.items.filter(d=>d!==i))}},{action:{type:"delete-item-state",itemId:e}})}if(!m){let e=function(){Z(()=>!0,"lowPriority"),P(()=>!0,"lowPriority")};var Xt=e;window.addEventListener("focus",e),window.addEventListener("visibilitychange",e)}return{store:y,scheduleListQueryFetch:z,getQueryState:Y,getQueryKey:Q,deleteItemState:fe,getItemState:W,loadMore:ae,invalidateQuery:Z,invalidateItem:P,scheduleItemFetch:F,awaitItemFetch:v,awaitListQueryFetch:E,useMultipleListQueries:l,useListQuery:a,useItem:K,useMultipleItems:q,addItemToState:ee,updateItemState:$,startItemMutation:N}}0&&(module.exports={newTSDFCollectionStore,newTSDFDocumentStore,newTSDFListQueryStore});
|
package/dist/main.d.ts
ADDED
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
import { Store } from 't-state';
|
|
2
|
+
|
|
3
|
+
type FetchType = 'lowPriority' | 'highPriority' | 'realtimeUpdate';
|
|
4
|
+
type ScheduleFetchResults = 'skipped' | 'started' | 'scheduled' | 'rt-scheduled';
|
|
5
|
+
|
|
6
|
+
type TSDFStatus = 'loading' | 'error' | 'refetching' | 'success';
|
|
7
|
+
type ValidPayload = number | string | Record<string, unknown>;
|
|
8
|
+
type ValidStoreState = Record<string, unknown> | any[];
|
|
9
|
+
|
|
10
|
+
type DocumentStatus = TSDFStatus | 'idle';
|
|
11
|
+
type TSDFDocumentStoreState<State extends ValidStoreState, NError> = {
|
|
12
|
+
data: State | null;
|
|
13
|
+
error: NError | null;
|
|
14
|
+
status: DocumentStatus;
|
|
15
|
+
refetchOnMount: false | FetchType;
|
|
16
|
+
};
|
|
17
|
+
type TSDFUseDocumentReturn<Selected, NError> = {
|
|
18
|
+
status: DocumentStatus;
|
|
19
|
+
data: Selected;
|
|
20
|
+
error: NError | null;
|
|
21
|
+
isLoading: boolean;
|
|
22
|
+
};
|
|
23
|
+
declare function newTSDFDocumentStore<State extends ValidStoreState, NError>({ debugName, fetchFn, initialData, disableRefetchOnWindowFocus, disableRefetchOnMount: globalDisableRefetchOnMount, lowPriorityThrottleMs, mediumPriorityThrottleMs, dynamicRealtimeThrottleMs, errorNormalizer, }: {
|
|
24
|
+
debugName?: string;
|
|
25
|
+
fetchFn: () => Promise<State>;
|
|
26
|
+
initialData?: State;
|
|
27
|
+
errorNormalizer: (exception: unknown) => NError;
|
|
28
|
+
disableRefetchOnWindowFocus?: boolean;
|
|
29
|
+
disableRefetchOnMount?: boolean;
|
|
30
|
+
lowPriorityThrottleMs?: number;
|
|
31
|
+
mediumPriorityThrottleMs?: number;
|
|
32
|
+
dynamicRealtimeThrottleMs?: (lastFetchDuration: number) => number;
|
|
33
|
+
}): {
|
|
34
|
+
store: Store<TSDFDocumentStoreState<State, NError>>;
|
|
35
|
+
awaitFetch: () => Promise<{
|
|
36
|
+
data: State;
|
|
37
|
+
error: null;
|
|
38
|
+
} | {
|
|
39
|
+
data: null;
|
|
40
|
+
error: NError;
|
|
41
|
+
}>;
|
|
42
|
+
scheduleFetch: (fetchType: FetchType) => ScheduleFetchResults;
|
|
43
|
+
invalidateData: (priority?: FetchType) => void;
|
|
44
|
+
useDocument: <Selected = State | null>({ selector, disabled, returnRefetchingStatus, disableRefetchOnMount, returnIdleStatus, ensureIsLoaded, }?: {
|
|
45
|
+
selector?: ((data: State | null) => Selected) | undefined;
|
|
46
|
+
disabled?: boolean | undefined;
|
|
47
|
+
disableRefetchOnMount?: boolean | undefined;
|
|
48
|
+
returnIdleStatus?: boolean | undefined;
|
|
49
|
+
ensureIsLoaded?: boolean | undefined;
|
|
50
|
+
returnRefetchingStatus?: boolean | undefined;
|
|
51
|
+
}) => Readonly<TSDFUseDocumentReturn<Selected, NError>>;
|
|
52
|
+
updateState: (produceNewData: (draftData: State) => State | void | undefined) => void;
|
|
53
|
+
startMutation: () => () => boolean;
|
|
54
|
+
};
|
|
55
|
+
type TSDFDocumentStore<State extends ValidStoreState, NError> = ReturnType<typeof newTSDFDocumentStore<State, NError>>;
|
|
56
|
+
|
|
57
|
+
type CollectionItemStatus = TSDFStatus;
|
|
58
|
+
type TSFDCollectionItem<ItemState extends ValidStoreState, ItemPayload extends ValidPayload, NError> = {
|
|
59
|
+
data: ItemState | null;
|
|
60
|
+
error: NError | null;
|
|
61
|
+
status: CollectionItemStatus;
|
|
62
|
+
payload: ItemPayload;
|
|
63
|
+
refetchOnMount: false | FetchType;
|
|
64
|
+
wasLoaded: boolean;
|
|
65
|
+
};
|
|
66
|
+
type TSFDCollectionState<ItemState extends ValidStoreState, ItemPayload extends ValidPayload, NError> = Record<string, TSFDCollectionItem<ItemState, ItemPayload, NError> | null>;
|
|
67
|
+
type TSFDUseCollectionItemReturn<Selected, ItemPayload, NError> = {
|
|
68
|
+
data: Selected;
|
|
69
|
+
status: CollectionItemStatus | 'idle' | 'deleted';
|
|
70
|
+
payload: ItemPayload | undefined;
|
|
71
|
+
error: NError | null;
|
|
72
|
+
itemStateKey: string;
|
|
73
|
+
isLoading: boolean;
|
|
74
|
+
};
|
|
75
|
+
declare function newTSDFCollectionStore<ItemState extends ValidStoreState, NError, ItemPayload extends ValidPayload>({ debugName, fetchFn, disableRefetchOnWindowFocus, lowPriorityThrottleMs, errorNormalizer, mediumPriorityThrottleMs, disableRefetchOnMount: globalDisableRefetchOnMount, dynamicRealtimeThrottleMs, getCollectionItemKey: filterCollectionItemObjKey, }: {
|
|
76
|
+
debugName?: string;
|
|
77
|
+
fetchFn: (params: ItemPayload) => Promise<ItemState>;
|
|
78
|
+
getCollectionItemKey?: (params: ItemPayload) => ValidPayload | any[];
|
|
79
|
+
errorNormalizer: (exception: unknown) => NError;
|
|
80
|
+
disableRefetchOnWindowFocus?: boolean;
|
|
81
|
+
disableRefetchOnMount?: boolean;
|
|
82
|
+
lowPriorityThrottleMs?: number;
|
|
83
|
+
mediumPriorityThrottleMs?: number;
|
|
84
|
+
dynamicRealtimeThrottleMs?: (lastFetchDuration: number) => number;
|
|
85
|
+
}): {
|
|
86
|
+
store: Store<TSFDCollectionState<ItemState, ItemPayload, NError>>;
|
|
87
|
+
scheduleFetch: {
|
|
88
|
+
(fetchType: FetchType, payload: ItemPayload): ScheduleFetchResults;
|
|
89
|
+
(fetchType: FetchType, payload: ItemPayload[]): ScheduleFetchResults[];
|
|
90
|
+
};
|
|
91
|
+
awaitFetch: (params: ItemPayload) => Promise<{
|
|
92
|
+
data: null;
|
|
93
|
+
error: NError;
|
|
94
|
+
} | {
|
|
95
|
+
data: ItemState;
|
|
96
|
+
error: null;
|
|
97
|
+
}>;
|
|
98
|
+
useMultipleItems: <Selected = ItemState | null>(queries: readonly ItemPayload[], { selector, omitPayload, returnIdleStatus, returnRefetchingStatus, disableRefetchOnMount, }?: {
|
|
99
|
+
selector?: ((data: ItemState | null) => Selected) | undefined;
|
|
100
|
+
omitPayload?: boolean | undefined;
|
|
101
|
+
disableRefetchOnMount?: boolean | undefined;
|
|
102
|
+
returnIdleStatus?: boolean | undefined;
|
|
103
|
+
returnRefetchingStatus?: boolean | undefined;
|
|
104
|
+
}) => readonly TSFDUseCollectionItemReturn<Selected, ItemPayload, NError>[];
|
|
105
|
+
useItem: <Selected_1 = ItemState | null>(payload: ItemPayload | undefined | false | null, options?: {
|
|
106
|
+
selector?: ((data: ItemState | null) => Selected_1) | undefined;
|
|
107
|
+
omitPayload?: boolean | undefined;
|
|
108
|
+
returnRefetchingStatus?: boolean | undefined;
|
|
109
|
+
disableRefetchOnMount?: boolean | undefined;
|
|
110
|
+
ensureIsLoaded?: boolean | undefined;
|
|
111
|
+
}) => TSFDUseCollectionItemReturn<Selected_1, ItemPayload, NError>;
|
|
112
|
+
getItemKey: (params: ItemPayload) => string;
|
|
113
|
+
getItemState: {
|
|
114
|
+
(fetchParam: ItemPayload): TSFDCollectionItem<ItemState, ItemPayload, NError> | null | undefined;
|
|
115
|
+
(fetchParams: ItemPayload[] | ((params: ItemPayload, data: ItemState | null) => boolean)): TSFDCollectionItem<ItemState, ItemPayload, NError>[];
|
|
116
|
+
};
|
|
117
|
+
startMutation: (fetchParams: ItemPayload | ItemPayload[] | ((params: ItemPayload, data: ItemState | null) => boolean)) => () => void;
|
|
118
|
+
invalidateItem: (itemPayload: ItemPayload | ItemPayload[] | ((params: ItemPayload, data: ItemState | null) => boolean), priority?: FetchType) => void;
|
|
119
|
+
updateItemState: (fetchParams: ItemPayload | ItemPayload[] | ((params: ItemPayload, data: ItemState | null) => boolean), produceNewData: (draftData: ItemState, collectionItem: TSFDCollectionItem<ItemState, ItemPayload, NError>) => void | ItemState, ifNothingWasUpdated?: () => void) => boolean;
|
|
120
|
+
addItemToState: (fetchParams: ItemPayload, data: ItemState) => void;
|
|
121
|
+
deleteItemState: (fetchParams: ItemPayload | ItemPayload[] | ((params: ItemPayload, data: ItemState | null) => boolean)) => void;
|
|
122
|
+
};
|
|
123
|
+
type TSDFCollectionStore<ItemState extends ValidStoreState, NError, FetchParams extends ValidPayload> = ReturnType<typeof newTSDFCollectionStore<ItemState, NError, FetchParams>>;
|
|
124
|
+
|
|
125
|
+
type QueryStatus = TSDFStatus | 'loadingMore';
|
|
126
|
+
type TSFDListQuery<NError, QueryPayload extends ValidPayload> = {
|
|
127
|
+
error: NError | null;
|
|
128
|
+
status: QueryStatus;
|
|
129
|
+
payload: QueryPayload;
|
|
130
|
+
hasMore: boolean;
|
|
131
|
+
wasLoaded: boolean;
|
|
132
|
+
refetchOnMount: false | FetchType;
|
|
133
|
+
items: string[];
|
|
134
|
+
};
|
|
135
|
+
type TSDFItemQuery<NError> = {
|
|
136
|
+
error: NError | null;
|
|
137
|
+
status: Exclude<QueryStatus, 'loadingMore'>;
|
|
138
|
+
wasLoaded: boolean;
|
|
139
|
+
refetchOnMount: false | FetchType;
|
|
140
|
+
};
|
|
141
|
+
type TSFDListQueryState<ItemState extends ValidStoreState, NError, QueryPayload extends ValidPayload> = {
|
|
142
|
+
items: Record<string, ItemState | null>;
|
|
143
|
+
queries: Record<string, TSFDListQuery<NError, QueryPayload>>;
|
|
144
|
+
itemQueries: Record<string, TSDFItemQuery<NError> | null>;
|
|
145
|
+
};
|
|
146
|
+
type TSFDUseListQueryReturn<Selected, ItemPayload, NError> = {
|
|
147
|
+
items: Selected[];
|
|
148
|
+
status: QueryStatus | 'idle';
|
|
149
|
+
payload: ItemPayload | undefined;
|
|
150
|
+
error: NError | null;
|
|
151
|
+
queryKey: string;
|
|
152
|
+
hasMore: boolean;
|
|
153
|
+
isLoading: boolean;
|
|
154
|
+
};
|
|
155
|
+
type TSFDUseItemReturn<Selected, NError> = {
|
|
156
|
+
data: Selected;
|
|
157
|
+
status: QueryStatus | 'idle' | 'deleted';
|
|
158
|
+
itemId: string;
|
|
159
|
+
error: NError | null;
|
|
160
|
+
isLoading: boolean;
|
|
161
|
+
};
|
|
162
|
+
type FetchListFnReturn<ItemState extends ValidStoreState> = {
|
|
163
|
+
items: {
|
|
164
|
+
id: string | number;
|
|
165
|
+
data: ItemState;
|
|
166
|
+
}[];
|
|
167
|
+
hasMore: boolean;
|
|
168
|
+
};
|
|
169
|
+
declare function newTSDFListQueryStore<ItemState extends ValidStoreState, NError, QueryPayload extends ValidPayload>({ debugName, fetchListFn, fetchItemFn, errorNormalizer, defaultQuerySize, disableRefetchOnWindowFocus, disableRefetchOnMount: globalDisableRefetchOnMount, lowPriorityThrottleMs, mediumPriorityThrottleMs, dynamicRealtimeThrottleMs, syncMutationsAndInvalidations, }: {
|
|
170
|
+
debugName?: string;
|
|
171
|
+
fetchListFn: (payload: QueryPayload, size: number) => Promise<FetchListFnReturn<ItemState>>;
|
|
172
|
+
fetchItemFn?: (itemId: string) => Promise<ItemState>;
|
|
173
|
+
errorNormalizer: (exception: unknown) => NError;
|
|
174
|
+
defaultQuerySize?: number;
|
|
175
|
+
disableRefetchOnWindowFocus?: boolean;
|
|
176
|
+
syncMutationsAndInvalidations?: {
|
|
177
|
+
syncQueries: (query1: QueryPayload, query2: QueryPayload) => boolean;
|
|
178
|
+
syncItemAndQuery: (itemId: string, query: QueryPayload) => boolean;
|
|
179
|
+
};
|
|
180
|
+
disableRefetchOnMount?: boolean;
|
|
181
|
+
lowPriorityThrottleMs?: number;
|
|
182
|
+
mediumPriorityThrottleMs?: number;
|
|
183
|
+
dynamicRealtimeThrottleMs?: (lastFetchDuration: number) => number;
|
|
184
|
+
}): {
|
|
185
|
+
store: Store<TSFDListQueryState<ItemState, NError, QueryPayload>>;
|
|
186
|
+
scheduleListQueryFetch: {
|
|
187
|
+
(fetchType: FetchType, payload: QueryPayload, size?: number): ScheduleFetchResults;
|
|
188
|
+
(fetchType: FetchType, payload: QueryPayload[], size?: number): ScheduleFetchResults[];
|
|
189
|
+
};
|
|
190
|
+
getQueryState: (params: QueryPayload) => TSFDListQuery<NError, QueryPayload> | undefined;
|
|
191
|
+
getQueryKey: (params: QueryPayload) => string;
|
|
192
|
+
deleteItemState: (itemId: string | string[] | ((item: ItemState, itemId: string) => boolean)) => void;
|
|
193
|
+
getItemState: {
|
|
194
|
+
(id: string[] | ((item: ItemState, itemId: string) => boolean)): {
|
|
195
|
+
id: string;
|
|
196
|
+
data: ItemState;
|
|
197
|
+
}[];
|
|
198
|
+
(id: string): ItemState | null | undefined;
|
|
199
|
+
};
|
|
200
|
+
loadMore: (params: QueryPayload, size: number) => ScheduleFetchResults;
|
|
201
|
+
invalidateQuery: (queryPayload: QueryPayload | QueryPayload[] | ((params: QueryPayload, data: TSFDListQuery<NError, QueryPayload>, queryKey: string) => boolean), priority?: FetchType, ignoreInvalidationSync?: boolean) => void;
|
|
202
|
+
invalidateItem: (itemId: string | string[] | ((item: ItemState, itemId: string) => boolean), priority?: FetchType, ignoreInvalidationSync?: boolean) => void;
|
|
203
|
+
scheduleItemFetch: {
|
|
204
|
+
(fetchType: FetchType, itemId: string): ScheduleFetchResults;
|
|
205
|
+
(fetchType: FetchType, itemId: string[]): ScheduleFetchResults[];
|
|
206
|
+
};
|
|
207
|
+
awaitItemFetch: (itemId: string) => Promise<{
|
|
208
|
+
data: null;
|
|
209
|
+
error: NError;
|
|
210
|
+
} | {
|
|
211
|
+
data: ItemState;
|
|
212
|
+
error: null;
|
|
213
|
+
}>;
|
|
214
|
+
awaitListQueryFetch: (params: QueryPayload, size?: number) => Promise<{
|
|
215
|
+
items: [
|
|
216
|
+
];
|
|
217
|
+
error: NError;
|
|
218
|
+
hasMore: boolean;
|
|
219
|
+
} | {
|
|
220
|
+
items: {
|
|
221
|
+
data: ItemState;
|
|
222
|
+
id: string;
|
|
223
|
+
}[];
|
|
224
|
+
error: null;
|
|
225
|
+
hasMore: boolean;
|
|
226
|
+
}>;
|
|
227
|
+
useMultipleListQueries: <SelectedItem = {
|
|
228
|
+
id: string;
|
|
229
|
+
data: ItemState;
|
|
230
|
+
}>(queries: readonly QueryPayload[], { itemSelector, omitPayload, returnIdleStatus, returnRefetchingStatus, loadSize, disableRefetchOnMount, }?: {
|
|
231
|
+
itemSelector?: ((data: ItemState, id: string) => SelectedItem) | undefined;
|
|
232
|
+
omitPayload?: boolean | undefined;
|
|
233
|
+
disableRefetchOnMount?: boolean | undefined;
|
|
234
|
+
returnIdleStatus?: boolean | undefined;
|
|
235
|
+
returnRefetchingStatus?: boolean | undefined;
|
|
236
|
+
loadSize?: number | undefined;
|
|
237
|
+
}) => readonly TSFDUseListQueryReturn<SelectedItem, QueryPayload, NError>[];
|
|
238
|
+
useListQuery: <SelectedItem_1 = {
|
|
239
|
+
id: string;
|
|
240
|
+
data: ItemState;
|
|
241
|
+
}>(payload: QueryPayload | false | null | undefined, options?: {
|
|
242
|
+
itemSelector?: ((data: ItemState, id: string) => SelectedItem_1) | undefined;
|
|
243
|
+
omitPayload?: boolean | undefined;
|
|
244
|
+
disableRefetchOnMount?: boolean | undefined;
|
|
245
|
+
returnIdleStatus?: boolean | undefined;
|
|
246
|
+
returnRefetchingStatus?: boolean | undefined;
|
|
247
|
+
ensureIsLoaded?: boolean | undefined;
|
|
248
|
+
loadSize?: number | undefined;
|
|
249
|
+
}) => TSFDUseListQueryReturn<SelectedItem_1, QueryPayload, NError>;
|
|
250
|
+
useItem: <SelectedItem_2 = ItemState>(itemId: string | false | null | undefined, options?: {
|
|
251
|
+
selector?: ((data: ItemState | null, id: string) => SelectedItem_2) | undefined;
|
|
252
|
+
disableRefetchOnMount?: boolean | undefined;
|
|
253
|
+
returnIdleStatus?: boolean | undefined;
|
|
254
|
+
returnRefetchingStatus?: boolean | undefined;
|
|
255
|
+
ensureIsLoaded?: boolean | undefined;
|
|
256
|
+
}) => TSFDUseItemReturn<SelectedItem_2, NError>;
|
|
257
|
+
useMultipleItems: <SelectedItem_3 = ItemState>(itemIds: string[], { selector, returnIdleStatus, returnRefetchingStatus, disableRefetchOnMount, }?: {
|
|
258
|
+
selector?: ((data: ItemState | null, id: string) => SelectedItem_3) | undefined;
|
|
259
|
+
disableRefetchOnMount?: boolean | undefined;
|
|
260
|
+
returnIdleStatus?: boolean | undefined;
|
|
261
|
+
returnRefetchingStatus?: boolean | undefined;
|
|
262
|
+
}) => readonly TSFDUseItemReturn<SelectedItem_3, NError>[];
|
|
263
|
+
addItemToState: (itemId: string, data: ItemState) => void;
|
|
264
|
+
updateItemState: (itemIds: string | string[] | ((item: ItemState, itemId: string) => boolean), produceNewData: (draftData: ItemState, itemId: string) => void | ItemState, ifNothingWasUpdated?: () => void) => boolean;
|
|
265
|
+
startItemMutation: (itemId: string | string[] | ((item: ItemState, itemId: string) => boolean)) => () => void;
|
|
266
|
+
};
|
|
267
|
+
type TSFDListQueryStore<ItemState extends ValidStoreState, NError, QueryPayload extends ValidPayload> = ReturnType<typeof newTSDFListQueryStore<ItemState, NError, QueryPayload>>;
|
|
268
|
+
|
|
269
|
+
export { TSDFCollectionStore, TSDFDocumentStore, TSDFDocumentStoreState, TSDFItemQuery, TSDFStatus, TSDFUseDocumentReturn, TSFDCollectionItem, TSFDCollectionState, TSFDListQuery, TSFDListQueryState, TSFDListQueryStore, TSFDUseCollectionItemReturn, TSFDUseItemReturn, TSFDUseListQueryReturn, ValidPayload, ValidStoreState, newTSDFCollectionStore, newTSDFDocumentStore, newTSDFListQueryStore };
|
package/dist/main.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
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};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tsdf",
|
|
3
|
-
"version": "8.0.0-beta.
|
|
3
|
+
"version": "8.0.0-beta.3",
|
|
4
4
|
"description": "A data fetching solution based on t-state",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Lucas Santos",
|
|
@@ -15,6 +15,9 @@
|
|
|
15
15
|
"require": "./dist/main.cjs"
|
|
16
16
|
}
|
|
17
17
|
},
|
|
18
|
+
"files": [
|
|
19
|
+
"dist"
|
|
20
|
+
],
|
|
18
21
|
"sideEffects": false,
|
|
19
22
|
"engines": {
|
|
20
23
|
"node": ">=16.0.0"
|
package/.eslintignore
DELETED
package/.eslintrc.cjs
DELETED
|
@@ -1,119 +0,0 @@
|
|
|
1
|
-
const isCI = process.env.CI === 'true';
|
|
2
|
-
|
|
3
|
-
const OFF = 0;
|
|
4
|
-
const WARN = 1;
|
|
5
|
-
const ERROR = 2;
|
|
6
|
-
const ERROR_IN_CI = isCI ? ERROR : WARN;
|
|
7
|
-
const ERROR_IN_CI_ONLY = isCI ? ERROR : 0;
|
|
8
|
-
|
|
9
|
-
module.exports = {
|
|
10
|
-
parser: '@typescript-eslint/parser',
|
|
11
|
-
parserOptions: {
|
|
12
|
-
project: './tsconfig.json',
|
|
13
|
-
createDefaultProgram: true,
|
|
14
|
-
ecmaVersion: 8,
|
|
15
|
-
ecmaFeatures: {
|
|
16
|
-
jsx: true,
|
|
17
|
-
},
|
|
18
|
-
useJSXTextNode: true,
|
|
19
|
-
sourceType: 'module',
|
|
20
|
-
},
|
|
21
|
-
env: {
|
|
22
|
-
browser: true,
|
|
23
|
-
},
|
|
24
|
-
plugins: ['@typescript-eslint', '@lucasols/extended-lint', 'vitest'],
|
|
25
|
-
|
|
26
|
-
rules: {
|
|
27
|
-
'no-warning-comments': [ERROR_IN_CI, { terms: ['FIX:'] }],
|
|
28
|
-
'@lucasols/extended-lint/no-warning-comments': [
|
|
29
|
-
ERROR_IN_CI_ONLY,
|
|
30
|
-
{ terms: ['FIX-LATER:', 'FIXLATER:'] },
|
|
31
|
-
],
|
|
32
|
-
'no-constant-binary-expression': ERROR_IN_CI,
|
|
33
|
-
'object-shorthand': ERROR_IN_CI,
|
|
34
|
-
'no-useless-rename': ERROR_IN_CI,
|
|
35
|
-
'no-param-reassign': ERROR_IN_CI,
|
|
36
|
-
'prefer-template': ERROR_IN_CI,
|
|
37
|
-
'prefer-const': [ERROR_IN_CI, { destructuring: 'all' }],
|
|
38
|
-
|
|
39
|
-
'no-prototype-builtins': OFF,
|
|
40
|
-
'no-inner-declarations': OFF,
|
|
41
|
-
'no-undef': OFF,
|
|
42
|
-
'no-console': [ERROR_IN_CI, { allow: ['warn', 'error', 'info'] }],
|
|
43
|
-
'no-restricted-imports': [
|
|
44
|
-
ERROR_IN_CI,
|
|
45
|
-
{
|
|
46
|
-
patterns: [
|
|
47
|
-
{
|
|
48
|
-
group: ['*.test'],
|
|
49
|
-
message: 'Do not import test files',
|
|
50
|
-
},
|
|
51
|
-
],
|
|
52
|
-
},
|
|
53
|
-
],
|
|
54
|
-
'no-restricted-syntax': [
|
|
55
|
-
ERROR_IN_CI_ONLY,
|
|
56
|
-
{
|
|
57
|
-
selector:
|
|
58
|
-
'CallExpression[callee.property.name="only"]',
|
|
59
|
-
message: 'No test.only',
|
|
60
|
-
},
|
|
61
|
-
{
|
|
62
|
-
selector:
|
|
63
|
-
'CallExpression[callee.property.name="todo"]',
|
|
64
|
-
message: 'No test.todo',
|
|
65
|
-
},
|
|
66
|
-
],
|
|
67
|
-
'no-implicit-coercion': [
|
|
68
|
-
ERROR_IN_CI,
|
|
69
|
-
{ disallowTemplateShorthand: true, allow: ['!!'] },
|
|
70
|
-
],
|
|
71
|
-
|
|
72
|
-
/* typescript */
|
|
73
|
-
'@typescript-eslint/no-unnecessary-condition': ERROR_IN_CI,
|
|
74
|
-
'@typescript-eslint/naming-convention': [
|
|
75
|
-
'error',
|
|
76
|
-
{
|
|
77
|
-
selector: 'typeLike',
|
|
78
|
-
format: ['PascalCase'],
|
|
79
|
-
},
|
|
80
|
-
],
|
|
81
|
-
'@typescript-eslint/no-throw-literal': ERROR_IN_CI,
|
|
82
|
-
'@typescript-eslint/no-unused-expressions': ERROR_IN_CI,
|
|
83
|
-
'@typescript-eslint/no-unused-vars': [
|
|
84
|
-
ERROR_IN_CI,
|
|
85
|
-
{ argsIgnorePattern: '^_', ignoreRestSiblings: true },
|
|
86
|
-
],
|
|
87
|
-
'@typescript-eslint/no-shadow': [
|
|
88
|
-
ERROR_IN_CI,
|
|
89
|
-
{ ignoreOnInitialization: true, allow: ['expect'] },
|
|
90
|
-
],
|
|
91
|
-
'@typescript-eslint/ban-types': [
|
|
92
|
-
ERROR_IN_CI,
|
|
93
|
-
{
|
|
94
|
-
types: {
|
|
95
|
-
Error: 'Dont use error type',
|
|
96
|
-
},
|
|
97
|
-
},
|
|
98
|
-
],
|
|
99
|
-
|
|
100
|
-
'@typescript-eslint/no-non-null-assertion': OFF,
|
|
101
|
-
'@typescript-eslint/no-empty-function': OFF,
|
|
102
|
-
'@typescript-eslint/no-explicit-any': OFF,
|
|
103
|
-
'@typescript-eslint/no-floating-promises': OFF,
|
|
104
|
-
'@typescript-eslint/no-unsafe-assignment': OFF,
|
|
105
|
-
'@typescript-eslint/no-misused-promises': OFF,
|
|
106
|
-
'@typescript-eslint/restrict-template-expressions': OFF,
|
|
107
|
-
'@typescript-eslint/unbound-method': OFF,
|
|
108
|
-
|
|
109
|
-
/* vitest */
|
|
110
|
-
'vitest/expect-expect': ERROR_IN_CI_ONLY,
|
|
111
|
-
'vitest/no-identical-title': ERROR_IN_CI,
|
|
112
|
-
},
|
|
113
|
-
extends: [
|
|
114
|
-
'eslint:recommended',
|
|
115
|
-
'plugin:@typescript-eslint/recommended',
|
|
116
|
-
'plugin:@typescript-eslint/recommended-requiring-type-checking',
|
|
117
|
-
'plugin:react-hooks/recommended',
|
|
118
|
-
],
|
|
119
|
-
};
|
package/.gitattributes
DELETED
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
# Auto detect text files and perform LF normalization
|
|
2
|
-
* text eol=lf
|
|
3
|
-
|
|
4
|
-
# Custom for Visual Studio
|
|
5
|
-
*.cs diff=csharp
|
|
6
|
-
|
|
7
|
-
# Standard to msysgit
|
|
8
|
-
*.doc diff=astextplain
|
|
9
|
-
*.DOC diff=astextplain
|
|
10
|
-
*.docx diff=astextplain
|
|
11
|
-
*.DOCX diff=astextplain
|
|
12
|
-
*.dot diff=astextplain
|
|
13
|
-
*.DOT diff=astextplain
|
|
14
|
-
*.pdf diff=astextplain
|
|
15
|
-
*.PDF diff=astextplain
|
|
16
|
-
*.rtf diff=astextplain
|
|
17
|
-
*.RTF diff=astextplain
|
|
18
|
-
|
|
19
|
-
# Denote all files that are truly binary and should not be modified.
|
|
20
|
-
*.png binary
|
|
21
|
-
*.jpg binary
|
|
22
|
-
*.ico binary
|
package/.prettierrc
DELETED
package/.vscode/settings.json
DELETED
package/.vscode/tasks.json
DELETED
|
@@ -1,35 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
// See https://go.microsoft.com/fwlink/?LinkId=733558
|
|
3
|
-
// for the documentation about the tasks.json format
|
|
4
|
-
"version": "2.0.0",
|
|
5
|
-
"tasks": [
|
|
6
|
-
{
|
|
7
|
-
"type": "npm",
|
|
8
|
-
"script": "npm-publish",
|
|
9
|
-
"label": "publish package",
|
|
10
|
-
"problemMatcher": [],
|
|
11
|
-
"presentation": {
|
|
12
|
-
"clear": true
|
|
13
|
-
}
|
|
14
|
-
},
|
|
15
|
-
{
|
|
16
|
-
"type": "npm",
|
|
17
|
-
"script": "test",
|
|
18
|
-
"label": "run tests",
|
|
19
|
-
"problemMatcher": [],
|
|
20
|
-
"presentation": {
|
|
21
|
-
"clear": true
|
|
22
|
-
}
|
|
23
|
-
},
|
|
24
|
-
{
|
|
25
|
-
"type": "npm",
|
|
26
|
-
"script": "eslint",
|
|
27
|
-
"problemMatcher": ["$eslint-stylish"],
|
|
28
|
-
"label": "eslint",
|
|
29
|
-
"detail": "CI=true eslint --ext .jsx,.js,.ts,.tsx src/ test/",
|
|
30
|
-
"presentation": {
|
|
31
|
-
"clear": true
|
|
32
|
-
}
|
|
33
|
-
}
|
|
34
|
-
]
|
|
35
|
-
}
|