@symbo.ls/fetch 3.14.658 → 3.14.659
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/cjs/index.js +1 -1
- package/dist/esm/index.js +1 -1
- package/index.js +31 -4
- package/package.json +1 -1
package/dist/cjs/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var Nt=Object.create;var rt=Object.defineProperty;var It=Object.getOwnPropertyDescriptor;var Ot=Object.getOwnPropertyNames;var qt=Object.getPrototypeOf,Ut=Object.prototype.hasOwnProperty;var zt=(e,t)=>{for(var s in t)rt(e,s,{get:t[s],enumerable:!0})},mt=(e,t,s,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Ot(t))!Ut.call(e,o)&&o!==s&&rt(e,o,{get:()=>t[o],enumerable:!(r=It(t,o))||r.enumerable});return e};var Tt=(e,t,s)=>(s=e!=null?Nt(qt(e)):{},mt(t||!e||!e.__esModule?rt(s,"default",{value:e,enumerable:!0}):s,e)),jt=e=>mt(rt({},"__esModule",{value:!0}),e);var oe={};zt(oe,{createAdapter:()=>Yt,default:()=>ae,executeFetch:()=>wt,fetchPlugin:()=>re,initAdapterAuth:()=>ct,parseDuration:()=>W,queryClient:()=>se,registerAdapter:()=>Kt,resolveDb:()=>kt});module.exports=jt(oe);var f=require("@symbo.ls/utils");const Gt=["select","rpc","insert","update","upsert","delete","subscribe"],Qt={rest:()=>import("./adapters/rest.js"),local:()=>import("./adapters/local.js")},at=Symbol.for("@symbo.ls/fetch:CUSTOM_ADAPTERS"),Y=(()=>{if(typeof globalThis<"u"&&globalThis[at])return globalThis[at];const e={};if(typeof globalThis<"u")try{return Object.defineProperty(globalThis,at,{value:e,writable:!1,configurable:!1,enumerable:!1}),globalThis[at]}catch{}return e})(),ot=Symbol.for("@symbo.ls/fetch:PENDING_ADAPTERS"),pt=(()=>{if(typeof globalThis<"u"&&globalThis[ot])return globalThis[ot];const e={};if(typeof globalThis<"u")try{return Object.defineProperty(globalThis,ot,{value:e,writable:!1,configurable:!1,enumerable:!1}),globalThis[ot]}catch{}return e})(),xt=5e3,Wt=e=>new Promise(t=>{if(Y[e])return t(Y[e]);const s=pt[e]||=[];let r=!1;const o=()=>{r||(r=!0,t(Y[e]||null))};s.push(o),setTimeout(o,xt)}),Kt=(e,t)=>{Y[e]=t;const s=pt[e];if(s&&s.length){pt[e]=[];for(const r of s)r()}},Yt=e=>{const t={};for(const s of Gt)e[s]&&(t[s]=e[s]);return t.name=e.name||"custom",t},kt=async e=>{if(!e)return null;if(typeof e.select=="function")return e;const{adapter:t,...s}=e,r=typeof t=="string"?t:typeof e=="string"?e:null;if(!r)return null;let o=Y[r]||Qt[r];if(!o&&(o=await Wt(r),!o))throw new Error(`Unknown db adapter: "${r}". Use registerAdapter() for adapters with optional deps.`);const a=await o();if(!a||typeof a.setup!="function")throw new Error(`Adapter "${r}" loader returned a module without a setup() function. Got keys: [${Object.keys(a||{}).join(", ")}]. Likely a bundler chunk-resolution issue.`);return a.setup(s)},W=e=>{if(!e)return 0;if(typeof e=="number")return e;const t=e.match(/^(\d+)(ms|s|m|h)$/);if(!t)return 0;const s=parseInt(t[1]),r=t[2];return r==="ms"?s:r==="s"?s*1e3:r==="m"?s*6e4:r==="h"?s*36e5:0},b=new Map,U=new Map,B=new Map,Bt=(e,t,s)=>{if(e.cache?.key)return e.cache.key;const r=Vt(e.params),o=s?`${s}:`:"",a=`${e.from}:${e.method}:${o}${JSON.stringify(r||"")}`;return t?`${a}:${t}`:a},J=e=>b.get(e)||null,H=(e,t,s)=>{const r=b.get(e),o={data:t,error:s,time:Date.now(),stale:!1};b.set(e,o);const a=U.get(e);if(a)for(const i of a)(0,f.isFunction)(i)&&i(o);return o},V=e=>{if(e){const t=b.get(e);t&&(t.stale=!0);return}for(const[,t]of b)t.stale=!0},it=e=>{if(e){b.delete(e);return}b.clear()},ce=(e,t)=>(U.has(e)||U.set(e,new Set),U.get(e).add(t),()=>{const s=U.get(e);s&&(s.delete(t),s.size===0&&U.delete(e))}),_t=e=>!e&&e!==!1?{staleTime:6e4,gcTime:3e5}:e===!1?null:e===!0?{staleTime:6e4,gcTime:3e5}:typeof e=="number"?{staleTime:e,gcTime:Math.max(e*5,3e5)}:(0,f.isString)(e)?{staleTime:W(e),gcTime:3e5}:{staleTime:W(e.stale||e.staleTime)||6e4,gcTime:W(e.gc||e.gcTime||e.expire)||3e5,key:e.key};let nt=null;const Jt=()=>{nt||(nt=setInterval(()=>{const e=Date.now();for(const[t,s]of b){const r=U.get(t);!(r&&r.size>0)&&e-s.time>(s.gcTime||3e5)&&b.delete(t)}},3e4),nt.unref&&nt.unref())};Jt();const Ft=3,yt=e=>Math.min(1e3*2**e,3e4),Et=e=>{const t=e.retry;return t===!1?{count:0}:t===!0||t===void 0?{count:Ft,delay:yt}:typeof t=="number"?{count:t,delay:yt}:{count:t.count??Ft,delay:(0,f.isFunction)(t.delay)?t.delay:typeof t.delay=="number"?()=>t.delay:yt}},Dt=async(e,t)=>{const{count:s,delay:r}=t;let o;for(let a=0;a<=s;a++)try{const i=await e();if(i?.error){if(o=i.error,a<s){const c=(0,f.isFunction)(r)?r(a,o):r;await new Promise(n=>setTimeout(n,c));continue}return i}return i}catch(i){if(o=i,a<s){const c=(0,f.isFunction)(r)?r(a,i):r;await new Promise(n=>setTimeout(n,c));continue}throw i}return{data:null,error:o}},x={focus:new Set,online:new Set};let Ct=!1;const Ht=()=>{if(Ct||typeof window>"u")return;Ct=!0;const e=()=>{for(const s of x.focus)s()},t=()=>{for(const s of x.online)s()};window.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&e()}),window.addEventListener("focus",e),window.addEventListener("online",t)},Pt=(e,t)=>{const s=t.__ref;if(e===!0)return{from:s.__state||t.key,method:"select",query:!0,on:"create"};if((0,f.isString)(e))return{from:e,method:"select",query:!0,on:"create"};if((0,f.isObject)(e)){const r={...e};return r.from=r.from||s.__state||t.key,r.method=r.method||"select",r.on=r.on||"create",r.query===void 0&&(r.query=!0),r}return null},Vt=e=>(!e||(0,f.isFunction)(e),e),ft=(e,t)=>{const s=e?.state?.root||t?.state?.root;if(s?.lang)return s.lang},At=(e,t)=>{const r=(e?.state?.root||t?.state?.root)?.__fetchScope;return r?String(r):void 0},Lt=(e,t,s)=>{let r;if(!e)r=void 0;else if((0,f.isFunction)(e))r=e(t,t.state);else{r={};for(const o in e){const a=e[o];r[o]=(0,f.isFunction)(a)?a(t,t.state):a}}return r},ct=async(e,t)=>{if(!e||e.__authInitialized||(e.__authInitialized=!0,!e.getSession))return;const s=(r,o)=>{const a=t.state?.root;a?.update&&a.update({auth:{user:r,session:o,loading:!1}})};try{const r=await e.getSession();s(r?.user||null,r)}catch(r){console.warn("[fetch] Failed to restore auth session:",r.message)}e.onAuthStateChange&&e.onAuthStateChange((r,o)=>{s(o?.user||null,o)})},gt=async(e,t)=>{if((0,f.isFunction)(e.select))return e.auth!==!1&&await ct(e,t),e;if(e.__resolved)return e.auth!==!1&&await ct(e.__resolved,t),e.__resolved;if(e.__resolving)return e.__resolving;e.__resolving=kt(e);const s=await e.__resolving;return delete e.__resolving,s?(s.auth=e.auth,s.url=e.url,s.key=e.key,e.__resolved=s,t.fetch=s,e.auth!==!1&&await ct(s,t),s):null},T=(e,t,...s)=>{const r=(0,f.isFunction)(e[t])?e[t]:null;r&&r.call(e,...s,e,e.state,e.context)},C=(e,t,s,...r)=>{const o=e&&(0,f.isFunction)(e[s])?e[s]:null;o&&o.call(t,...r,t,t.state,t.context)},X=e=>{const t={},s=e.node;if(!s)return t;if(s.tagName==="FORM"){const o=new FormData(s);for(const[a,i]of o.entries())t[a]=i;return t}const r=s.querySelectorAll("input, textarea, select");for(let o=0;o<r.length;o++){const a=r[o],i=a.name||a.getAttribute("name");i&&(a.type==="checkbox"?t[i]=a.checked:a.type==="file"?t[i]=a.files:t[i]=a.value)}return t},z=(e,t,s,r={})=>{const o=s&&s.startsWith("~/"),a=o&&e.state?.root||e.state;if(a?.update)if(o){const i=s.slice(2);t&&typeof t=="object"&&!Array.isArray(t)&&i in t?a.update(t,{preventFetch:!0,...r}):a.update({[i]:t},{preventFetch:!0,...r})}else{const i=s?{[s]:t}:t;a.update(i,{preventFetch:!0,...r})}},k=(e,t)=>{const s=e?.__ref;s&&(s.__fetchStatus=t,s.__fetching=t.isFetching,s.__fetchError=t.error)},I=async(e,t,s,r={})=>{const o=s?.fetch;if(!o||!t||!t.__ref||e.enabled===!1||(0,f.isFunction)(e.enabled)&&!e.enabled(t,t.state)||e.skip===!0||(0,f.isFunction)(e.skip)&&e.skip(t,t.state))return;const a=await gt(o,s);if(!a||!t.__ref)return;const i=t.__ref,{from:c,method:n,query:_,params:v,cache:Z,transform:F,single:ut,auth:tt,fields:R,as:O,limit:K,offset:et,order:j,headers:N,baseUrl:y,page:g,cursor:m,getNextPageParam:G,getPreviousPageParam:S,infinite:P,placeholderData:q,initialData:Q,select:A,keepPreviousData:$}=e;let E=(0,f.isString)(A)?A:void 0;if(_&&(0,f.isFunction)(t.getQuery)){const d=t.getQuery(a.name||"paths");d&&(E=d.select||d.length&&d.join(",")||E)}const L=Lt(v,t,s),D=_t(Z),st=Et(e),lt=ft(t,s),bt=At(t,s),$t=lt?`:${lt}`:"",Mt=bt?`${bt}:`:"",p=D?Z?.key||`${c}:${n}:${Mt}${JSON.stringify(L||"")}${P?":infinite":""}${g?":p"+JSON.stringify(g):""}${$t}`:null;if(!i.__fetchInitialized&&p&&(i.__fetchInitialized=!0,Q!==void 0)){const d=(0,f.isFunction)(Q)?Q():Q;H(p,d,null)}if((n==="select"||n==="rpc")&&p&&D){const d=J(p);if(d&&!d.error){const l=Date.now()-d.time,h=d.stale||l>(D.staleTime||0);let u=d.data;if((0,f.isFunction)(A)&&(u=A(u,t,t.state)),F&&(u=F(u,t,t.state)),z(t,u,O),!h){k(t,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!0,error:null,status:"success",fetchStatus:"idle"});return}}else if(q!==void 0){const l=(0,f.isFunction)(q)?q(t,t.state):q;l!==void 0&&z(t,l,O)}}if(p&&B.has(p)&&!r.force){const d=B.get(p);try{const l=await Promise.race([d,new Promise((h,u)=>setTimeout(()=>u("DEDUP_TIMEOUT"),15e3))]);if(l?.data!==void 0){let h=l.data;(0,f.isFunction)(A)&&(h=A(h,t,t.state)),F&&(h=F(h,t,t.state)),z(t,h,O),T(t,"onFetchComplete",h),C(e,t,"onFetchComplete",h)}}catch{}return}const Rt=!J(p)?.data;k(t,{isFetching:!0,isLoading:Rt,isStale:!1,isSuccess:!1,error:null,status:"pending",fetchStatus:"fetching"}),T(t,"onFetchStart"),C(e,t,"onFetchStart");const M=s?.analyze?.emitNetwork,dt=M?typeof performance<"u"?performance.now():Date.now():0;M&&M({phase:"start",mode:"query",from:c,method:n,cacheKey:p,lang:lt});const vt=Dt(async()=>{if(tt!==!1&&a.auth!==!1&&a.getSession){const u=await a.getSession();if(tt===!0&&!u){const w={message:"Not authenticated"};return k(t,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!1,error:w,status:"error",fetchStatus:"idle"}),T(t,"onFetchError",w),C(e,t,"onFetchError",w),{data:null,error:w}}}const d=a[n];if(!(0,f.isFunction)(d))return{data:null,error:{message:`Method "${n}" not found on adapter`}};const l={from:c,select:E,params:L,single:ut,limit:K,offset:et,order:j,headers:N,baseUrl:y},h=ft(t,s);if(h&&(l.headers={...l.headers,"Accept-Language":h}),g!==void 0){if((0,f.isObject)(g))g.offset!==void 0&&(l.offset=g.offset),g.limit!==void 0&&(l.limit=g.limit),g.cursor!==void 0&&(l.params={...l.params,cursor:g.cursor});else if(typeof g=="number"){const u=e.pageSize||K||20;l.offset=(g-1)*u,l.limit=u}}if(m!==void 0&&(l.params={...l.params,cursor:m}),n==="insert"||n==="update"||n==="upsert"){let u;if(R===!0||e.on==="submit")u=X(t);else if((0,f.isArray)(R)){const w=X(t);u={};for(const ht of R)u[ht]=w[ht]}else t.state?.parse?u=t.state.parse():(0,f.isObject)(t.state)&&(u={...t.state});F&&(u=F(u,t,t.state)),l.data=u}if(n==="rpc"){let u=L;if(e.on==="submit"){const w=X(t);u=e.transformParams?e.transformParams(w,t,t.state):w}l.params=u}if(n==="subscribe"){const u=a.subscribe({from:c,params:L,on:e.subscribeOn},(w,ht,ne)=>{z(t,w,O),T(t,"onFetchComplete",w),C(e,t,"onFetchComplete",w)});return i.__unsubscribe=u,{data:null,error:null,subscribed:!0}}return d(l)},st);p&&B.set(p,vt);try{const d=await vt;if(d?.subscribed)return;const{data:l,error:h}=d||{};if(h){p&&H(p,null,h),k(t,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!1,error:h,status:"error",fetchStatus:"idle"}),T(t,"onFetchError",h),C(e,t,"onFetchError",h),M&&M({phase:"error",mode:"query",from:c,method:n,cacheKey:p,error:h.message||h,durationMs:(typeof performance<"u"?performance.now():Date.now())-dt});return}if(l!==void 0){if((n==="select"||n==="rpc")&&p){const w=H(p,l,null);w.gcTime=D?.gcTime||3e5}let u=l;P&&(0,f.isArray)(l)&&(i.__pages||(i.__pages=[]),r.direction==="previous"?i.__pages.unshift(l):i.__pages.push(l),u=i.__pages.flat(),G&&(i.__nextPageParam=G(l,i.__pages),i.__hasNextPage=i.__nextPageParam!=null),S&&(i.__prevPageParam=S(l,i.__pages),i.__hasPreviousPage=i.__prevPageParam!=null)),(0,f.isFunction)(A)&&(u=A(u,t,t.state)),F&&(u=F(u,t,t.state)),(!$||u!==void 0)&&z(t,u,O),k(t,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!0,error:null,status:"success",fetchStatus:"idle"}),T(t,"onFetchComplete",u),C(e,t,"onFetchComplete",u),M&&M({phase:"success",mode:"query",ok:!0,from:c,method:n,cacheKey:p,durationMs:(typeof performance<"u"?performance.now():Date.now())-dt})}}catch(d){k(t,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!1,error:d,status:"error",fetchStatus:"idle"}),T(t,"onFetchError",d),C(e,t,"onFetchError",d),M&&M({phase:"error",mode:"query",from:c,method:n,cacheKey:p,error:d.message||String(d),durationMs:(typeof performance<"u"?performance.now():Date.now())-dt})}finally{p&&B.delete(p)}},Xt=(e,t,s)=>{const r=e.on,o=t.__ref;o.__fetchListeners||(o.__fetchListeners=[]);const a=e.__runner||I;if(r==="submit"){const i=n=>{n.preventDefault(),a(e,t,s)},c=t.node;c&&(c.addEventListener("submit",i),o.__fetchListeners.push(()=>c.removeEventListener("submit",i)))}else if(r==="click"){const i=()=>a(e,t,s),c=t.node;c&&(c.addEventListener("click",i),o.__fetchListeners.push(()=>c.removeEventListener("click",i)))}else r==="stateChange"&&(o.__fetchOnStateChange=()=>a(e,t,s))},Zt=(e,t,s)=>{const r=t.__ref;r.__fetchCleanups||(r.__fetchCleanups=[]),Ht();const o=e.refetchInterval;if(o){const a=typeof o=="number"?o:W(o);if(a>0){const i=setInterval(()=>{(e.refetchIntervalInBackground||typeof document>"u"||document.visibilityState==="visible")&&I(e,t,s,{force:!0})},a);r.__fetchCleanups.push(()=>clearInterval(i))}}if(e.refetchOnWindowFocus!==!1){const a=()=>{const i=ft(t,s),c=At(t,s),n=Bt(e,i,c),_=J(n),v=_t(e.cache);(!_||_.stale||Date.now()-_.time>(v?.staleTime||0))&&I(e,t,s,{force:!0})};x.focus.add(a),r.__fetchCleanups.push(()=>x.focus.delete(a))}if(e.refetchOnReconnect!==!1){const a=()=>I(e,t,s,{force:!0});x.online.add(a),r.__fetchCleanups.push(()=>x.online.delete(a))}},te=(e,t,s)=>{if(!t.optimistic)return null;const r=e.__ref,o=t.as,a=e.state?.parse?e.state.parse():(0,f.isObject)(e.state)?{...e.state}:e.state;r.__optimisticSnapshot=a;const i=(0,f.isFunction)(t.optimistic)?t.optimistic(s,a,e):t.optimistic;return i!==void 0&&z(e,i,o),a},St=(e,t)=>{const s=e.__ref,r=s.__optimisticSnapshot;r!==void 0&&(z(e,r,t.as),delete s.__optimisticSnapshot)},ee=async(e,t,s)=>{const r=s?.fetch;if(!r)return;const o=await gt(r,s);if(!o)return;const a=t.__ref,{method:i,from:c,fields:n,transform:_,as:v,on:Z,auth:F,headers:ut,baseUrl:tt,invalidates:R,optimistic:O,onMutate:K,onSuccess:et,onError:j,onSettled:N}=e;let y;if(n===!0||Z==="submit")y=X(t);else if((0,f.isArray)(n)){const S=X(t);y={};for(const P of n)y[P]=S[P]}else t.state?.parse?y=t.state.parse():(0,f.isObject)(t.state)&&(y={...t.state});_&&(y=_(y,t,t.state)),(0,f.isFunction)(K)&&K(y,t,t.state);const g=O?te(t,e,y):null;a.__fetching=!0,k(t,{isFetching:!0,isLoading:!1,isStale:!1,isSuccess:!1,error:null,status:"pending",fetchStatus:"fetching"}),T(t,"onFetchStart"),C(e,t,"onFetchStart");const m=s?.analyze?.emitNetwork,G=m?typeof performance<"u"?performance.now():Date.now():0;m&&m({phase:"start",mode:"mutation",from:c,method:i});try{if(F!==!1&&o.auth!==!1&&o.getSession){const L=await o.getSession();if(F===!0&&!L){g!==void 0&&St(t,e);const D={message:"Not authenticated"};T(t,"onFetchError",D),C(e,t,"onFetchError",D);return}}const S=o[i];if(!(0,f.isFunction)(S))return;const P={from:c,data:y,headers:ut,baseUrl:tt};e.params&&(P.params=Lt(e.params,t,s));const q=ft(t,s);q&&(P.headers={...P.headers,"Accept-Language":q});const Q=Et(e),A=await Dt(()=>S(P),Q),{data:$,error:E}=A||{};if(E){g!==void 0&&St(t,e),k(t,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!1,error:E,status:"error",fetchStatus:"idle"}),T(t,"onFetchError",E),(0,f.isFunction)(j)&&j(E,y,t),(0,f.isFunction)(N)&&N(null,E,y,t),m&&m({phase:"error",mode:"mutation",from:c,method:i,error:E.message||String(E),durationMs:(typeof performance<"u"?performance.now():Date.now())-G});return}if(delete a.__optimisticSnapshot,$!==void 0){const L=v?{[v]:$}:$;t.state?.update&&t.state.update(L,{preventFetch:!0})}if(k(t,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!0,error:null,status:"success",fetchStatus:"idle"}),T(t,"onFetchComplete",$),C(e,t,"onFetchComplete",$),(0,f.isFunction)(et)&&et($,y,t),(0,f.isFunction)(N)&&N($,null,y,t),m&&m({phase:"success",mode:"mutation",ok:!0,from:c,method:i,durationMs:(typeof performance<"u"?performance.now():Date.now())-G}),R){const L=(0,f.isArray)(R)?R:[R];for(const D of L)if(D===!0||D==="*")for(const[st]of b)st.startsWith(c+":")&&V(st);else V(D)}}catch(S){g!==void 0&&St(t,e),k(t,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!1,error:S,status:"error",fetchStatus:"idle"}),T(t,"onFetchError",S),C(e,t,"onFetchError",S),(0,f.isFunction)(j)&&j(S,y,t),(0,f.isFunction)(N)&&N(null,S,y,t),m&&m({phase:"error",mode:"mutation",from:c,method:i,error:S.message||String(S),durationMs:(typeof performance<"u"?performance.now():Date.now())-G})}finally{a.__fetching=!1}},wt=(e,t,s,r)=>{if(!e||!r?.fetch)return;const a=(0,f.exec)(e,t);if(!a)return;const i=(0,f.isArray)(a)?a.map(n=>Pt((0,f.exec)(n,t),t)).filter(Boolean):[Pt(a,t)].filter(Boolean);for(const n of i){const _=n.method==="insert"||n.method==="update"||n.method==="upsert"||n.method==="delete",v=_?ee:I;n.on==="create"?v(n,t,r):Promise.resolve().then(()=>{Xt({...n,__runner:v},t,r)}),!_&&n.on==="create"&&(n.refetchInterval||n.refetchOnWindowFocus!==!1||n.refetchOnReconnect!==!1)&&Zt(n,t,r)}const c=t.__ref;c.refetch=n=>{for(const _ of i)I(_,t,r,{force:!0,...n})},c.fetchNextPage=()=>{const n=i[0];if(!n||!n.infinite)return;const _=c.__nextPageParam;if(_==null)return;const v={...n,cursor:_};I(v,t,r,{direction:"next",force:!0})},c.fetchPreviousPage=()=>{const n=i[0];if(!n||!n.infinite)return;const _=c.__prevPageParam;if(_==null)return;const v={...n,cursor:_};I(v,t,r,{direction:"previous",force:!0})}},se={invalidateQueries:e=>{if(!e){V();return}if((0,f.isString)(e))for(const[t]of b)(t.startsWith(e)||t.includes(e))&&V(t);else if((0,f.isArray)(e)){const t=e.join(":");for(const[s]of b)s.includes(t)&&V(s)}},removeQueries:e=>{if(!e){it();return}if((0,f.isString)(e))for(const[t]of b)(t.startsWith(e)||t.includes(e))&&it(t)},getQueryData:e=>J(e)?.data??void 0,setQueryData:(e,t)=>{const s=J(e),r=(0,f.isFunction)(t)?t(s?.data):t;H(e,r,null)},prefetchQuery:async(e,t)=>{const s=t?.fetch;if(!s)return;const r=await gt(s,t);if(!r)return;const o=e.cache?.key||`${e.from}:${e.method||"select"}:${JSON.stringify(e.params||"")}`,a=r[e.method||"select"];if(!(0,f.isFunction)(a))return;const i=await a({from:e.from,params:e.params,limit:e.limit,offset:e.offset,order:e.order,single:e.single});if(i?.data!==void 0&&!i?.error){const c=H(o,i.data,null);c.gcTime=_t(e.cache)?.gcTime||3e5}return i},getCache:()=>b,clear:()=>it(),dropNonLang:e=>{if(!e)return;const t=`:${e}`;for(const[s]of b)s.match(/:([a-z]{2,3})$/i)&&(s.endsWith(t)||it(s))}},re={name:"fetch",create(e){const t=e.fetch;t&&(e.parent||B.clear(),wt(t,e,e.state,e.context))}};var ae=wt;
|
|
1
|
+
"use strict";var It=Object.create;var ot=Object.defineProperty;var qt=Object.getOwnPropertyDescriptor;var Ut=Object.getOwnPropertyNames;var zt=Object.getPrototypeOf,jt=Object.prototype.hasOwnProperty;var Gt=(e,t)=>{for(var r in t)ot(e,r,{get:t[r],enumerable:!0})},Ft=(e,t,r,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Ut(t))!jt.call(e,i)&&i!==r&&ot(e,i,{get:()=>t[i],enumerable:!(s=qt(t,i))||s.enumerable});return e};var Et=(e,t,r)=>(r=e!=null?It(zt(e)):{},Ft(t||!e||!e.__esModule?ot(r,"default",{value:e,enumerable:!0}):r,e)),Qt=e=>Ft(ot({},"__esModule",{value:!0}),e);var ne={};Gt(ne,{createAdapter:()=>Jt,default:()=>ae,executeFetch:()=>Tt,fetchPlugin:()=>ie,initAdapterAuth:()=>ut,parseDuration:()=>G,queryClient:()=>oe,registerAdapter:()=>Bt,resolveDb:()=>$t});module.exports=Qt(ne);var n=require("@symbo.ls/utils");const Wt=["select","rpc","insert","update","upsert","delete","subscribe"],xt={rest:()=>import("./adapters/rest.js"),local:()=>import("./adapters/local.js")},it=Symbol.for("@symbo.ls/fetch:CUSTOM_ADAPTERS"),Y=(()=>{if(typeof globalThis<"u"&&globalThis[it])return globalThis[it];const e={};if(typeof globalThis<"u")try{return Object.defineProperty(globalThis,it,{value:e,writable:!1,configurable:!1,enumerable:!1}),globalThis[it]}catch{}return e})(),at=Symbol.for("@symbo.ls/fetch:PENDING_ADAPTERS"),gt=(()=>{if(typeof globalThis<"u"&&globalThis[at])return globalThis[at];const e={};if(typeof globalThis<"u")try{return Object.defineProperty(globalThis,at,{value:e,writable:!1,configurable:!1,enumerable:!1}),globalThis[at]}catch{}return e})(),Kt=5e3,Yt=e=>new Promise(t=>{if(Y[e])return t(Y[e]);const r=gt[e]||=[];let s=!1;const i=()=>{s||(s=!0,t(Y[e]||null))};r.push(i),setTimeout(i,Kt)}),Bt=(e,t)=>{Y[e]=t;const r=gt[e];if(r&&r.length){gt[e]=[];for(const s of r)s()}},Jt=e=>{const t={};for(const r of Wt)e[r]&&(t[r]=e[r]);return t.name=e.name||"custom",t},$t=async e=>{if(!e)return null;if(typeof e.select=="function")return e;const{adapter:t,...r}=e,s=typeof t=="string"?t:typeof e=="string"?e:null;if(!s)return null;let i=Y[s]||xt[s];if(!i&&(i=await Yt(s),!i))throw new Error(`Unknown db adapter: "${s}". Use registerAdapter() for adapters with optional deps.`);const o=await i();if(!o||typeof o.setup!="function")throw new Error(`Adapter "${s}" loader returned a module without a setup() function. Got keys: [${Object.keys(o||{}).join(", ")}]. Likely a bundler chunk-resolution issue.`);return o.setup(r)},G=e=>{if(!e)return 0;if(typeof e=="number")return e;const t=e.match(/^(\d+)(ms|s|m|h)$/);if(!t)return 0;const r=parseInt(t[1]),s=t[2];return s==="ms"?r:s==="s"?r*1e3:s==="m"?r*6e4:s==="h"?r*36e5:0},v=new Map,N=new Map,z=new Map,Ht=(e,t,r)=>{if(e.cache?.key)return e.cache.key;const s=Zt(e.params),i=r?`${r}:`:"",o=`${e.from}:${e.method}:${i}${JSON.stringify(s||"")}`;return t?`${o}:${t}`:o},B=e=>v.get(e)||null,J=(e,t,r)=>{const s=v.get(e),i={data:t,error:r,time:Date.now(),stale:!1};v.set(e,i);const o=N.get(e);if(o)for(const a of o)(0,n.isFunction)(a)&&a(i);return i},H=e=>{if(e){const t=v.get(e);t&&(t.stale=!0);return}for(const[,t]of v)t.stale=!0},nt=e=>{if(e){v.delete(e);return}v.clear()},le=(e,t)=>(N.has(e)||N.set(e,new Set),N.get(e).add(t),()=>{const r=N.get(e);r&&(r.delete(t),r.size===0&&N.delete(e))}),St=e=>!e&&e!==!1?{staleTime:6e4,gcTime:3e5}:e===!1?null:e===!0?{staleTime:6e4,gcTime:3e5}:typeof e=="number"?{staleTime:e,gcTime:Math.max(e*5,3e5)}:(0,n.isString)(e)?{staleTime:G(e),gcTime:3e5}:{staleTime:G(e.stale||e.staleTime)||6e4,gcTime:G(e.gc||e.gcTime||e.expire)||3e5,key:e.key};let ft=null;const Vt=()=>{ft||(ft=setInterval(()=>{const e=Date.now();for(const[t,r]of v){const s=N.get(t);!(s&&s.size>0)&&e-r.time>(r.gcTime||3e5)&&v.delete(t)}},3e4),ft.unref&&ft.unref())};Vt();const Dt=3,wt=e=>Math.min(1e3*2**e,3e4),Ct=e=>{const t=e.retry;return t===!1?{count:0}:t===!0||t===void 0?{count:Dt,delay:wt}:typeof t=="number"?{count:t,delay:wt}:{count:t.count??Dt,delay:(0,n.isFunction)(t.delay)?t.delay:typeof t.delay=="number"?()=>t.delay:wt}},Pt=async(e,t)=>{const{count:r,delay:s}=t;let i;for(let o=0;o<=r;o++)try{const a=await e();if(a?.error){if(i=a.error,o<r){const l=(0,n.isFunction)(s)?s(o,i):s;await new Promise(f=>setTimeout(f,l));continue}return a}return a}catch(a){if(i=a,o<r){const l=(0,n.isFunction)(s)?s(o,a):s;await new Promise(f=>setTimeout(f,l));continue}throw a}return{data:null,error:i}},j={focus:new Set,online:new Set};let At=!1;const Xt=()=>{if(At||typeof window>"u")return;At=!0;const e=()=>{for(const r of j.focus)r()},t=()=>{for(const r of j.online)r()};window.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&e()}),window.addEventListener("focus",e),window.addEventListener("online",t)},Lt=(e,t)=>{const r=t.__ref;if(e===!0)return{from:r.__state||t.key,method:"select",query:!0,on:"create"};if((0,n.isString)(e))return{from:e,method:"select",query:!0,on:"create"};if((0,n.isObject)(e)){const s={...e};return s.from=s.from||r.__state||t.key,s.method=s.method||"select",s.on=s.on||"create",s.query===void 0&&(s.query=!0),s}return null},Zt=e=>(!e||(0,n.isFunction)(e),e),ct=(e,t)=>{const r=e?.state?.root||t?.state?.root;if(r?.lang)return r.lang},bt=(e,t)=>{const s=(e?.state?.root||t?.state?.root)?.__fetchScope;return s?String(s):void 0},kt=(e,t,r)=>{let s;if(!e)s=void 0;else if((0,n.isFunction)(e))s=e(t,t.state);else{s={};for(const i in e){const o=e[i];s[i]=(0,n.isFunction)(o)?o(t,t.state):o}}return s},ut=async(e,t)=>{if(!e||e.__authInitialized||(e.__authInitialized=!0,!e.getSession))return;const r=(s,i)=>{const o=t.state?.root;o?.update&&o.update({auth:{user:s,session:i,loading:!1}})};try{const s=await e.getSession();r(s?.user||null,s)}catch(s){console.warn("[fetch] Failed to restore auth session:",s.message)}e.onAuthStateChange&&e.onAuthStateChange((s,i)=>{r(i?.user||null,i)})},vt=async(e,t)=>{if((0,n.isFunction)(e.select))return e.auth!==!1&&await ut(e,t),e;if(e.__resolved)return e.auth!==!1&&await ut(e.__resolved,t),e.__resolved;if(e.__resolving)return e.__resolving;e.__resolving=$t(e);const r=await e.__resolving;return delete e.__resolving,r?(r.auth=e.auth,r.url=e.url,r.key=e.key,e.__resolved=r,t.fetch=r,e.auth!==!1&&await ut(r,t),r):null},D=(e,t,...r)=>{const s=(0,n.isFunction)(e[t])?e[t]:null;s&&s.call(e,...r,e,e.state,e.context)},P=(e,t,r,...s)=>{const i=e&&(0,n.isFunction)(e[r])?e[r]:null;i&&i.call(t,...s,t,t.state,t.context)},V=e=>{const t={},r=e.node;if(!r)return t;if(r.tagName==="FORM"){const i=new FormData(r);for(const[o,a]of i.entries())t[o]=a;return t}const s=r.querySelectorAll("input, textarea, select");for(let i=0;i<s.length;i++){const o=s[i],a=o.name||o.getAttribute("name");a&&(o.type==="checkbox"?t[a]=o.checked:o.type==="file"?t[a]=o.files:t[a]=o.value)}return t},I=(e,t,r,s={})=>{const i=r&&r.startsWith("~/"),o=i&&e.state?.root||e.state;if(o?.update)if(i){const a=r.slice(2);t&&typeof t=="object"&&!Array.isArray(t)&&a in t?o.update(t,{preventFetch:!0,...s}):o.update({[a]:t},{preventFetch:!0,...s})}else{const a=r?{[r]:t}:t;o.update(a,{preventFetch:!0,...s})}},k=(e,t)=>{const r=e?.__ref;r&&(r.__fetchStatus=t,r.__fetching=t.isFetching,r.__fetchError=t.error)},R=async(e,t,r,s={})=>{const i=r?.fetch;if(!i||!t||!t.__ref)return;const o=t.__ref,a=bt(t,r);(!o.__fetchScopeOwner||o.__fetchScopeOwner.scope!==a)&&(o.__fetchScopeOwner={scope:a});const l=o.__fetchScopeOwner,f=()=>t.__ref===o&&o.__fetchScopeOwner===l&&bt(t,r)===a;if(e.enabled===!1||(0,n.isFunction)(e.enabled)&&!e.enabled(t,t.state)||e.skip===!0||(0,n.isFunction)(e.skip)&&e.skip(t,t.state))return;const h=await vt(i,r);if(!h||!f())return;const{from:g,method:S,query:X,params:lt,cache:Z,transform:T,single:dt,auth:Q,fields:q,as:A,limit:$,offset:w,order:W,headers:C,baseUrl:x,page:p,cursor:L,getNextPageParam:K,getPreviousPageParam:tt,infinite:et,placeholderData:F,initialData:E,select:m,keepPreviousData:O}=e;let U=(0,n.isString)(m)?m:void 0;if(X&&(0,n.isFunction)(t.getQuery)){const d=t.getQuery(h.name||"paths");d&&(U=d.select||d.length&&d.join(",")||U)}const rt=kt(lt,t,r),st=St(Z),Mt=Ct(e),ht=ct(t,r),Ot=ht?`:${ht}`:"",Rt=a?`${a}:`:"",_=st?Z?.key||`${g}:${S}:${Rt}${JSON.stringify(rt||"")}${et?":infinite":""}${p?":p"+JSON.stringify(p):""}${Ot}`:null;if(!o.__fetchInitialized&&_&&(o.__fetchInitialized=!0,E!==void 0)){const d=(0,n.isFunction)(E)?E():E;J(_,d,null)}if((S==="select"||S==="rpc")&&_&&st){const d=B(_);if(d&&!d.error){const u=Date.now()-d.time,y=d.stale||u>(st.staleTime||0);let c=d.data;if((0,n.isFunction)(m)&&(c=m(c,t,t.state)),T&&(c=T(c,t,t.state)),!f())return;if(I(t,c,A),!y){k(t,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!0,error:null,status:"success",fetchStatus:"idle"});return}}else if(F!==void 0){const u=(0,n.isFunction)(F)?F(t,t.state):F;u!==void 0&&I(t,u,A)}}if(_&&z.has(_)&&!s.force){const d=z.get(_);try{const u=await Promise.race([d,new Promise((y,c)=>setTimeout(()=>c("DEDUP_TIMEOUT"),15e3))]);if(!f())return;if(u?.data!==void 0){let y=u.data;if((0,n.isFunction)(m)&&(y=m(y,t,t.state)),T&&(y=T(y,t,t.state)),!f())return;I(t,y,A),D(t,"onFetchComplete",y),P(e,t,"onFetchComplete",y)}}catch{if(!f())return}return}const Nt=!B(_)?.data;k(t,{isFetching:!0,isLoading:Nt,isStale:!1,isSuccess:!1,error:null,status:"pending",fetchStatus:"fetching"}),D(t,"onFetchStart"),P(e,t,"onFetchStart");const M=r?.analyze?.emitNetwork,pt=M?typeof performance<"u"?performance.now():Date.now():0;M&&M({phase:"start",mode:"query",from:g,method:S,cacheKey:_,lang:ht});const _t=Pt(async()=>{if(!f())return;if(Q!==!1&&h.auth!==!1&&h.getSession){const c=await h.getSession();if(!f())return;if(Q===!0&&!c){const b={message:"Not authenticated"};return k(t,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!1,error:b,status:"error",fetchStatus:"idle"}),D(t,"onFetchError",b),P(e,t,"onFetchError",b),{data:null,error:b}}}const d=h[S];if(!(0,n.isFunction)(d))return{data:null,error:{message:`Method "${S}" not found on adapter`}};const u={from:g,select:U,params:rt,single:dt,limit:$,offset:w,order:W,headers:C,baseUrl:x},y=ct(t,r);if(y&&(u.headers={...u.headers,"Accept-Language":y}),p!==void 0){if((0,n.isObject)(p))p.offset!==void 0&&(u.offset=p.offset),p.limit!==void 0&&(u.limit=p.limit),p.cursor!==void 0&&(u.params={...u.params,cursor:p.cursor});else if(typeof p=="number"){const c=e.pageSize||$||20;u.offset=(p-1)*c,u.limit=c}}if(L!==void 0&&(u.params={...u.params,cursor:L}),S==="insert"||S==="update"||S==="upsert"){let c;if(q===!0||e.on==="submit")c=V(t);else if((0,n.isArray)(q)){const b=V(t);c={};for(const yt of q)c[yt]=b[yt]}else t.state?.parse?c=t.state.parse():(0,n.isObject)(t.state)&&(c={...t.state});T&&(c=T(c,t,t.state)),u.data=c}if(S==="rpc"){let c=rt;if(e.on==="submit"){const b=V(t);c=e.transformParams?e.transformParams(b,t,t.state):b}u.params=c}if(S==="subscribe"){const c=h.subscribe({from:g,params:rt,on:e.subscribeOn},(b,yt,ce)=>{f()&&(I(t,b,A),D(t,"onFetchComplete",b),P(e,t,"onFetchComplete",b))});return f()?(o.__unsubscribe=c,{data:null,error:null,subscribed:!0}):((0,n.isFunction)(c)&&c(),{data:null,error:null,subscribed:!0})}return d(u)},Mt);_&&z.set(_,_t);try{const d=await _t;if(!f()||d?.subscribed)return;const{data:u,error:y}=d||{};if(y){_&&J(_,null,y),k(t,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!1,error:y,status:"error",fetchStatus:"idle"}),D(t,"onFetchError",y),P(e,t,"onFetchError",y),M&&M({phase:"error",mode:"query",from:g,method:S,cacheKey:_,error:y.message||y,durationMs:(typeof performance<"u"?performance.now():Date.now())-pt});return}if(u!==void 0){if((S==="select"||S==="rpc")&&_){const b=J(_,u,null);b.gcTime=st?.gcTime||3e5}let c=u;if(et&&(0,n.isArray)(u)&&(o.__pages||(o.__pages=[]),s.direction==="previous"?o.__pages.unshift(u):o.__pages.push(u),c=o.__pages.flat(),K&&(o.__nextPageParam=K(u,o.__pages),o.__hasNextPage=o.__nextPageParam!=null),tt&&(o.__prevPageParam=tt(u,o.__pages),o.__hasPreviousPage=o.__prevPageParam!=null)),(0,n.isFunction)(m)&&(c=m(c,t,t.state)),T&&(c=T(c,t,t.state)),!f())return;(!O||c!==void 0)&&I(t,c,A),k(t,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!0,error:null,status:"success",fetchStatus:"idle"}),D(t,"onFetchComplete",c),P(e,t,"onFetchComplete",c),M&&M({phase:"success",mode:"query",ok:!0,from:g,method:S,cacheKey:_,durationMs:(typeof performance<"u"?performance.now():Date.now())-pt})}}catch(d){if(!f())return;k(t,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!1,error:d,status:"error",fetchStatus:"idle"}),D(t,"onFetchError",d),P(e,t,"onFetchError",d),M&&M({phase:"error",mode:"query",from:g,method:S,cacheKey:_,error:d.message||String(d),durationMs:(typeof performance<"u"?performance.now():Date.now())-pt})}finally{_&&z.get(_)===_t&&z.delete(_)}},te=(e,t,r)=>{const s=e.on,i=t.__ref;i.__fetchListeners||(i.__fetchListeners=[]);const o=e.__runner||R;if(s==="submit"){const a=f=>{f.preventDefault(),o(e,t,r)},l=t.node;l&&(l.addEventListener("submit",a),i.__fetchListeners.push(()=>l.removeEventListener("submit",a)))}else if(s==="click"){const a=()=>o(e,t,r),l=t.node;l&&(l.addEventListener("click",a),i.__fetchListeners.push(()=>l.removeEventListener("click",a)))}else s==="stateChange"&&(i.__fetchOnStateChange=()=>o(e,t,r))},ee=(e,t,r)=>{const s=t.__ref;s.__fetchCleanups||(s.__fetchCleanups=[]),Xt();const i=e.refetchInterval;if(i){const o=typeof i=="number"?i:G(i);if(o>0){const a=setInterval(()=>{(e.refetchIntervalInBackground||typeof document>"u"||document.visibilityState==="visible")&&R(e,t,r,{force:!0})},o);s.__fetchCleanups.push(()=>clearInterval(a))}}if(e.refetchOnWindowFocus!==!1){const o=()=>{const a=ct(t,r),l=bt(t,r),f=Ht(e,a,l),h=B(f),g=St(e.cache);(!h||h.stale||Date.now()-h.time>(g?.staleTime||0))&&R(e,t,r,{force:!0})};j.focus.add(o),s.__fetchCleanups.push(()=>j.focus.delete(o))}if(e.refetchOnReconnect!==!1){const o=()=>R(e,t,r,{force:!0});j.online.add(o),s.__fetchCleanups.push(()=>j.online.delete(o))}},re=(e,t,r)=>{if(!t.optimistic)return null;const s=e.__ref,i=t.as,o=e.state?.parse?e.state.parse():(0,n.isObject)(e.state)?{...e.state}:e.state;s.__optimisticSnapshot=o;const a=(0,n.isFunction)(t.optimistic)?t.optimistic(r,o,e):t.optimistic;return a!==void 0&&I(e,a,i),o},mt=(e,t)=>{const r=e.__ref,s=r.__optimisticSnapshot;s!==void 0&&(I(e,s,t.as),delete r.__optimisticSnapshot)},se=async(e,t,r)=>{const s=r?.fetch;if(!s)return;const i=await vt(s,r);if(!i)return;const o=t.__ref,{method:a,from:l,fields:f,transform:h,as:g,on:S,auth:X,headers:lt,baseUrl:Z,invalidates:T,optimistic:dt,onMutate:Q,onSuccess:q,onError:A,onSettled:$}=e;let w;if(f===!0||S==="submit")w=V(t);else if((0,n.isArray)(f)){const p=V(t);w={};for(const L of f)w[L]=p[L]}else t.state?.parse?w=t.state.parse():(0,n.isObject)(t.state)&&(w={...t.state});h&&(w=h(w,t,t.state)),(0,n.isFunction)(Q)&&Q(w,t,t.state);const W=dt?re(t,e,w):null;o.__fetching=!0,k(t,{isFetching:!0,isLoading:!1,isStale:!1,isSuccess:!1,error:null,status:"pending",fetchStatus:"fetching"}),D(t,"onFetchStart"),P(e,t,"onFetchStart");const C=r?.analyze?.emitNetwork,x=C?typeof performance<"u"?performance.now():Date.now():0;C&&C({phase:"start",mode:"mutation",from:l,method:a});try{if(X!==!1&&i.auth!==!1&&i.getSession){const m=await i.getSession();if(X===!0&&!m){W!==void 0&&mt(t,e);const O={message:"Not authenticated"};D(t,"onFetchError",O),P(e,t,"onFetchError",O);return}}const p=i[a];if(!(0,n.isFunction)(p))return;const L={from:l,data:w,headers:lt,baseUrl:Z};e.params&&(L.params=kt(e.params,t,r));const K=ct(t,r);K&&(L.headers={...L.headers,"Accept-Language":K});const tt=Ct(e),et=await Pt(()=>p(L),tt),{data:F,error:E}=et||{};if(E){W!==void 0&&mt(t,e),k(t,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!1,error:E,status:"error",fetchStatus:"idle"}),D(t,"onFetchError",E),(0,n.isFunction)(A)&&A(E,w,t),(0,n.isFunction)($)&&$(null,E,w,t),C&&C({phase:"error",mode:"mutation",from:l,method:a,error:E.message||String(E),durationMs:(typeof performance<"u"?performance.now():Date.now())-x});return}if(delete o.__optimisticSnapshot,F!==void 0){const m=g?{[g]:F}:F;t.state?.update&&t.state.update(m,{preventFetch:!0})}if(k(t,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!0,error:null,status:"success",fetchStatus:"idle"}),D(t,"onFetchComplete",F),P(e,t,"onFetchComplete",F),(0,n.isFunction)(q)&&q(F,w,t),(0,n.isFunction)($)&&$(F,null,w,t),C&&C({phase:"success",mode:"mutation",ok:!0,from:l,method:a,durationMs:(typeof performance<"u"?performance.now():Date.now())-x}),T){const m=(0,n.isArray)(T)?T:[T];for(const O of m)if(O===!0||O==="*")for(const[U]of v)U.startsWith(l+":")&&H(U);else H(O)}}catch(p){W!==void 0&&mt(t,e),k(t,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!1,error:p,status:"error",fetchStatus:"idle"}),D(t,"onFetchError",p),P(e,t,"onFetchError",p),(0,n.isFunction)(A)&&A(p,w,t),(0,n.isFunction)($)&&$(null,p,w,t),C&&C({phase:"error",mode:"mutation",from:l,method:a,error:p.message||String(p),durationMs:(typeof performance<"u"?performance.now():Date.now())-x})}finally{o.__fetching=!1}},Tt=(e,t,r,s)=>{if(!e||!s?.fetch)return;const o=(0,n.exec)(e,t);if(!o)return;const a=(0,n.isArray)(o)?o.map(f=>Lt((0,n.exec)(f,t),t)).filter(Boolean):[Lt(o,t)].filter(Boolean);for(const f of a){const h=f.method==="insert"||f.method==="update"||f.method==="upsert"||f.method==="delete",g=h?se:R;f.on==="create"?g(f,t,s):Promise.resolve().then(()=>{te({...f,__runner:g},t,s)}),!h&&f.on==="create"&&(f.refetchInterval||f.refetchOnWindowFocus!==!1||f.refetchOnReconnect!==!1)&&ee(f,t,s)}const l=t.__ref;l.refetch=f=>{for(const h of a)R(h,t,s,{force:!0,...f})},l.fetchNextPage=()=>{const f=a[0];if(!f||!f.infinite)return;const h=l.__nextPageParam;if(h==null)return;const g={...f,cursor:h};R(g,t,s,{direction:"next",force:!0})},l.fetchPreviousPage=()=>{const f=a[0];if(!f||!f.infinite)return;const h=l.__prevPageParam;if(h==null)return;const g={...f,cursor:h};R(g,t,s,{direction:"previous",force:!0})}},oe={invalidateQueries:e=>{if(!e){H();return}if((0,n.isString)(e))for(const[t]of v)(t.startsWith(e)||t.includes(e))&&H(t);else if((0,n.isArray)(e)){const t=e.join(":");for(const[r]of v)r.includes(t)&&H(r)}},removeQueries:e=>{if(!e){nt();return}if((0,n.isString)(e))for(const[t]of v)(t.startsWith(e)||t.includes(e))&&nt(t)},getQueryData:e=>B(e)?.data??void 0,setQueryData:(e,t)=>{const r=B(e),s=(0,n.isFunction)(t)?t(r?.data):t;J(e,s,null)},prefetchQuery:async(e,t)=>{const r=t?.fetch;if(!r)return;const s=await vt(r,t);if(!s)return;const i=e.cache?.key||`${e.from}:${e.method||"select"}:${JSON.stringify(e.params||"")}`,o=s[e.method||"select"];if(!(0,n.isFunction)(o))return;const a=await o({from:e.from,params:e.params,limit:e.limit,offset:e.offset,order:e.order,single:e.single});if(a?.data!==void 0&&!a?.error){const l=J(i,a.data,null);l.gcTime=St(e.cache)?.gcTime||3e5}return a},getCache:()=>v,clear:()=>nt(),dropNonLang:e=>{if(!e)return;const t=`:${e}`;for(const[r]of v)r.match(/:([a-z]{2,3})$/i)&&(r.endsWith(t)||nt(r))}},ie={name:"fetch",create(e){const t=e.fetch;t&&(e.parent||z.clear(),Tt(t,e,e.state,e.context))}};var ae=Tt;
|
package/dist/esm/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isArray as x,isFunction as l,isObject as Y,isString as B,exec as Tt}from"@symbo.ls/utils";const Nt=["select","rpc","insert","update","upsert","delete","subscribe"],It={rest:()=>import("./adapters/rest.js"),local:()=>import("./adapters/local.js")},it=Symbol.for("@symbo.ls/fetch:CUSTOM_ADAPTERS"),J=(()=>{if(typeof globalThis<"u"&&globalThis[it])return globalThis[it];const e={};if(typeof globalThis<"u")try{return Object.defineProperty(globalThis,it,{value:e,writable:!1,configurable:!1,enumerable:!1}),globalThis[it]}catch{}return e})(),nt=Symbol.for("@symbo.ls/fetch:PENDING_ADAPTERS"),_t=(()=>{if(typeof globalThis<"u"&&globalThis[nt])return globalThis[nt];const e={};if(typeof globalThis<"u")try{return Object.defineProperty(globalThis,nt,{value:e,writable:!1,configurable:!1,enumerable:!1}),globalThis[nt]}catch{}return e})(),Ot=5e3,qt=e=>new Promise(t=>{if(J[e])return t(J[e]);const s=_t[e]||=[];let r=!1;const i=()=>{r||(r=!0,t(J[e]||null))};s.push(i),setTimeout(i,Ot)}),Vt=(e,t)=>{J[e]=t;const s=_t[e];if(s&&s.length){_t[e]=[];for(const r of s)r()}},Xt=e=>{const t={};for(const s of Nt)e[s]&&(t[s]=e[s]);return t.name=e.name||"custom",t},Ut=async e=>{if(!e)return null;if(typeof e.select=="function")return e;const{adapter:t,...s}=e,r=typeof t=="string"?t:typeof e=="string"?e:null;if(!r)return null;let i=J[r]||It[r];if(!i&&(i=await qt(r),!i))throw new Error(`Unknown db adapter: "${r}". Use registerAdapter() for adapters with optional deps.`);const a=await i();if(!a||typeof a.setup!="function")throw new Error(`Adapter "${r}" loader returned a module without a setup() function. Got keys: [${Object.keys(a||{}).join(", ")}]. Likely a bundler chunk-resolution issue.`);return a.setup(s)},H=e=>{if(!e)return 0;if(typeof e=="number")return e;const t=e.match(/^(\d+)(ms|s|m|h)$/);if(!t)return 0;const s=parseInt(t[1]),r=t[2];return r==="ms"?s:r==="s"?s*1e3:r==="m"?s*6e4:r==="h"?s*36e5:0},b=new Map,U=new Map,V=new Map,zt=(e,t,s)=>{if(e.cache?.key)return e.cache.key;const r=Qt(e.params),i=s?`${s}:`:"",a=`${e.from}:${e.method}:${i}${JSON.stringify(r||"")}`;return t?`${a}:${t}`:a},X=e=>b.get(e)||null,Z=(e,t,s)=>{const r=b.get(e),i={data:t,error:s,time:Date.now(),stale:!1};b.set(e,i);const a=U.get(e);if(a)for(const o of a)l(o)&&o(i);return i},tt=e=>{if(e){const t=b.get(e);t&&(t.stale=!0);return}for(const[,t]of b)t.stale=!0},ft=e=>{if(e){b.delete(e);return}b.clear()},Zt=(e,t)=>(U.has(e)||U.set(e,new Set),U.get(e).add(t),()=>{const s=U.get(e);s&&(s.delete(t),s.size===0&&U.delete(e))}),yt=e=>!e&&e!==!1?{staleTime:6e4,gcTime:3e5}:e===!1?null:e===!0?{staleTime:6e4,gcTime:3e5}:typeof e=="number"?{staleTime:e,gcTime:Math.max(e*5,3e5)}:B(e)?{staleTime:H(e),gcTime:3e5}:{staleTime:H(e.stale||e.staleTime)||6e4,gcTime:H(e.gc||e.gcTime||e.expire)||3e5,key:e.key};let ct=null;const jt=()=>{ct||(ct=setInterval(()=>{const e=Date.now();for(const[t,s]of b){const r=U.get(t);!(r&&r.size>0)&&e-s.time>(s.gcTime||3e5)&&b.delete(t)}},3e4),ct.unref&&ct.unref())};jt();const Ft=3,gt=e=>Math.min(1e3*2**e,3e4),Et=e=>{const t=e.retry;return t===!1?{count:0}:t===!0||t===void 0?{count:Ft,delay:gt}:typeof t=="number"?{count:t,delay:gt}:{count:t.count??Ft,delay:l(t.delay)?t.delay:typeof t.delay=="number"?()=>t.delay:gt}},Dt=async(e,t)=>{const{count:s,delay:r}=t;let i;for(let a=0;a<=s;a++)try{const o=await e();if(o?.error){if(i=o.error,a<s){const f=l(r)?r(a,i):r;await new Promise(n=>setTimeout(n,f));continue}return o}return o}catch(o){if(i=o,a<s){const f=l(r)?r(a,o):r;await new Promise(n=>setTimeout(n,f));continue}throw o}return{data:null,error:i}},W={focus:new Set,online:new Set};let Ct=!1;const Gt=()=>{if(Ct||typeof window>"u")return;Ct=!0;const e=()=>{for(const s of W.focus)s()},t=()=>{for(const s of W.online)s()};window.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&e()}),window.addEventListener("focus",e),window.addEventListener("online",t)},Pt=(e,t)=>{const s=t.__ref;if(e===!0)return{from:s.__state||t.key,method:"select",query:!0,on:"create"};if(B(e))return{from:e,method:"select",query:!0,on:"create"};if(Y(e)){const r={...e};return r.from=r.from||s.__state||t.key,r.method=r.method||"select",r.on=r.on||"create",r.query===void 0&&(r.query=!0),r}return null},Qt=e=>(!e||l(e),e),ut=(e,t)=>{const s=e?.state?.root||t?.state?.root;if(s?.lang)return s.lang},At=(e,t)=>{const r=(e?.state?.root||t?.state?.root)?.__fetchScope;return r?String(r):void 0},Lt=(e,t,s)=>{let r;if(!e)r=void 0;else if(l(e))r=e(t,t.state);else{r={};for(const i in e){const a=e[i];r[i]=l(a)?a(t,t.state):a}}return r},St=async(e,t)=>{if(!e||e.__authInitialized||(e.__authInitialized=!0,!e.getSession))return;const s=(r,i)=>{const a=t.state?.root;a?.update&&a.update({auth:{user:r,session:i,loading:!1}})};try{const r=await e.getSession();s(r?.user||null,r)}catch(r){console.warn("[fetch] Failed to restore auth session:",r.message)}e.onAuthStateChange&&e.onAuthStateChange((r,i)=>{s(i?.user||null,i)})},wt=async(e,t)=>{if(l(e.select))return e.auth!==!1&&await St(e,t),e;if(e.__resolved)return e.auth!==!1&&await St(e.__resolved,t),e.__resolved;if(e.__resolving)return e.__resolving;e.__resolving=Ut(e);const s=await e.__resolving;return delete e.__resolving,s?(s.auth=e.auth,s.url=e.url,s.key=e.key,e.__resolved=s,t.fetch=s,e.auth!==!1&&await St(s,t),s):null},T=(e,t,...s)=>{const r=l(e[t])?e[t]:null;r&&r.call(e,...s,e,e.state,e.context)},C=(e,t,s,...r)=>{const i=e&&l(e[s])?e[s]:null;i&&i.call(t,...r,t,t.state,t.context)},et=e=>{const t={},s=e.node;if(!s)return t;if(s.tagName==="FORM"){const i=new FormData(s);for(const[a,o]of i.entries())t[a]=o;return t}const r=s.querySelectorAll("input, textarea, select");for(let i=0;i<r.length;i++){const a=r[i],o=a.name||a.getAttribute("name");o&&(a.type==="checkbox"?t[o]=a.checked:a.type==="file"?t[o]=a.files:t[o]=a.value)}return t},z=(e,t,s,r={})=>{const i=s&&s.startsWith("~/"),a=i&&e.state?.root||e.state;if(a?.update)if(i){const o=s.slice(2);t&&typeof t=="object"&&!Array.isArray(t)&&o in t?a.update(t,{preventFetch:!0,...r}):a.update({[o]:t},{preventFetch:!0,...r})}else{const o=s?{[s]:t}:t;a.update(o,{preventFetch:!0,...r})}},k=(e,t)=>{const s=e?.__ref;s&&(s.__fetchStatus=t,s.__fetching=t.isFetching,s.__fetchError=t.error)},I=async(e,t,s,r={})=>{const i=s?.fetch;if(!i||!t||!t.__ref||e.enabled===!1||l(e.enabled)&&!e.enabled(t,t.state)||e.skip===!0||l(e.skip)&&e.skip(t,t.state))return;const a=await wt(i,s);if(!a||!t.__ref)return;const o=t.__ref,{from:f,method:n,query:_,params:v,cache:st,transform:F,single:lt,auth:rt,fields:R,as:O,limit:K,offset:at,order:j,headers:N,baseUrl:y,page:g,cursor:m,getNextPageParam:G,getPreviousPageParam:S,infinite:P,placeholderData:q,initialData:Q,select:A,keepPreviousData:$}=e;let E=B(A)?A:void 0;if(_&&l(t.getQuery)){const d=t.getQuery(a.name||"paths");d&&(E=d.select||d.length&&d.join(",")||E)}const L=Lt(v,t,s),D=yt(st),ot=Et(e),dt=ut(t,s),vt=At(t,s),$t=dt?`:${dt}`:"",Mt=vt?`${vt}:`:"",p=D?st?.key||`${f}:${n}:${Mt}${JSON.stringify(L||"")}${P?":infinite":""}${g?":p"+JSON.stringify(g):""}${$t}`:null;if(!o.__fetchInitialized&&p&&(o.__fetchInitialized=!0,Q!==void 0)){const d=l(Q)?Q():Q;Z(p,d,null)}if((n==="select"||n==="rpc")&&p&&D){const d=X(p);if(d&&!d.error){const u=Date.now()-d.time,h=d.stale||u>(D.staleTime||0);let c=d.data;if(l(A)&&(c=A(c,t,t.state)),F&&(c=F(c,t,t.state)),z(t,c,O),!h){k(t,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!0,error:null,status:"success",fetchStatus:"idle"});return}}else if(q!==void 0){const u=l(q)?q(t,t.state):q;u!==void 0&&z(t,u,O)}}if(p&&V.has(p)&&!r.force){const d=V.get(p);try{const u=await Promise.race([d,new Promise((h,c)=>setTimeout(()=>c("DEDUP_TIMEOUT"),15e3))]);if(u?.data!==void 0){let h=u.data;l(A)&&(h=A(h,t,t.state)),F&&(h=F(h,t,t.state)),z(t,h,O),T(t,"onFetchComplete",h),C(e,t,"onFetchComplete",h)}}catch{}return}const Rt=!X(p)?.data;k(t,{isFetching:!0,isLoading:Rt,isStale:!1,isSuccess:!1,error:null,status:"pending",fetchStatus:"fetching"}),T(t,"onFetchStart"),C(e,t,"onFetchStart");const M=s?.analyze?.emitNetwork,ht=M?typeof performance<"u"?performance.now():Date.now():0;M&&M({phase:"start",mode:"query",from:f,method:n,cacheKey:p,lang:dt});const mt=Dt(async()=>{if(rt!==!1&&a.auth!==!1&&a.getSession){const c=await a.getSession();if(rt===!0&&!c){const w={message:"Not authenticated"};return k(t,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!1,error:w,status:"error",fetchStatus:"idle"}),T(t,"onFetchError",w),C(e,t,"onFetchError",w),{data:null,error:w}}}const d=a[n];if(!l(d))return{data:null,error:{message:`Method "${n}" not found on adapter`}};const u={from:f,select:E,params:L,single:lt,limit:K,offset:at,order:j,headers:N,baseUrl:y},h=ut(t,s);if(h&&(u.headers={...u.headers,"Accept-Language":h}),g!==void 0){if(Y(g))g.offset!==void 0&&(u.offset=g.offset),g.limit!==void 0&&(u.limit=g.limit),g.cursor!==void 0&&(u.params={...u.params,cursor:g.cursor});else if(typeof g=="number"){const c=e.pageSize||K||20;u.offset=(g-1)*c,u.limit=c}}if(m!==void 0&&(u.params={...u.params,cursor:m}),n==="insert"||n==="update"||n==="upsert"){let c;if(R===!0||e.on==="submit")c=et(t);else if(x(R)){const w=et(t);c={};for(const pt of R)c[pt]=w[pt]}else t.state?.parse?c=t.state.parse():Y(t.state)&&(c={...t.state});F&&(c=F(c,t,t.state)),u.data=c}if(n==="rpc"){let c=L;if(e.on==="submit"){const w=et(t);c=e.transformParams?e.transformParams(w,t,t.state):w}u.params=c}if(n==="subscribe"){const c=a.subscribe({from:f,params:L,on:e.subscribeOn},(w,pt,Jt)=>{z(t,w,O),T(t,"onFetchComplete",w),C(e,t,"onFetchComplete",w)});return o.__unsubscribe=c,{data:null,error:null,subscribed:!0}}return d(u)},ot);p&&V.set(p,mt);try{const d=await mt;if(d?.subscribed)return;const{data:u,error:h}=d||{};if(h){p&&Z(p,null,h),k(t,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!1,error:h,status:"error",fetchStatus:"idle"}),T(t,"onFetchError",h),C(e,t,"onFetchError",h),M&&M({phase:"error",mode:"query",from:f,method:n,cacheKey:p,error:h.message||h,durationMs:(typeof performance<"u"?performance.now():Date.now())-ht});return}if(u!==void 0){if((n==="select"||n==="rpc")&&p){const w=Z(p,u,null);w.gcTime=D?.gcTime||3e5}let c=u;P&&x(u)&&(o.__pages||(o.__pages=[]),r.direction==="previous"?o.__pages.unshift(u):o.__pages.push(u),c=o.__pages.flat(),G&&(o.__nextPageParam=G(u,o.__pages),o.__hasNextPage=o.__nextPageParam!=null),S&&(o.__prevPageParam=S(u,o.__pages),o.__hasPreviousPage=o.__prevPageParam!=null)),l(A)&&(c=A(c,t,t.state)),F&&(c=F(c,t,t.state)),(!$||c!==void 0)&&z(t,c,O),k(t,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!0,error:null,status:"success",fetchStatus:"idle"}),T(t,"onFetchComplete",c),C(e,t,"onFetchComplete",c),M&&M({phase:"success",mode:"query",ok:!0,from:f,method:n,cacheKey:p,durationMs:(typeof performance<"u"?performance.now():Date.now())-ht})}}catch(d){k(t,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!1,error:d,status:"error",fetchStatus:"idle"}),T(t,"onFetchError",d),C(e,t,"onFetchError",d),M&&M({phase:"error",mode:"query",from:f,method:n,cacheKey:p,error:d.message||String(d),durationMs:(typeof performance<"u"?performance.now():Date.now())-ht})}finally{p&&V.delete(p)}},xt=(e,t,s)=>{const r=e.on,i=t.__ref;i.__fetchListeners||(i.__fetchListeners=[]);const a=e.__runner||I;if(r==="submit"){const o=n=>{n.preventDefault(),a(e,t,s)},f=t.node;f&&(f.addEventListener("submit",o),i.__fetchListeners.push(()=>f.removeEventListener("submit",o)))}else if(r==="click"){const o=()=>a(e,t,s),f=t.node;f&&(f.addEventListener("click",o),i.__fetchListeners.push(()=>f.removeEventListener("click",o)))}else r==="stateChange"&&(i.__fetchOnStateChange=()=>a(e,t,s))},Wt=(e,t,s)=>{const r=t.__ref;r.__fetchCleanups||(r.__fetchCleanups=[]),Gt();const i=e.refetchInterval;if(i){const a=typeof i=="number"?i:H(i);if(a>0){const o=setInterval(()=>{(e.refetchIntervalInBackground||typeof document>"u"||document.visibilityState==="visible")&&I(e,t,s,{force:!0})},a);r.__fetchCleanups.push(()=>clearInterval(o))}}if(e.refetchOnWindowFocus!==!1){const a=()=>{const o=ut(t,s),f=At(t,s),n=zt(e,o,f),_=X(n),v=yt(e.cache);(!_||_.stale||Date.now()-_.time>(v?.staleTime||0))&&I(e,t,s,{force:!0})};W.focus.add(a),r.__fetchCleanups.push(()=>W.focus.delete(a))}if(e.refetchOnReconnect!==!1){const a=()=>I(e,t,s,{force:!0});W.online.add(a),r.__fetchCleanups.push(()=>W.online.delete(a))}},Kt=(e,t,s)=>{if(!t.optimistic)return null;const r=e.__ref,i=t.as,a=e.state?.parse?e.state.parse():Y(e.state)?{...e.state}:e.state;r.__optimisticSnapshot=a;const o=l(t.optimistic)?t.optimistic(s,a,e):t.optimistic;return o!==void 0&&z(e,o,i),a},bt=(e,t)=>{const s=e.__ref,r=s.__optimisticSnapshot;r!==void 0&&(z(e,r,t.as),delete s.__optimisticSnapshot)},Yt=async(e,t,s)=>{const r=s?.fetch;if(!r)return;const i=await wt(r,s);if(!i)return;const a=t.__ref,{method:o,from:f,fields:n,transform:_,as:v,on:st,auth:F,headers:lt,baseUrl:rt,invalidates:R,optimistic:O,onMutate:K,onSuccess:at,onError:j,onSettled:N}=e;let y;if(n===!0||st==="submit")y=et(t);else if(x(n)){const S=et(t);y={};for(const P of n)y[P]=S[P]}else t.state?.parse?y=t.state.parse():Y(t.state)&&(y={...t.state});_&&(y=_(y,t,t.state)),l(K)&&K(y,t,t.state);const g=O?Kt(t,e,y):null;a.__fetching=!0,k(t,{isFetching:!0,isLoading:!1,isStale:!1,isSuccess:!1,error:null,status:"pending",fetchStatus:"fetching"}),T(t,"onFetchStart"),C(e,t,"onFetchStart");const m=s?.analyze?.emitNetwork,G=m?typeof performance<"u"?performance.now():Date.now():0;m&&m({phase:"start",mode:"mutation",from:f,method:o});try{if(F!==!1&&i.auth!==!1&&i.getSession){const L=await i.getSession();if(F===!0&&!L){g!==void 0&&bt(t,e);const D={message:"Not authenticated"};T(t,"onFetchError",D),C(e,t,"onFetchError",D);return}}const S=i[o];if(!l(S))return;const P={from:f,data:y,headers:lt,baseUrl:rt};e.params&&(P.params=Lt(e.params,t,s));const q=ut(t,s);q&&(P.headers={...P.headers,"Accept-Language":q});const Q=Et(e),A=await Dt(()=>S(P),Q),{data:$,error:E}=A||{};if(E){g!==void 0&&bt(t,e),k(t,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!1,error:E,status:"error",fetchStatus:"idle"}),T(t,"onFetchError",E),l(j)&&j(E,y,t),l(N)&&N(null,E,y,t),m&&m({phase:"error",mode:"mutation",from:f,method:o,error:E.message||String(E),durationMs:(typeof performance<"u"?performance.now():Date.now())-G});return}if(delete a.__optimisticSnapshot,$!==void 0){const L=v?{[v]:$}:$;t.state?.update&&t.state.update(L,{preventFetch:!0})}if(k(t,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!0,error:null,status:"success",fetchStatus:"idle"}),T(t,"onFetchComplete",$),C(e,t,"onFetchComplete",$),l(at)&&at($,y,t),l(N)&&N($,null,y,t),m&&m({phase:"success",mode:"mutation",ok:!0,from:f,method:o,durationMs:(typeof performance<"u"?performance.now():Date.now())-G}),R){const L=x(R)?R:[R];for(const D of L)if(D===!0||D==="*")for(const[ot]of b)ot.startsWith(f+":")&&tt(ot);else tt(D)}}catch(S){g!==void 0&&bt(t,e),k(t,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!1,error:S,status:"error",fetchStatus:"idle"}),T(t,"onFetchError",S),C(e,t,"onFetchError",S),l(j)&&j(S,y,t),l(N)&&N(null,S,y,t),m&&m({phase:"error",mode:"mutation",from:f,method:o,error:S.message||String(S),durationMs:(typeof performance<"u"?performance.now():Date.now())-G})}finally{a.__fetching=!1}},kt=(e,t,s,r)=>{if(!e||!r?.fetch)return;const a=Tt(e,t);if(!a)return;const o=x(a)?a.map(n=>Pt(Tt(n,t),t)).filter(Boolean):[Pt(a,t)].filter(Boolean);for(const n of o){const _=n.method==="insert"||n.method==="update"||n.method==="upsert"||n.method==="delete",v=_?Yt:I;n.on==="create"?v(n,t,r):Promise.resolve().then(()=>{xt({...n,__runner:v},t,r)}),!_&&n.on==="create"&&(n.refetchInterval||n.refetchOnWindowFocus!==!1||n.refetchOnReconnect!==!1)&&Wt(n,t,r)}const f=t.__ref;f.refetch=n=>{for(const _ of o)I(_,t,r,{force:!0,...n})},f.fetchNextPage=()=>{const n=o[0];if(!n||!n.infinite)return;const _=f.__nextPageParam;if(_==null)return;const v={...n,cursor:_};I(v,t,r,{direction:"next",force:!0})},f.fetchPreviousPage=()=>{const n=o[0];if(!n||!n.infinite)return;const _=f.__prevPageParam;if(_==null)return;const v={...n,cursor:_};I(v,t,r,{direction:"previous",force:!0})}},te={invalidateQueries:e=>{if(!e){tt();return}if(B(e))for(const[t]of b)(t.startsWith(e)||t.includes(e))&&tt(t);else if(x(e)){const t=e.join(":");for(const[s]of b)s.includes(t)&&tt(s)}},removeQueries:e=>{if(!e){ft();return}if(B(e))for(const[t]of b)(t.startsWith(e)||t.includes(e))&&ft(t)},getQueryData:e=>X(e)?.data??void 0,setQueryData:(e,t)=>{const s=X(e),r=l(t)?t(s?.data):t;Z(e,r,null)},prefetchQuery:async(e,t)=>{const s=t?.fetch;if(!s)return;const r=await wt(s,t);if(!r)return;const i=e.cache?.key||`${e.from}:${e.method||"select"}:${JSON.stringify(e.params||"")}`,a=r[e.method||"select"];if(!l(a))return;const o=await a({from:e.from,params:e.params,limit:e.limit,offset:e.offset,order:e.order,single:e.single});if(o?.data!==void 0&&!o?.error){const f=Z(i,o.data,null);f.gcTime=yt(e.cache)?.gcTime||3e5}return o},getCache:()=>b,clear:()=>ft(),dropNonLang:e=>{if(!e)return;const t=`:${e}`;for(const[s]of b)s.match(/:([a-z]{2,3})$/i)&&(s.endsWith(t)||ft(s))}},ee={name:"fetch",create(e){const t=e.fetch;t&&(e.parent||V.clear(),kt(t,e,e.state,e.context))}};var se=kt;export{Xt as createAdapter,se as default,kt as executeFetch,ee as fetchPlugin,St as initAdapterAuth,H as parseDuration,te as queryClient,Vt as registerAdapter,Ut as resolveDb};
|
|
1
|
+
import{isArray as z,isFunction as u,isObject as Y,isString as B,exec as Et}from"@symbo.ls/utils";const It=["select","rpc","insert","update","upsert","delete","subscribe"],qt={rest:()=>import("./adapters/rest.js"),local:()=>import("./adapters/local.js")},nt=Symbol.for("@symbo.ls/fetch:CUSTOM_ADAPTERS"),J=(()=>{if(typeof globalThis<"u"&&globalThis[nt])return globalThis[nt];const e={};if(typeof globalThis<"u")try{return Object.defineProperty(globalThis,nt,{value:e,writable:!1,configurable:!1,enumerable:!1}),globalThis[nt]}catch{}return e})(),ft=Symbol.for("@symbo.ls/fetch:PENDING_ADAPTERS"),St=(()=>{if(typeof globalThis<"u"&&globalThis[ft])return globalThis[ft];const e={};if(typeof globalThis<"u")try{return Object.defineProperty(globalThis,ft,{value:e,writable:!1,configurable:!1,enumerable:!1}),globalThis[ft]}catch{}return e})(),Ut=5e3,zt=e=>new Promise(t=>{if(J[e])return t(J[e]);const r=St[e]||=[];let s=!1;const i=()=>{s||(s=!0,t(J[e]||null))};r.push(i),setTimeout(i,Ut)}),Zt=(e,t)=>{J[e]=t;const r=St[e];if(r&&r.length){St[e]=[];for(const s of r)s()}},te=e=>{const t={};for(const r of It)e[r]&&(t[r]=e[r]);return t.name=e.name||"custom",t},jt=async e=>{if(!e)return null;if(typeof e.select=="function")return e;const{adapter:t,...r}=e,s=typeof t=="string"?t:typeof e=="string"?e:null;if(!s)return null;let i=J[s]||qt[s];if(!i&&(i=await zt(s),!i))throw new Error(`Unknown db adapter: "${s}". Use registerAdapter() for adapters with optional deps.`);const o=await i();if(!o||typeof o.setup!="function")throw new Error(`Adapter "${s}" loader returned a module without a setup() function. Got keys: [${Object.keys(o||{}).join(", ")}]. Likely a bundler chunk-resolution issue.`);return o.setup(r)},H=e=>{if(!e)return 0;if(typeof e=="number")return e;const t=e.match(/^(\d+)(ms|s|m|h)$/);if(!t)return 0;const r=parseInt(t[1]),s=t[2];return s==="ms"?r:s==="s"?r*1e3:s==="m"?r*6e4:s==="h"?r*36e5:0},v=new Map,N=new Map,j=new Map,Gt=(e,t,r)=>{if(e.cache?.key)return e.cache.key;const s=xt(e.params),i=r?`${r}:`:"",o=`${e.from}:${e.method}:${i}${JSON.stringify(s||"")}`;return t?`${o}:${t}`:o},V=e=>v.get(e)||null,X=(e,t,r)=>{const s=v.get(e),i={data:t,error:r,time:Date.now(),stale:!1};v.set(e,i);const o=N.get(e);if(o)for(const a of o)u(a)&&a(i);return i},Z=e=>{if(e){const t=v.get(e);t&&(t.stale=!0);return}for(const[,t]of v)t.stale=!0},ct=e=>{if(e){v.delete(e);return}v.clear()},ee=(e,t)=>(N.has(e)||N.set(e,new Set),N.get(e).add(t),()=>{const r=N.get(e);r&&(r.delete(t),r.size===0&&N.delete(e))}),wt=e=>!e&&e!==!1?{staleTime:6e4,gcTime:3e5}:e===!1?null:e===!0?{staleTime:6e4,gcTime:3e5}:typeof e=="number"?{staleTime:e,gcTime:Math.max(e*5,3e5)}:B(e)?{staleTime:H(e),gcTime:3e5}:{staleTime:H(e.stale||e.staleTime)||6e4,gcTime:H(e.gc||e.gcTime||e.expire)||3e5,key:e.key};let ut=null;const Qt=()=>{ut||(ut=setInterval(()=>{const e=Date.now();for(const[t,r]of v){const s=N.get(t);!(s&&s.size>0)&&e-r.time>(r.gcTime||3e5)&&v.delete(t)}},3e4),ut.unref&&ut.unref())};Qt();const Dt=3,bt=e=>Math.min(1e3*2**e,3e4),Ct=e=>{const t=e.retry;return t===!1?{count:0}:t===!0||t===void 0?{count:Dt,delay:bt}:typeof t=="number"?{count:t,delay:bt}:{count:t.count??Dt,delay:u(t.delay)?t.delay:typeof t.delay=="number"?()=>t.delay:bt}},Pt=async(e,t)=>{const{count:r,delay:s}=t;let i;for(let o=0;o<=r;o++)try{const a=await e();if(a?.error){if(i=a.error,o<r){const l=u(s)?s(o,i):s;await new Promise(n=>setTimeout(n,l));continue}return a}return a}catch(a){if(i=a,o<r){const l=u(s)?s(o,a):s;await new Promise(n=>setTimeout(n,l));continue}throw a}return{data:null,error:i}},G={focus:new Set,online:new Set};let At=!1;const Wt=()=>{if(At||typeof window>"u")return;At=!0;const e=()=>{for(const r of G.focus)r()},t=()=>{for(const r of G.online)r()};window.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&e()}),window.addEventListener("focus",e),window.addEventListener("online",t)},Lt=(e,t)=>{const r=t.__ref;if(e===!0)return{from:r.__state||t.key,method:"select",query:!0,on:"create"};if(B(e))return{from:e,method:"select",query:!0,on:"create"};if(Y(e)){const s={...e};return s.from=s.from||r.__state||t.key,s.method=s.method||"select",s.on=s.on||"create",s.query===void 0&&(s.query=!0),s}return null},xt=e=>(!e||u(e),e),lt=(e,t)=>{const r=e?.state?.root||t?.state?.root;if(r?.lang)return r.lang},vt=(e,t)=>{const s=(e?.state?.root||t?.state?.root)?.__fetchScope;return s?String(s):void 0},kt=(e,t,r)=>{let s;if(!e)s=void 0;else if(u(e))s=e(t,t.state);else{s={};for(const i in e){const o=e[i];s[i]=u(o)?o(t,t.state):o}}return s},mt=async(e,t)=>{if(!e||e.__authInitialized||(e.__authInitialized=!0,!e.getSession))return;const r=(s,i)=>{const o=t.state?.root;o?.update&&o.update({auth:{user:s,session:i,loading:!1}})};try{const s=await e.getSession();r(s?.user||null,s)}catch(s){console.warn("[fetch] Failed to restore auth session:",s.message)}e.onAuthStateChange&&e.onAuthStateChange((s,i)=>{r(i?.user||null,i)})},Tt=async(e,t)=>{if(u(e.select))return e.auth!==!1&&await mt(e,t),e;if(e.__resolved)return e.auth!==!1&&await mt(e.__resolved,t),e.__resolved;if(e.__resolving)return e.__resolving;e.__resolving=jt(e);const r=await e.__resolving;return delete e.__resolving,r?(r.auth=e.auth,r.url=e.url,r.key=e.key,e.__resolved=r,t.fetch=r,e.auth!==!1&&await mt(r,t),r):null},D=(e,t,...r)=>{const s=u(e[t])?e[t]:null;s&&s.call(e,...r,e,e.state,e.context)},P=(e,t,r,...s)=>{const i=e&&u(e[r])?e[r]:null;i&&i.call(t,...s,t,t.state,t.context)},tt=e=>{const t={},r=e.node;if(!r)return t;if(r.tagName==="FORM"){const i=new FormData(r);for(const[o,a]of i.entries())t[o]=a;return t}const s=r.querySelectorAll("input, textarea, select");for(let i=0;i<s.length;i++){const o=s[i],a=o.name||o.getAttribute("name");a&&(o.type==="checkbox"?t[a]=o.checked:o.type==="file"?t[a]=o.files:t[a]=o.value)}return t},I=(e,t,r,s={})=>{const i=r&&r.startsWith("~/"),o=i&&e.state?.root||e.state;if(o?.update)if(i){const a=r.slice(2);t&&typeof t=="object"&&!Array.isArray(t)&&a in t?o.update(t,{preventFetch:!0,...s}):o.update({[a]:t},{preventFetch:!0,...s})}else{const a=r?{[r]:t}:t;o.update(a,{preventFetch:!0,...s})}},k=(e,t)=>{const r=e?.__ref;r&&(r.__fetchStatus=t,r.__fetching=t.isFetching,r.__fetchError=t.error)},R=async(e,t,r,s={})=>{const i=r?.fetch;if(!i||!t||!t.__ref)return;const o=t.__ref,a=vt(t,r);(!o.__fetchScopeOwner||o.__fetchScopeOwner.scope!==a)&&(o.__fetchScopeOwner={scope:a});const l=o.__fetchScopeOwner,n=()=>t.__ref===o&&o.__fetchScopeOwner===l&&vt(t,r)===a;if(e.enabled===!1||u(e.enabled)&&!e.enabled(t,t.state)||e.skip===!0||u(e.skip)&&e.skip(t,t.state))return;const h=await Tt(i,r);if(!h||!n())return;const{from:g,method:S,query:et,params:dt,cache:rt,transform:T,single:ht,auth:Q,fields:q,as:A,limit:$,offset:w,order:W,headers:C,baseUrl:x,page:p,cursor:L,getNextPageParam:K,getPreviousPageParam:st,infinite:ot,placeholderData:F,initialData:E,select:m,keepPreviousData:O}=e;let U=B(m)?m:void 0;if(et&&u(t.getQuery)){const d=t.getQuery(h.name||"paths");d&&(U=d.select||d.length&&d.join(",")||U)}const it=kt(dt,t,r),at=wt(rt),Mt=Ct(e),pt=lt(t,r),Ot=pt?`:${pt}`:"",Rt=a?`${a}:`:"",_=at?rt?.key||`${g}:${S}:${Rt}${JSON.stringify(it||"")}${ot?":infinite":""}${p?":p"+JSON.stringify(p):""}${Ot}`:null;if(!o.__fetchInitialized&&_&&(o.__fetchInitialized=!0,E!==void 0)){const d=u(E)?E():E;X(_,d,null)}if((S==="select"||S==="rpc")&&_&&at){const d=V(_);if(d&&!d.error){const c=Date.now()-d.time,y=d.stale||c>(at.staleTime||0);let f=d.data;if(u(m)&&(f=m(f,t,t.state)),T&&(f=T(f,t,t.state)),!n())return;if(I(t,f,A),!y){k(t,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!0,error:null,status:"success",fetchStatus:"idle"});return}}else if(F!==void 0){const c=u(F)?F(t,t.state):F;c!==void 0&&I(t,c,A)}}if(_&&j.has(_)&&!s.force){const d=j.get(_);try{const c=await Promise.race([d,new Promise((y,f)=>setTimeout(()=>f("DEDUP_TIMEOUT"),15e3))]);if(!n())return;if(c?.data!==void 0){let y=c.data;if(u(m)&&(y=m(y,t,t.state)),T&&(y=T(y,t,t.state)),!n())return;I(t,y,A),D(t,"onFetchComplete",y),P(e,t,"onFetchComplete",y)}}catch{if(!n())return}return}const Nt=!V(_)?.data;k(t,{isFetching:!0,isLoading:Nt,isStale:!1,isSuccess:!1,error:null,status:"pending",fetchStatus:"fetching"}),D(t,"onFetchStart"),P(e,t,"onFetchStart");const M=r?.analyze?.emitNetwork,_t=M?typeof performance<"u"?performance.now():Date.now():0;M&&M({phase:"start",mode:"query",from:g,method:S,cacheKey:_,lang:pt});const yt=Pt(async()=>{if(!n())return;if(Q!==!1&&h.auth!==!1&&h.getSession){const f=await h.getSession();if(!n())return;if(Q===!0&&!f){const b={message:"Not authenticated"};return k(t,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!1,error:b,status:"error",fetchStatus:"idle"}),D(t,"onFetchError",b),P(e,t,"onFetchError",b),{data:null,error:b}}}const d=h[S];if(!u(d))return{data:null,error:{message:`Method "${S}" not found on adapter`}};const c={from:g,select:U,params:it,single:ht,limit:$,offset:w,order:W,headers:C,baseUrl:x},y=lt(t,r);if(y&&(c.headers={...c.headers,"Accept-Language":y}),p!==void 0){if(Y(p))p.offset!==void 0&&(c.offset=p.offset),p.limit!==void 0&&(c.limit=p.limit),p.cursor!==void 0&&(c.params={...c.params,cursor:p.cursor});else if(typeof p=="number"){const f=e.pageSize||$||20;c.offset=(p-1)*f,c.limit=f}}if(L!==void 0&&(c.params={...c.params,cursor:L}),S==="insert"||S==="update"||S==="upsert"){let f;if(q===!0||e.on==="submit")f=tt(t);else if(z(q)){const b=tt(t);f={};for(const gt of q)f[gt]=b[gt]}else t.state?.parse?f=t.state.parse():Y(t.state)&&(f={...t.state});T&&(f=T(f,t,t.state)),c.data=f}if(S==="rpc"){let f=it;if(e.on==="submit"){const b=tt(t);f=e.transformParams?e.transformParams(b,t,t.state):b}c.params=f}if(S==="subscribe"){const f=h.subscribe({from:g,params:it,on:e.subscribeOn},(b,gt,Vt)=>{n()&&(I(t,b,A),D(t,"onFetchComplete",b),P(e,t,"onFetchComplete",b))});return n()?(o.__unsubscribe=f,{data:null,error:null,subscribed:!0}):(u(f)&&f(),{data:null,error:null,subscribed:!0})}return d(c)},Mt);_&&j.set(_,yt);try{const d=await yt;if(!n()||d?.subscribed)return;const{data:c,error:y}=d||{};if(y){_&&X(_,null,y),k(t,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!1,error:y,status:"error",fetchStatus:"idle"}),D(t,"onFetchError",y),P(e,t,"onFetchError",y),M&&M({phase:"error",mode:"query",from:g,method:S,cacheKey:_,error:y.message||y,durationMs:(typeof performance<"u"?performance.now():Date.now())-_t});return}if(c!==void 0){if((S==="select"||S==="rpc")&&_){const b=X(_,c,null);b.gcTime=at?.gcTime||3e5}let f=c;if(ot&&z(c)&&(o.__pages||(o.__pages=[]),s.direction==="previous"?o.__pages.unshift(c):o.__pages.push(c),f=o.__pages.flat(),K&&(o.__nextPageParam=K(c,o.__pages),o.__hasNextPage=o.__nextPageParam!=null),st&&(o.__prevPageParam=st(c,o.__pages),o.__hasPreviousPage=o.__prevPageParam!=null)),u(m)&&(f=m(f,t,t.state)),T&&(f=T(f,t,t.state)),!n())return;(!O||f!==void 0)&&I(t,f,A),k(t,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!0,error:null,status:"success",fetchStatus:"idle"}),D(t,"onFetchComplete",f),P(e,t,"onFetchComplete",f),M&&M({phase:"success",mode:"query",ok:!0,from:g,method:S,cacheKey:_,durationMs:(typeof performance<"u"?performance.now():Date.now())-_t})}}catch(d){if(!n())return;k(t,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!1,error:d,status:"error",fetchStatus:"idle"}),D(t,"onFetchError",d),P(e,t,"onFetchError",d),M&&M({phase:"error",mode:"query",from:g,method:S,cacheKey:_,error:d.message||String(d),durationMs:(typeof performance<"u"?performance.now():Date.now())-_t})}finally{_&&j.get(_)===yt&&j.delete(_)}},Kt=(e,t,r)=>{const s=e.on,i=t.__ref;i.__fetchListeners||(i.__fetchListeners=[]);const o=e.__runner||R;if(s==="submit"){const a=n=>{n.preventDefault(),o(e,t,r)},l=t.node;l&&(l.addEventListener("submit",a),i.__fetchListeners.push(()=>l.removeEventListener("submit",a)))}else if(s==="click"){const a=()=>o(e,t,r),l=t.node;l&&(l.addEventListener("click",a),i.__fetchListeners.push(()=>l.removeEventListener("click",a)))}else s==="stateChange"&&(i.__fetchOnStateChange=()=>o(e,t,r))},Yt=(e,t,r)=>{const s=t.__ref;s.__fetchCleanups||(s.__fetchCleanups=[]),Wt();const i=e.refetchInterval;if(i){const o=typeof i=="number"?i:H(i);if(o>0){const a=setInterval(()=>{(e.refetchIntervalInBackground||typeof document>"u"||document.visibilityState==="visible")&&R(e,t,r,{force:!0})},o);s.__fetchCleanups.push(()=>clearInterval(a))}}if(e.refetchOnWindowFocus!==!1){const o=()=>{const a=lt(t,r),l=vt(t,r),n=Gt(e,a,l),h=V(n),g=wt(e.cache);(!h||h.stale||Date.now()-h.time>(g?.staleTime||0))&&R(e,t,r,{force:!0})};G.focus.add(o),s.__fetchCleanups.push(()=>G.focus.delete(o))}if(e.refetchOnReconnect!==!1){const o=()=>R(e,t,r,{force:!0});G.online.add(o),s.__fetchCleanups.push(()=>G.online.delete(o))}},Bt=(e,t,r)=>{if(!t.optimistic)return null;const s=e.__ref,i=t.as,o=e.state?.parse?e.state.parse():Y(e.state)?{...e.state}:e.state;s.__optimisticSnapshot=o;const a=u(t.optimistic)?t.optimistic(r,o,e):t.optimistic;return a!==void 0&&I(e,a,i),o},Ft=(e,t)=>{const r=e.__ref,s=r.__optimisticSnapshot;s!==void 0&&(I(e,s,t.as),delete r.__optimisticSnapshot)},Jt=async(e,t,r)=>{const s=r?.fetch;if(!s)return;const i=await Tt(s,r);if(!i)return;const o=t.__ref,{method:a,from:l,fields:n,transform:h,as:g,on:S,auth:et,headers:dt,baseUrl:rt,invalidates:T,optimistic:ht,onMutate:Q,onSuccess:q,onError:A,onSettled:$}=e;let w;if(n===!0||S==="submit")w=tt(t);else if(z(n)){const p=tt(t);w={};for(const L of n)w[L]=p[L]}else t.state?.parse?w=t.state.parse():Y(t.state)&&(w={...t.state});h&&(w=h(w,t,t.state)),u(Q)&&Q(w,t,t.state);const W=ht?Bt(t,e,w):null;o.__fetching=!0,k(t,{isFetching:!0,isLoading:!1,isStale:!1,isSuccess:!1,error:null,status:"pending",fetchStatus:"fetching"}),D(t,"onFetchStart"),P(e,t,"onFetchStart");const C=r?.analyze?.emitNetwork,x=C?typeof performance<"u"?performance.now():Date.now():0;C&&C({phase:"start",mode:"mutation",from:l,method:a});try{if(et!==!1&&i.auth!==!1&&i.getSession){const m=await i.getSession();if(et===!0&&!m){W!==void 0&&Ft(t,e);const O={message:"Not authenticated"};D(t,"onFetchError",O),P(e,t,"onFetchError",O);return}}const p=i[a];if(!u(p))return;const L={from:l,data:w,headers:dt,baseUrl:rt};e.params&&(L.params=kt(e.params,t,r));const K=lt(t,r);K&&(L.headers={...L.headers,"Accept-Language":K});const st=Ct(e),ot=await Pt(()=>p(L),st),{data:F,error:E}=ot||{};if(E){W!==void 0&&Ft(t,e),k(t,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!1,error:E,status:"error",fetchStatus:"idle"}),D(t,"onFetchError",E),u(A)&&A(E,w,t),u($)&&$(null,E,w,t),C&&C({phase:"error",mode:"mutation",from:l,method:a,error:E.message||String(E),durationMs:(typeof performance<"u"?performance.now():Date.now())-x});return}if(delete o.__optimisticSnapshot,F!==void 0){const m=g?{[g]:F}:F;t.state?.update&&t.state.update(m,{preventFetch:!0})}if(k(t,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!0,error:null,status:"success",fetchStatus:"idle"}),D(t,"onFetchComplete",F),P(e,t,"onFetchComplete",F),u(q)&&q(F,w,t),u($)&&$(F,null,w,t),C&&C({phase:"success",mode:"mutation",ok:!0,from:l,method:a,durationMs:(typeof performance<"u"?performance.now():Date.now())-x}),T){const m=z(T)?T:[T];for(const O of m)if(O===!0||O==="*")for(const[U]of v)U.startsWith(l+":")&&Z(U);else Z(O)}}catch(p){W!==void 0&&Ft(t,e),k(t,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!1,error:p,status:"error",fetchStatus:"idle"}),D(t,"onFetchError",p),P(e,t,"onFetchError",p),u(A)&&A(p,w,t),u($)&&$(null,p,w,t),C&&C({phase:"error",mode:"mutation",from:l,method:a,error:p.message||String(p),durationMs:(typeof performance<"u"?performance.now():Date.now())-x})}finally{o.__fetching=!1}},$t=(e,t,r,s)=>{if(!e||!s?.fetch)return;const o=Et(e,t);if(!o)return;const a=z(o)?o.map(n=>Lt(Et(n,t),t)).filter(Boolean):[Lt(o,t)].filter(Boolean);for(const n of a){const h=n.method==="insert"||n.method==="update"||n.method==="upsert"||n.method==="delete",g=h?Jt:R;n.on==="create"?g(n,t,s):Promise.resolve().then(()=>{Kt({...n,__runner:g},t,s)}),!h&&n.on==="create"&&(n.refetchInterval||n.refetchOnWindowFocus!==!1||n.refetchOnReconnect!==!1)&&Yt(n,t,s)}const l=t.__ref;l.refetch=n=>{for(const h of a)R(h,t,s,{force:!0,...n})},l.fetchNextPage=()=>{const n=a[0];if(!n||!n.infinite)return;const h=l.__nextPageParam;if(h==null)return;const g={...n,cursor:h};R(g,t,s,{direction:"next",force:!0})},l.fetchPreviousPage=()=>{const n=a[0];if(!n||!n.infinite)return;const h=l.__prevPageParam;if(h==null)return;const g={...n,cursor:h};R(g,t,s,{direction:"previous",force:!0})}},re={invalidateQueries:e=>{if(!e){Z();return}if(B(e))for(const[t]of v)(t.startsWith(e)||t.includes(e))&&Z(t);else if(z(e)){const t=e.join(":");for(const[r]of v)r.includes(t)&&Z(r)}},removeQueries:e=>{if(!e){ct();return}if(B(e))for(const[t]of v)(t.startsWith(e)||t.includes(e))&&ct(t)},getQueryData:e=>V(e)?.data??void 0,setQueryData:(e,t)=>{const r=V(e),s=u(t)?t(r?.data):t;X(e,s,null)},prefetchQuery:async(e,t)=>{const r=t?.fetch;if(!r)return;const s=await Tt(r,t);if(!s)return;const i=e.cache?.key||`${e.from}:${e.method||"select"}:${JSON.stringify(e.params||"")}`,o=s[e.method||"select"];if(!u(o))return;const a=await o({from:e.from,params:e.params,limit:e.limit,offset:e.offset,order:e.order,single:e.single});if(a?.data!==void 0&&!a?.error){const l=X(i,a.data,null);l.gcTime=wt(e.cache)?.gcTime||3e5}return a},getCache:()=>v,clear:()=>ct(),dropNonLang:e=>{if(!e)return;const t=`:${e}`;for(const[r]of v)r.match(/:([a-z]{2,3})$/i)&&(r.endsWith(t)||ct(r))}},se={name:"fetch",create(e){const t=e.fetch;t&&(e.parent||j.clear(),$t(t,e,e.state,e.context))}};var oe=$t;export{te as createAdapter,oe as default,$t as executeFetch,se as fetchPlugin,mt as initAdapterAuth,H as parseDuration,re as queryClient,Zt as registerAdapter,jt as resolveDb};
|
package/index.js
CHANGED
|
@@ -568,6 +568,19 @@ const runFetch = async (config, element, context, opts = {}) => {
|
|
|
568
568
|
// if it's gone, bail before anything else touches `element`.
|
|
569
569
|
if (!element || !element.__ref) return
|
|
570
570
|
|
|
571
|
+
// Cache keys separate tenants, but they do not own an asynchronous reply.
|
|
572
|
+
// Capture before adapter/auth awaits and keep a generation per observed
|
|
573
|
+
// scope. A -> B -> A must not revive A's older request. Queries started in
|
|
574
|
+
// the same scope share this generation, so unrelated reads stay concurrent.
|
|
575
|
+
const ref = element.__ref
|
|
576
|
+
const scope = resolveScope(element, context)
|
|
577
|
+
if (!ref.__fetchScopeOwner || ref.__fetchScopeOwner.scope !== scope) {
|
|
578
|
+
ref.__fetchScopeOwner = { scope }
|
|
579
|
+
}
|
|
580
|
+
const owner = ref.__fetchScopeOwner
|
|
581
|
+
const isCurrent = () => element.__ref === ref &&
|
|
582
|
+
ref.__fetchScopeOwner === owner && resolveScope(element, context) === scope
|
|
583
|
+
|
|
571
584
|
// enabled check
|
|
572
585
|
if (config.enabled === false) return
|
|
573
586
|
if (isFunction(config.enabled) && !config.enabled(element, element.state)) return
|
|
@@ -580,9 +593,8 @@ const runFetch = async (config, element, context, opts = {}) => {
|
|
|
580
593
|
|
|
581
594
|
// Re-check after the await — a slow adapter-resolve can outlive the
|
|
582
595
|
// element that triggered the fetch.
|
|
583
|
-
if (!
|
|
596
|
+
if (!isCurrent()) return
|
|
584
597
|
|
|
585
|
-
const ref = element.__ref
|
|
586
598
|
const {
|
|
587
599
|
from, method, query, params: rawParams, cache: cacheRaw, transform,
|
|
588
600
|
single, auth, fields, as: stateKey, limit, offset, order,
|
|
@@ -604,7 +616,6 @@ const runFetch = async (config, element, context, opts = {}) => {
|
|
|
604
616
|
const cacheConfig = parseCacheConfig(cacheRaw)
|
|
605
617
|
const retryConfig = resolveRetryConfig(config)
|
|
606
618
|
const lang = resolveLanguage(element, context)
|
|
607
|
-
const scope = resolveScope(element, context)
|
|
608
619
|
|
|
609
620
|
// Build cache key — lang suffix lets queryClient.dropNonLang(keepLang)
|
|
610
621
|
// evict stale-language entries on setLang() without flushing the rest.
|
|
@@ -635,6 +646,7 @@ const runFetch = async (config, element, context, opts = {}) => {
|
|
|
635
646
|
let data = cached.data
|
|
636
647
|
if (isFunction(selectTransform)) data = selectTransform(data, element, element.state)
|
|
637
648
|
if (transform) data = transform(data, element, element.state)
|
|
649
|
+
if (!isCurrent()) return
|
|
638
650
|
updateElementState(element, data, stateKey)
|
|
639
651
|
if (!isStale) {
|
|
640
652
|
setFetchStatus(element, { isFetching: false, isLoading: false, isStale: false, isSuccess: true, error: null, status: 'success', fetchStatus: 'idle' })
|
|
@@ -654,15 +666,18 @@ const runFetch = async (config, element, context, opts = {}) => {
|
|
|
654
666
|
const existing = activeQueries.get(cacheKey)
|
|
655
667
|
try {
|
|
656
668
|
const result = await Promise.race([existing, new Promise((_, r) => setTimeout(() => r('DEDUP_TIMEOUT'), 15000))])
|
|
669
|
+
if (!isCurrent()) return
|
|
657
670
|
if (result?.data !== undefined) {
|
|
658
671
|
let finalData = result.data
|
|
659
672
|
if (isFunction(selectTransform)) finalData = selectTransform(finalData, element, element.state)
|
|
660
673
|
if (transform) finalData = transform(finalData, element, element.state)
|
|
674
|
+
if (!isCurrent()) return
|
|
661
675
|
updateElementState(element, finalData, stateKey)
|
|
662
676
|
triggerCallback(element, 'onFetchComplete', finalData)
|
|
663
677
|
triggerConfigCallback(config, element, 'onFetchComplete', finalData)
|
|
664
678
|
}
|
|
665
679
|
} catch (e) {
|
|
680
|
+
if (!isCurrent()) return
|
|
666
681
|
// Error handled by the original caller
|
|
667
682
|
}
|
|
668
683
|
return
|
|
@@ -687,8 +702,11 @@ const runFetch = async (config, element, context, opts = {}) => {
|
|
|
687
702
|
if (_emitNet) _emitNet({ phase: 'start', mode: 'query', from, method, cacheKey, lang })
|
|
688
703
|
|
|
689
704
|
const doFetch = async () => {
|
|
705
|
+
// withRetry can invoke this again after a scope switch or unmount.
|
|
706
|
+
if (!isCurrent()) return
|
|
690
707
|
if (auth !== false && adapter.auth !== false && adapter.getSession) {
|
|
691
708
|
const session = await adapter.getSession()
|
|
709
|
+
if (!isCurrent()) return
|
|
692
710
|
if (auth === true && !session) {
|
|
693
711
|
const err = { message: 'Not authenticated' }
|
|
694
712
|
setFetchStatus(element, { isFetching: false, isLoading: false, isStale: false, isSuccess: false, error: err, status: 'error', fetchStatus: 'idle' })
|
|
@@ -759,11 +777,16 @@ const runFetch = async (config, element, context, opts = {}) => {
|
|
|
759
777
|
const unsubscribe = adapter.subscribe(
|
|
760
778
|
{ from, params, on: config.subscribeOn },
|
|
761
779
|
(newData, oldData, payload) => {
|
|
780
|
+
if (!isCurrent()) return
|
|
762
781
|
updateElementState(element, newData, stateKey)
|
|
763
782
|
triggerCallback(element, 'onFetchComplete', newData)
|
|
764
783
|
triggerConfigCallback(config, element, 'onFetchComplete', newData)
|
|
765
784
|
}
|
|
766
785
|
)
|
|
786
|
+
if (!isCurrent()) {
|
|
787
|
+
if (isFunction(unsubscribe)) unsubscribe()
|
|
788
|
+
return { data: null, error: null, subscribed: true }
|
|
789
|
+
}
|
|
767
790
|
ref.__unsubscribe = unsubscribe
|
|
768
791
|
return { data: null, error: null, subscribed: true }
|
|
769
792
|
}
|
|
@@ -779,6 +802,7 @@ const runFetch = async (config, element, context, opts = {}) => {
|
|
|
779
802
|
|
|
780
803
|
try {
|
|
781
804
|
const result = await fetchPromise
|
|
805
|
+
if (!isCurrent()) return
|
|
782
806
|
if (result?.subscribed) return
|
|
783
807
|
|
|
784
808
|
const { data, error } = result || {}
|
|
@@ -828,6 +852,7 @@ const runFetch = async (config, element, context, opts = {}) => {
|
|
|
828
852
|
|
|
829
853
|
if (isFunction(selectTransform)) finalData = selectTransform(finalData, element, element.state)
|
|
830
854
|
if (transform) finalData = transform(finalData, element, element.state)
|
|
855
|
+
if (!isCurrent()) return
|
|
831
856
|
|
|
832
857
|
// keepPreviousData — don't clear state while fetching new page
|
|
833
858
|
if (!keepPreviousData || finalData !== undefined) {
|
|
@@ -843,6 +868,7 @@ const runFetch = async (config, element, context, opts = {}) => {
|
|
|
843
868
|
})
|
|
844
869
|
}
|
|
845
870
|
} catch (e) {
|
|
871
|
+
if (!isCurrent()) return
|
|
846
872
|
setFetchStatus(element, { isFetching: false, isLoading: false, isStale: false, isSuccess: false, error: e, status: 'error', fetchStatus: 'idle' })
|
|
847
873
|
triggerCallback(element, 'onFetchError', e)
|
|
848
874
|
triggerConfigCallback(config, element, 'onFetchError', e)
|
|
@@ -852,7 +878,8 @@ const runFetch = async (config, element, context, opts = {}) => {
|
|
|
852
878
|
durationMs: (typeof performance !== 'undefined' ? performance.now() : Date.now()) - __analyzeStart
|
|
853
879
|
})
|
|
854
880
|
} finally {
|
|
855
|
-
|
|
881
|
+
// A forced refetch may have replaced this key while the old request ran.
|
|
882
|
+
if (cacheKey && activeQueries.get(cacheKey) === fetchPromise) activeQueries.delete(cacheKey)
|
|
856
883
|
}
|
|
857
884
|
}
|
|
858
885
|
|