@symbo.ls/fetch 3.14.10 → 3.14.11
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/CHANGELOG.md +8 -2
- package/dist/cjs/index.js +1 -1
- package/dist/esm/index.js +1 -1
- package/index.js +46 -13
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,14 +1,20 @@
|
|
|
1
1
|
# @symbo.ls/fetch
|
|
2
2
|
|
|
3
|
+
## 3.14.11
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- Auto-generated cross-repo patch release.
|
|
8
|
+
|
|
3
9
|
## 3.14.10
|
|
4
10
|
|
|
5
11
|
### Patch Changes
|
|
6
12
|
|
|
7
|
-
- Manual patch bump triggered via workflow_dispatch (scope:
|
|
13
|
+
- Manual patch bump triggered via workflow_dispatch (scope: all).
|
|
8
14
|
No source change behind this bump — released to refresh dist or
|
|
9
15
|
coordinate a cross-package version line.
|
|
10
16
|
- Updated dependencies
|
|
11
|
-
- @symbo.ls/utils@3.14.
|
|
17
|
+
- @symbo.ls/utils@3.14.16
|
|
12
18
|
|
|
13
19
|
## 3.14.9
|
|
14
20
|
|
package/dist/cjs/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var At=Object.create;var st=Object.defineProperty;var kt=Object.getOwnPropertyDescriptor;var Mt=Object.getOwnPropertyNames;var $t=Object.getPrototypeOf,It=Object.prototype.hasOwnProperty;var Nt=(e,t)=>{for(var s in t)st(e,s,{get:t[s],enumerable:!0})},wt=(e,t,s,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Mt(t))!It.call(e,n)&&n!==s&&st(e,n,{get:()=>t[n],enumerable:!(r=kt(t,n))||r.enumerable});return e};var dt=(e,t,s)=>(s=e!=null?At($t(e)):{},wt(t||!e||!e.__esModule?st(s,"default",{value:e,enumerable:!0}):s,e)),Rt=e=>wt(st({},"__esModule",{value:!0}),e);var Vt={};Nt(Vt,{createAdapter:()=>Ot,default:()=>Ht,executeFetch:()=>gt,fetchPlugin:()=>Jt,initAdapterAuth:()=>ot,parseDuration:()=>j,queryClient:()=>Gt,registerAdapter:()=>zt,resolveDb:()=>Et});module.exports=Rt(Vt);var f=require("@symbo.ls/utils");const qt=["select","rpc","insert","update","delete","subscribe"],rt=Symbol.for("@symbo.ls/fetch:BUILTIN_ADAPTERS"),mt=(()=>{if(typeof globalThis<"u"&&globalThis[rt])return globalThis[rt];const e={supabase:()=>import("./adapters/supabase.js"),rest:()=>import("./adapters/rest.js"),local:()=>import("./adapters/local.js")};if(typeof globalThis<"u")try{return Object.defineProperty(globalThis,rt,{value:e,writable:!1,configurable:!1,enumerable:!1}),globalThis[rt]}catch{}return e})(),zt=(e,t)=>{mt[e]=t},Ot=e=>{const t={};for(const s of qt)e[s]&&(t[s]=e[s]);return t.name=e.name||"custom",t},Et=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;const n=mt[r];if(!n)throw new Error(`Unknown db adapter: "${r}". Use registerAdapter() for adapters with optional deps.`);return(await n()).setup(s)},j=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},m=new Map,O=new Map,Y=new Map,Ut=(e,t)=>{if(e.cache?.key)return e.cache.key;const s=Wt(e.params),r=`${e.from}:${e.method}:${JSON.stringify(s||"")}`;return t?`${r}:${t}`:r},G=e=>m.get(e)||null,J=(e,t,s)=>{const r=m.get(e),n={data:t,error:s,time:Date.now(),stale:!1};m.set(e,n);const a=O.get(e);if(a)for(const i of a)(0,f.isFunction)(i)&&i(n);return n},H=e=>{if(e){const t=m.get(e);t&&(t.stale=!0);return}for(const[,t]of m)t.stale=!0},at=e=>{if(e){m.delete(e);return}m.clear()},ee=(e,t)=>(O.has(e)||O.set(e,new Set),O.get(e).add(t),()=>{const s=O.get(e);s&&(s.delete(t),s.size===0&&O.delete(e))}),ht=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:j(e),gcTime:3e5}:{staleTime:j(e.stale||e.staleTime)||6e4,gcTime:j(e.gc||e.gcTime||e.expire)||3e5,key:e.key};let it=null;const xt=()=>{it||(it=setInterval(()=>{const e=Date.now();for(const[t,s]of m){const r=O.get(t);!(r&&r.size>0)&&e-s.time>(s.gcTime||3e5)&&m.delete(t)}},3e4),it.unref&&it.unref())};xt();const bt=3,pt=e=>Math.min(1e3*2**e,3e4),vt=e=>{const t=e.retry;return t===!1?{count:0}:t===!0||t===void 0?{count:bt,delay:pt}:typeof t=="number"?{count:t,delay:pt}:{count:t.count??bt,delay:(0,f.isFunction)(t.delay)?t.delay:typeof t.delay=="number"?()=>t.delay:pt}},Ft=async(e,t)=>{const{count:s,delay:r}=t;let n;for(let a=0;a<=s;a++)try{const i=await e();if(i?.error){if(n=i.error,a<s){const c=(0,f.isFunction)(r)?r(a,n):r;await new Promise(o=>setTimeout(o,c));continue}return i}return i}catch(i){if(n=i,a<s){const c=(0,f.isFunction)(r)?r(a,i):r;await new Promise(o=>setTimeout(o,c));continue}throw i}return{data:null,error:n}},B={focus:new Set,online:new Set};let Tt=!1;const Qt=()=>{if(Tt||typeof window>"u")return;Tt=!0;const e=()=>{for(const s of B.focus)s()},t=()=>{for(const s of B.online)s()};window.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&e()}),window.addEventListener("focus",e),window.addEventListener("online",t)},Dt=(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},Wt=e=>(!e||(0,f.isFunction)(e),e),nt=(e,t)=>{const s=e?.state?.root||t?.state?.root;if(s?.lang)return s.lang},Ct=(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 n in e){const a=e[n];r[n]=(0,f.isFunction)(a)?a(t,t.state):a}}return r},ot=async(e,t)=>{if(!e||e.__authInitialized||(e.__authInitialized=!0,!e.getSession))return;const s=(r,n)=>{const a=t.state?.root;a?.update&&a.update({auth:{user:r,session:n,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,n)=>{s(n?.user||null,n)})},_t=async(e,t)=>{if((0,f.isFunction)(e.select))return e.auth!==!1&&await ot(e,t),e;if(e.__resolved)return e.auth!==!1&&await ot(e.__resolved,t),e.__resolved;if(e.__resolving)return e.__resolving;e.__resolving=Et(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 ot(s,t),s):null},v=(e,t,...s)=>{const r=(0,f.isFunction)(e[t])?e[t]:null;r&&r.call(e,...s,e,e.state,e.context)},E=(e,t,s,...r)=>{const n=e&&(0,f.isFunction)(e[s])?e[s]:null;n&&n.call(t,...r,t,t.state,t.context)},V=e=>{const t={},s=e.node;if(!s)return t;if(s.tagName==="FORM"){const n=new FormData(s);for(const[a,i]of n.entries())t[a]=i;return t}const r=s.querySelectorAll("input, textarea, select");for(let n=0;n<r.length;n++){const a=r[n],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},U=(e,t,s,r={})=>{const n=s&&s.startsWith("~/"),a=n&&e.state?.root||e.state;if(a?.update)if(n){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)},R=async(e,t,s,r={})=>{const n=s?.fetch;if(!n||!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 _t(n,s);if(!a||!t.__ref)return;const i=t.__ref,{from:c,method:o,query:y,params:F,cache:X,transform:T,single:ft,auth:Z,fields:I,as:q,limit:K,offset:tt,order:x,headers:N,baseUrl:_,page:g,cursor:b,getNextPageParam:Q,getPreviousPageParam:S,infinite:L,placeholderData:z,initialData:W,select:P,keepPreviousData:M}=e;let D=(0,f.isString)(P)?P:void 0;if(y&&(0,f.isFunction)(t.getQuery)){const d=t.getQuery(a.name||"paths");d&&(D=d.select||d.length&&d.join(",")||D)}const A=Ct(F,t,s),C=ht(X),et=vt(e),ct=nt(t,s),Lt=ct?`:${ct}`:"",p=C?X?.key||`${c}:${o}:${JSON.stringify(A||"")}${L?":infinite":""}${g?":p"+JSON.stringify(g):""}${Lt}`:null;if(!i.__fetchInitialized&&p&&(i.__fetchInitialized=!0,W!==void 0)){const d=(0,f.isFunction)(W)?W():W;J(p,d,null)}if((o==="select"||o==="rpc")&&p&&C){const d=G(p);if(d&&!d.error){const l=Date.now()-d.time,h=d.stale||l>(C.staleTime||0);let u=d.data;if((0,f.isFunction)(P)&&(u=P(u,t,t.state)),T&&(u=T(u,t,t.state)),U(t,u,q),!h){k(t,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!0,error:null,status:"success",fetchStatus:"idle"});return}}else if(z!==void 0){const l=(0,f.isFunction)(z)?z(t,t.state):z;l!==void 0&&U(t,l,q)}}if(p&&Y.has(p)&&!r.force){const d=Y.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)(P)&&(h=P(h,t,t.state)),T&&(h=T(h,t,t.state)),U(t,h,q),v(t,"onFetchComplete",h),E(e,t,"onFetchComplete",h)}}catch{}return}const Pt=!G(p)?.data;k(t,{isFetching:!0,isLoading:Pt,isStale:!1,isSuccess:!1,error:null,status:"pending",fetchStatus:"fetching"}),v(t,"onFetchStart"),E(e,t,"onFetchStart");const $=s?.analyze?.emitNetwork,ut=$?typeof performance<"u"?performance.now():Date.now():0;$&&$({phase:"start",mode:"query",from:c,method:o,cacheKey:p,lang:ct});const St=Ft(async()=>{if(Z!==!1&&a.auth!==!1&&a.getSession){const u=await a.getSession();if(Z===!0&&!u){const w={message:"Not authenticated"};return k(t,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!1,error:w,status:"error",fetchStatus:"idle"}),v(t,"onFetchError",w),E(e,t,"onFetchError",w),{data:null,error:w}}}const d=a[o];if(!(0,f.isFunction)(d))return{data:null,error:{message:`Method "${o}" not found on adapter`}};const l={from:c,select:D,params:A,single:ft,limit:K,offset:tt,order:x,headers:N,baseUrl:_},h=nt(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(b!==void 0&&(l.params={...l.params,cursor:b}),o==="insert"||o==="update"||o==="upsert"){let u;if(I===!0||e.on==="submit")u=V(t);else if((0,f.isArray)(I)){const w=V(t);u={};for(const lt of I)u[lt]=w[lt]}else t.state?.parse?u=t.state.parse():(0,f.isObject)(t.state)&&(u={...t.state});T&&(u=T(u,t,t.state)),l.data=u}if(o==="rpc"){let u=A;if(e.on==="submit"){const w=V(t);u=e.transformParams?e.transformParams(w,t,t.state):w}l.params=u}if(o==="subscribe"){const u=a.subscribe({from:c,params:A,on:e.subscribeOn},(w,lt,Zt)=>{U(t,w,q),v(t,"onFetchComplete",w),E(e,t,"onFetchComplete",w)});return i.__unsubscribe=u,{data:null,error:null,subscribed:!0}}return d(l)},et);p&&Y.set(p,St);try{const d=await St;if(d?.subscribed)return;const{data:l,error:h}=d||{};if(h){p&&J(p,null,h),k(t,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!1,error:h,status:"error",fetchStatus:"idle"}),v(t,"onFetchError",h),E(e,t,"onFetchError",h),$&&$({phase:"error",mode:"query",from:c,method:o,cacheKey:p,error:h.message||h,durationMs:(typeof performance<"u"?performance.now():Date.now())-ut});return}if(l!==void 0){if((o==="select"||o==="rpc")&&p){const w=J(p,l,null);w.gcTime=C?.gcTime||3e5}let u=l;L&&(0,f.isArray)(l)&&(i.__pages||(i.__pages=[]),r.direction==="previous"?i.__pages.unshift(l):i.__pages.push(l),u=i.__pages.flat(),Q&&(i.__nextPageParam=Q(l,i.__pages),i.__hasNextPage=i.__nextPageParam!=null),S&&(i.__prevPageParam=S(l,i.__pages),i.__hasPreviousPage=i.__prevPageParam!=null)),(0,f.isFunction)(P)&&(u=P(u,t,t.state)),T&&(u=T(u,t,t.state)),(!M||u!==void 0)&&U(t,u,q),k(t,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!0,error:null,status:"success",fetchStatus:"idle"}),v(t,"onFetchComplete",u),E(e,t,"onFetchComplete",u),$&&$({phase:"success",mode:"query",ok:!0,from:c,method:o,cacheKey:p,durationMs:(typeof performance<"u"?performance.now():Date.now())-ut})}}catch(d){k(t,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!1,error:d,status:"error",fetchStatus:"idle"}),v(t,"onFetchError",d),E(e,t,"onFetchError",d),$&&$({phase:"error",mode:"query",from:c,method:o,cacheKey:p,error:d.message||String(d),durationMs:(typeof performance<"u"?performance.now():Date.now())-ut})}finally{p&&Y.delete(p)}},Bt=(e,t,s)=>{const r=e.on,n=t.__ref;n.__fetchListeners||(n.__fetchListeners=[]);const a=e.__runner||R;if(r==="submit"){const i=o=>{o.preventDefault(),a(e,t,s)},c=t.node;c&&(c.addEventListener("submit",i),n.__fetchListeners.push(()=>c.removeEventListener("submit",i)))}else if(r==="click"){const i=()=>a(e,t,s),c=t.node;c&&(c.addEventListener("click",i),n.__fetchListeners.push(()=>c.removeEventListener("click",i)))}else r==="stateChange"&&(n.__fetchOnStateChange=()=>a(e,t,s))},jt=(e,t,s)=>{const r=t.__ref;r.__fetchCleanups||(r.__fetchCleanups=[]),Qt();const n=e.refetchInterval;if(n){const a=typeof n=="number"?n:j(n);if(a>0){const i=setInterval(()=>{(e.refetchIntervalInBackground||typeof document>"u"||document.visibilityState==="visible")&&R(e,t,s,{force:!0})},a);r.__fetchCleanups.push(()=>clearInterval(i))}}if(e.refetchOnWindowFocus!==!1){const a=()=>{const i=nt(t,s),c=Ut(e,i),o=G(c),y=ht(e.cache);(!o||o.stale||Date.now()-o.time>(y?.staleTime||0))&&R(e,t,s,{force:!0})};B.focus.add(a),r.__fetchCleanups.push(()=>B.focus.delete(a))}if(e.refetchOnReconnect!==!1){const a=()=>R(e,t,s,{force:!0});B.online.add(a),r.__fetchCleanups.push(()=>B.online.delete(a))}},Kt=(e,t,s)=>{if(!t.optimistic)return null;const r=e.__ref,n=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&&U(e,i,n),a},yt=(e,t)=>{const s=e.__ref,r=s.__optimisticSnapshot;r!==void 0&&(U(e,r,t.as),delete s.__optimisticSnapshot)},Yt=async(e,t,s)=>{const r=s?.fetch;if(!r)return;const n=await _t(r,s);if(!n)return;const a=t.__ref,{method:i,from:c,fields:o,transform:y,as:F,on:X,auth:T,headers:ft,baseUrl:Z,invalidates:I,optimistic:q,onMutate:K,onSuccess:tt,onError:x,onSettled:N}=e;let _;if(o===!0||X==="submit")_=V(t);else if((0,f.isArray)(o)){const S=V(t);_={};for(const L of o)_[L]=S[L]}else t.state?.parse?_=t.state.parse():(0,f.isObject)(t.state)&&(_={...t.state});y&&(_=y(_,t,t.state)),(0,f.isFunction)(K)&&K(_,t,t.state);const g=q?Kt(t,e,_):null;a.__fetching=!0,k(t,{isFetching:!0,isLoading:!1,isStale:!1,isSuccess:!1,error:null,status:"pending",fetchStatus:"fetching"}),v(t,"onFetchStart"),E(e,t,"onFetchStart");const b=s?.analyze?.emitNetwork,Q=b?typeof performance<"u"?performance.now():Date.now():0;b&&b({phase:"start",mode:"mutation",from:c,method:i});try{if(T!==!1&&n.auth!==!1&&n.getSession){const A=await n.getSession();if(T===!0&&!A){g!==void 0&&yt(t,e);const C={message:"Not authenticated"};v(t,"onFetchError",C),E(e,t,"onFetchError",C);return}}const S=n[i];if(!(0,f.isFunction)(S))return;const L={from:c,data:_,headers:ft,baseUrl:Z};e.params&&(L.params=Ct(e.params,t,s));const z=nt(t,s);z&&(L.headers={...L.headers,"Accept-Language":z});const W=vt(e),P=await Ft(()=>S(L),W),{data:M,error:D}=P||{};if(D){g!==void 0&&yt(t,e),k(t,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!1,error:D,status:"error",fetchStatus:"idle"}),v(t,"onFetchError",D),(0,f.isFunction)(x)&&x(D,_,t),(0,f.isFunction)(N)&&N(null,D,_,t),b&&b({phase:"error",mode:"mutation",from:c,method:i,error:D.message||String(D),durationMs:(typeof performance<"u"?performance.now():Date.now())-Q});return}if(delete a.__optimisticSnapshot,M!==void 0){const A=F?{[F]:M}:M;t.state?.update&&t.state.update(A,{preventFetch:!0})}if(k(t,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!0,error:null,status:"success",fetchStatus:"idle"}),v(t,"onFetchComplete",M),E(e,t,"onFetchComplete",M),(0,f.isFunction)(tt)&&tt(M,_,t),(0,f.isFunction)(N)&&N(M,null,_,t),b&&b({phase:"success",mode:"mutation",ok:!0,from:c,method:i,durationMs:(typeof performance<"u"?performance.now():Date.now())-Q}),I){const A=(0,f.isArray)(I)?I:[I];for(const C of A)if(C===!0||C==="*")for(const[et]of m)et.startsWith(c+":")&&H(et);else H(C)}}catch(S){g!==void 0&&yt(t,e),k(t,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!1,error:S,status:"error",fetchStatus:"idle"}),v(t,"onFetchError",S),E(e,t,"onFetchError",S),(0,f.isFunction)(x)&&x(S,_,t),(0,f.isFunction)(N)&&N(null,S,_,t),b&&b({phase:"error",mode:"mutation",from:c,method:i,error:S.message||String(S),durationMs:(typeof performance<"u"?performance.now():Date.now())-Q})}finally{a.__fetching=!1}},gt=(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(o=>Dt((0,f.exec)(o,t),t)).filter(Boolean):[Dt(a,t)].filter(Boolean);for(const o of i){const y=o.method==="insert"||o.method==="update"||o.method==="upsert"||o.method==="delete",F=y?Yt:R;o.on==="create"?F(o,t,r):Promise.resolve().then(()=>{Bt({...o,__runner:F},t,r)}),!y&&o.on==="create"&&(o.refetchInterval||o.refetchOnWindowFocus!==!1||o.refetchOnReconnect!==!1)&&jt(o,t,r)}const c=t.__ref;c.refetch=o=>{for(const y of i)R(y,t,r,{force:!0,...o})},c.fetchNextPage=()=>{const o=i[0];if(!o||!o.infinite)return;const y=c.__nextPageParam;if(y==null)return;const F={...o,cursor:y};R(F,t,r,{direction:"next",force:!0})},c.fetchPreviousPage=()=>{const o=i[0];if(!o||!o.infinite)return;const y=c.__prevPageParam;if(y==null)return;const F={...o,cursor:y};R(F,t,r,{direction:"previous",force:!0})}},Gt={invalidateQueries:e=>{if(!e){H();return}if((0,f.isString)(e))for(const[t]of m)(t.startsWith(e)||t.includes(e))&&H(t);else if((0,f.isArray)(e)){const t=e.join(":");for(const[s]of m)s.includes(t)&&H(s)}},removeQueries:e=>{if(!e){at();return}if((0,f.isString)(e))for(const[t]of m)(t.startsWith(e)||t.includes(e))&&at(t)},getQueryData:e=>G(e)?.data??void 0,setQueryData:(e,t)=>{const s=G(e),r=(0,f.isFunction)(t)?t(s?.data):t;J(e,r,null)},prefetchQuery:async(e,t)=>{const s=t?.fetch;if(!s)return;const r=await _t(s,t);if(!r)return;const n=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=J(n,i.data,null);c.gcTime=ht(e.cache)?.gcTime||3e5}return i},getCache:()=>m,clear:()=>at(),dropNonLang:e=>{if(!e)return;const t=`:${e}`;for(const[s]of m)s.match(/:([a-z]{2,3})$/i)&&(s.endsWith(t)||at(s))}},Jt={name:"fetch",create(e){const t=e.fetch;t&&(e.parent||Y.clear(),gt(t,e,e.state,e.context))}};var Ht=gt;
|
|
1
|
+
"use strict";var At=Object.create;var st=Object.defineProperty;var kt=Object.getOwnPropertyDescriptor;var Mt=Object.getOwnPropertyNames;var $t=Object.getPrototypeOf,Rt=Object.prototype.hasOwnProperty;var It=(e,t)=>{for(var s in t)st(e,s,{get:t[s],enumerable:!0})},wt=(e,t,s,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Mt(t))!Rt.call(e,n)&&n!==s&&st(e,n,{get:()=>t[n],enumerable:!(r=kt(t,n))||r.enumerable});return e};var dt=(e,t,s)=>(s=e!=null?At($t(e)):{},wt(t||!e||!e.__esModule?st(s,"default",{value:e,enumerable:!0}):s,e)),Nt=e=>wt(st({},"__esModule",{value:!0}),e);var Xt={};It(Xt,{createAdapter:()=>Ut,default:()=>Vt,executeFetch:()=>gt,fetchPlugin:()=>Ht,initAdapterAuth:()=>ot,parseDuration:()=>K,queryClient:()=>Jt,registerAdapter:()=>zt,resolveDb:()=>Et});module.exports=Nt(Xt);var f=require("@symbo.ls/utils");const qt=["select","rpc","insert","update","delete","subscribe"],Ot={supabase:()=>import("./adapters/supabase.js"),rest:()=>import("./adapters/rest.js"),local:()=>import("./adapters/local.js")},rt=Symbol.for("@symbo.ls/fetch:CUSTOM_ADAPTERS"),bt=(()=>{if(typeof globalThis<"u"&&globalThis[rt])return globalThis[rt];const e={};if(typeof globalThis<"u")try{return Object.defineProperty(globalThis,rt,{value:e,writable:!1,configurable:!1,enumerable:!1}),globalThis[rt]}catch{}return e})(),zt=(e,t)=>{bt[e]=t},Ut=e=>{const t={};for(const s of qt)e[s]&&(t[s]=e[s]);return t.name=e.name||"custom",t},Et=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;const n=bt[r]||Ot[r];if(!n)throw new Error(`Unknown db adapter: "${r}". Use registerAdapter() for adapters with optional deps.`);const a=await n();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)},K=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,z=new Map,B=new Map,xt=(e,t)=>{if(e.cache?.key)return e.cache.key;const s=Wt(e.params),r=`${e.from}:${e.method}:${JSON.stringify(s||"")}`;return t?`${r}:${t}`:r},G=e=>b.get(e)||null,J=(e,t,s)=>{const r=b.get(e),n={data:t,error:s,time:Date.now(),stale:!1};b.set(e,n);const a=z.get(e);if(a)for(const i of a)(0,f.isFunction)(i)&&i(n);return n},H=e=>{if(e){const t=b.get(e);t&&(t.stale=!0);return}for(const[,t]of b)t.stale=!0},at=e=>{if(e){b.delete(e);return}b.clear()},se=(e,t)=>(z.has(e)||z.set(e,new Set),z.get(e).add(t),()=>{const s=z.get(e);s&&(s.delete(t),s.size===0&&z.delete(e))}),ht=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:K(e),gcTime:3e5}:{staleTime:K(e.stale||e.staleTime)||6e4,gcTime:K(e.gc||e.gcTime||e.expire)||3e5,key:e.key};let it=null;const Qt=()=>{it||(it=setInterval(()=>{const e=Date.now();for(const[t,s]of b){const r=z.get(t);!(r&&r.size>0)&&e-s.time>(s.gcTime||3e5)&&b.delete(t)}},3e4),it.unref&&it.unref())};Qt();const mt=3,pt=e=>Math.min(1e3*2**e,3e4),vt=e=>{const t=e.retry;return t===!1?{count:0}:t===!0||t===void 0?{count:mt,delay:pt}:typeof t=="number"?{count:t,delay:pt}:{count:t.count??mt,delay:(0,f.isFunction)(t.delay)?t.delay:typeof t.delay=="number"?()=>t.delay:pt}},Ft=async(e,t)=>{const{count:s,delay:r}=t;let n;for(let a=0;a<=s;a++)try{const i=await e();if(i?.error){if(n=i.error,a<s){const c=(0,f.isFunction)(r)?r(a,n):r;await new Promise(o=>setTimeout(o,c));continue}return i}return i}catch(i){if(n=i,a<s){const c=(0,f.isFunction)(r)?r(a,i):r;await new Promise(o=>setTimeout(o,c));continue}throw i}return{data:null,error:n}},W={focus:new Set,online:new Set};let Tt=!1;const jt=()=>{if(Tt||typeof window>"u")return;Tt=!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)},Dt=(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},Wt=e=>(!e||(0,f.isFunction)(e),e),nt=(e,t)=>{const s=e?.state?.root||t?.state?.root;if(s?.lang)return s.lang},Ct=(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 n in e){const a=e[n];r[n]=(0,f.isFunction)(a)?a(t,t.state):a}}return r},ot=async(e,t)=>{if(!e||e.__authInitialized||(e.__authInitialized=!0,!e.getSession))return;const s=(r,n)=>{const a=t.state?.root;a?.update&&a.update({auth:{user:r,session:n,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,n)=>{s(n?.user||null,n)})},_t=async(e,t)=>{if((0,f.isFunction)(e.select))return e.auth!==!1&&await ot(e,t),e;if(e.__resolved)return e.auth!==!1&&await ot(e.__resolved,t),e.__resolved;if(e.__resolving)return e.__resolving;e.__resolving=Et(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 ot(s,t),s):null},v=(e,t,...s)=>{const r=(0,f.isFunction)(e[t])?e[t]:null;r&&r.call(e,...s,e,e.state,e.context)},E=(e,t,s,...r)=>{const n=e&&(0,f.isFunction)(e[s])?e[s]:null;n&&n.call(t,...r,t,t.state,t.context)},V=e=>{const t={},s=e.node;if(!s)return t;if(s.tagName==="FORM"){const n=new FormData(s);for(const[a,i]of n.entries())t[a]=i;return t}const r=s.querySelectorAll("input, textarea, select");for(let n=0;n<r.length;n++){const a=r[n],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},U=(e,t,s,r={})=>{const n=s&&s.startsWith("~/"),a=n&&e.state?.root||e.state;if(a?.update)if(n){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)},N=async(e,t,s,r={})=>{const n=s?.fetch;if(!n||!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 _t(n,s);if(!a||!t.__ref)return;const i=t.__ref,{from:c,method:o,query:y,params:F,cache:X,transform:T,single:ft,auth:Z,fields:R,as:q,limit:Y,offset:tt,order:x,headers:I,baseUrl:_,page:g,cursor:m,getNextPageParam:Q,getPreviousPageParam:S,infinite:P,placeholderData:O,initialData:j,select:L,keepPreviousData:M}=e;let D=(0,f.isString)(L)?L:void 0;if(y&&(0,f.isFunction)(t.getQuery)){const d=t.getQuery(a.name||"paths");d&&(D=d.select||d.length&&d.join(",")||D)}const A=Ct(F,t,s),C=ht(X),et=vt(e),ct=nt(t,s),Pt=ct?`:${ct}`:"",p=C?X?.key||`${c}:${o}:${JSON.stringify(A||"")}${P?":infinite":""}${g?":p"+JSON.stringify(g):""}${Pt}`:null;if(!i.__fetchInitialized&&p&&(i.__fetchInitialized=!0,j!==void 0)){const d=(0,f.isFunction)(j)?j():j;J(p,d,null)}if((o==="select"||o==="rpc")&&p&&C){const d=G(p);if(d&&!d.error){const l=Date.now()-d.time,h=d.stale||l>(C.staleTime||0);let u=d.data;if((0,f.isFunction)(L)&&(u=L(u,t,t.state)),T&&(u=T(u,t,t.state)),U(t,u,q),!h){k(t,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!0,error:null,status:"success",fetchStatus:"idle"});return}}else if(O!==void 0){const l=(0,f.isFunction)(O)?O(t,t.state):O;l!==void 0&&U(t,l,q)}}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)(L)&&(h=L(h,t,t.state)),T&&(h=T(h,t,t.state)),U(t,h,q),v(t,"onFetchComplete",h),E(e,t,"onFetchComplete",h)}}catch{}return}const Lt=!G(p)?.data;k(t,{isFetching:!0,isLoading:Lt,isStale:!1,isSuccess:!1,error:null,status:"pending",fetchStatus:"fetching"}),v(t,"onFetchStart"),E(e,t,"onFetchStart");const $=s?.analyze?.emitNetwork,ut=$?typeof performance<"u"?performance.now():Date.now():0;$&&$({phase:"start",mode:"query",from:c,method:o,cacheKey:p,lang:ct});const St=Ft(async()=>{if(Z!==!1&&a.auth!==!1&&a.getSession){const u=await a.getSession();if(Z===!0&&!u){const w={message:"Not authenticated"};return k(t,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!1,error:w,status:"error",fetchStatus:"idle"}),v(t,"onFetchError",w),E(e,t,"onFetchError",w),{data:null,error:w}}}const d=a[o];if(!(0,f.isFunction)(d))return{data:null,error:{message:`Method "${o}" not found on adapter`}};const l={from:c,select:D,params:A,single:ft,limit:Y,offset:tt,order:x,headers:I,baseUrl:_},h=nt(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||Y||20;l.offset=(g-1)*u,l.limit=u}}if(m!==void 0&&(l.params={...l.params,cursor:m}),o==="insert"||o==="update"||o==="upsert"){let u;if(R===!0||e.on==="submit")u=V(t);else if((0,f.isArray)(R)){const w=V(t);u={};for(const lt of R)u[lt]=w[lt]}else t.state?.parse?u=t.state.parse():(0,f.isObject)(t.state)&&(u={...t.state});T&&(u=T(u,t,t.state)),l.data=u}if(o==="rpc"){let u=A;if(e.on==="submit"){const w=V(t);u=e.transformParams?e.transformParams(w,t,t.state):w}l.params=u}if(o==="subscribe"){const u=a.subscribe({from:c,params:A,on:e.subscribeOn},(w,lt,te)=>{U(t,w,q),v(t,"onFetchComplete",w),E(e,t,"onFetchComplete",w)});return i.__unsubscribe=u,{data:null,error:null,subscribed:!0}}return d(l)},et);p&&B.set(p,St);try{const d=await St;if(d?.subscribed)return;const{data:l,error:h}=d||{};if(h){p&&J(p,null,h),k(t,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!1,error:h,status:"error",fetchStatus:"idle"}),v(t,"onFetchError",h),E(e,t,"onFetchError",h),$&&$({phase:"error",mode:"query",from:c,method:o,cacheKey:p,error:h.message||h,durationMs:(typeof performance<"u"?performance.now():Date.now())-ut});return}if(l!==void 0){if((o==="select"||o==="rpc")&&p){const w=J(p,l,null);w.gcTime=C?.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(),Q&&(i.__nextPageParam=Q(l,i.__pages),i.__hasNextPage=i.__nextPageParam!=null),S&&(i.__prevPageParam=S(l,i.__pages),i.__hasPreviousPage=i.__prevPageParam!=null)),(0,f.isFunction)(L)&&(u=L(u,t,t.state)),T&&(u=T(u,t,t.state)),(!M||u!==void 0)&&U(t,u,q),k(t,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!0,error:null,status:"success",fetchStatus:"idle"}),v(t,"onFetchComplete",u),E(e,t,"onFetchComplete",u),$&&$({phase:"success",mode:"query",ok:!0,from:c,method:o,cacheKey:p,durationMs:(typeof performance<"u"?performance.now():Date.now())-ut})}}catch(d){k(t,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!1,error:d,status:"error",fetchStatus:"idle"}),v(t,"onFetchError",d),E(e,t,"onFetchError",d),$&&$({phase:"error",mode:"query",from:c,method:o,cacheKey:p,error:d.message||String(d),durationMs:(typeof performance<"u"?performance.now():Date.now())-ut})}finally{p&&B.delete(p)}},Kt=(e,t,s)=>{const r=e.on,n=t.__ref;n.__fetchListeners||(n.__fetchListeners=[]);const a=e.__runner||N;if(r==="submit"){const i=o=>{o.preventDefault(),a(e,t,s)},c=t.node;c&&(c.addEventListener("submit",i),n.__fetchListeners.push(()=>c.removeEventListener("submit",i)))}else if(r==="click"){const i=()=>a(e,t,s),c=t.node;c&&(c.addEventListener("click",i),n.__fetchListeners.push(()=>c.removeEventListener("click",i)))}else r==="stateChange"&&(n.__fetchOnStateChange=()=>a(e,t,s))},Yt=(e,t,s)=>{const r=t.__ref;r.__fetchCleanups||(r.__fetchCleanups=[]),jt();const n=e.refetchInterval;if(n){const a=typeof n=="number"?n:K(n);if(a>0){const i=setInterval(()=>{(e.refetchIntervalInBackground||typeof document>"u"||document.visibilityState==="visible")&&N(e,t,s,{force:!0})},a);r.__fetchCleanups.push(()=>clearInterval(i))}}if(e.refetchOnWindowFocus!==!1){const a=()=>{const i=nt(t,s),c=xt(e,i),o=G(c),y=ht(e.cache);(!o||o.stale||Date.now()-o.time>(y?.staleTime||0))&&N(e,t,s,{force:!0})};W.focus.add(a),r.__fetchCleanups.push(()=>W.focus.delete(a))}if(e.refetchOnReconnect!==!1){const a=()=>N(e,t,s,{force:!0});W.online.add(a),r.__fetchCleanups.push(()=>W.online.delete(a))}},Bt=(e,t,s)=>{if(!t.optimistic)return null;const r=e.__ref,n=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&&U(e,i,n),a},yt=(e,t)=>{const s=e.__ref,r=s.__optimisticSnapshot;r!==void 0&&(U(e,r,t.as),delete s.__optimisticSnapshot)},Gt=async(e,t,s)=>{const r=s?.fetch;if(!r)return;const n=await _t(r,s);if(!n)return;const a=t.__ref,{method:i,from:c,fields:o,transform:y,as:F,on:X,auth:T,headers:ft,baseUrl:Z,invalidates:R,optimistic:q,onMutate:Y,onSuccess:tt,onError:x,onSettled:I}=e;let _;if(o===!0||X==="submit")_=V(t);else if((0,f.isArray)(o)){const S=V(t);_={};for(const P of o)_[P]=S[P]}else t.state?.parse?_=t.state.parse():(0,f.isObject)(t.state)&&(_={...t.state});y&&(_=y(_,t,t.state)),(0,f.isFunction)(Y)&&Y(_,t,t.state);const g=q?Bt(t,e,_):null;a.__fetching=!0,k(t,{isFetching:!0,isLoading:!1,isStale:!1,isSuccess:!1,error:null,status:"pending",fetchStatus:"fetching"}),v(t,"onFetchStart"),E(e,t,"onFetchStart");const m=s?.analyze?.emitNetwork,Q=m?typeof performance<"u"?performance.now():Date.now():0;m&&m({phase:"start",mode:"mutation",from:c,method:i});try{if(T!==!1&&n.auth!==!1&&n.getSession){const A=await n.getSession();if(T===!0&&!A){g!==void 0&&yt(t,e);const C={message:"Not authenticated"};v(t,"onFetchError",C),E(e,t,"onFetchError",C);return}}const S=n[i];if(!(0,f.isFunction)(S))return;const P={from:c,data:_,headers:ft,baseUrl:Z};e.params&&(P.params=Ct(e.params,t,s));const O=nt(t,s);O&&(P.headers={...P.headers,"Accept-Language":O});const j=vt(e),L=await Ft(()=>S(P),j),{data:M,error:D}=L||{};if(D){g!==void 0&&yt(t,e),k(t,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!1,error:D,status:"error",fetchStatus:"idle"}),v(t,"onFetchError",D),(0,f.isFunction)(x)&&x(D,_,t),(0,f.isFunction)(I)&&I(null,D,_,t),m&&m({phase:"error",mode:"mutation",from:c,method:i,error:D.message||String(D),durationMs:(typeof performance<"u"?performance.now():Date.now())-Q});return}if(delete a.__optimisticSnapshot,M!==void 0){const A=F?{[F]:M}:M;t.state?.update&&t.state.update(A,{preventFetch:!0})}if(k(t,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!0,error:null,status:"success",fetchStatus:"idle"}),v(t,"onFetchComplete",M),E(e,t,"onFetchComplete",M),(0,f.isFunction)(tt)&&tt(M,_,t),(0,f.isFunction)(I)&&I(M,null,_,t),m&&m({phase:"success",mode:"mutation",ok:!0,from:c,method:i,durationMs:(typeof performance<"u"?performance.now():Date.now())-Q}),R){const A=(0,f.isArray)(R)?R:[R];for(const C of A)if(C===!0||C==="*")for(const[et]of b)et.startsWith(c+":")&&H(et);else H(C)}}catch(S){g!==void 0&&yt(t,e),k(t,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!1,error:S,status:"error",fetchStatus:"idle"}),v(t,"onFetchError",S),E(e,t,"onFetchError",S),(0,f.isFunction)(x)&&x(S,_,t),(0,f.isFunction)(I)&&I(null,S,_,t),m&&m({phase:"error",mode:"mutation",from:c,method:i,error:S.message||String(S),durationMs:(typeof performance<"u"?performance.now():Date.now())-Q})}finally{a.__fetching=!1}},gt=(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(o=>Dt((0,f.exec)(o,t),t)).filter(Boolean):[Dt(a,t)].filter(Boolean);for(const o of i){const y=o.method==="insert"||o.method==="update"||o.method==="upsert"||o.method==="delete",F=y?Gt:N;o.on==="create"?F(o,t,r):Promise.resolve().then(()=>{Kt({...o,__runner:F},t,r)}),!y&&o.on==="create"&&(o.refetchInterval||o.refetchOnWindowFocus!==!1||o.refetchOnReconnect!==!1)&&Yt(o,t,r)}const c=t.__ref;c.refetch=o=>{for(const y of i)N(y,t,r,{force:!0,...o})},c.fetchNextPage=()=>{const o=i[0];if(!o||!o.infinite)return;const y=c.__nextPageParam;if(y==null)return;const F={...o,cursor:y};N(F,t,r,{direction:"next",force:!0})},c.fetchPreviousPage=()=>{const o=i[0];if(!o||!o.infinite)return;const y=c.__prevPageParam;if(y==null)return;const F={...o,cursor:y};N(F,t,r,{direction:"previous",force:!0})}},Jt={invalidateQueries:e=>{if(!e){H();return}if((0,f.isString)(e))for(const[t]of b)(t.startsWith(e)||t.includes(e))&&H(t);else if((0,f.isArray)(e)){const t=e.join(":");for(const[s]of b)s.includes(t)&&H(s)}},removeQueries:e=>{if(!e){at();return}if((0,f.isString)(e))for(const[t]of b)(t.startsWith(e)||t.includes(e))&&at(t)},getQueryData:e=>G(e)?.data??void 0,setQueryData:(e,t)=>{const s=G(e),r=(0,f.isFunction)(t)?t(s?.data):t;J(e,r,null)},prefetchQuery:async(e,t)=>{const s=t?.fetch;if(!s)return;const r=await _t(s,t);if(!r)return;const n=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=J(n,i.data,null);c.gcTime=ht(e.cache)?.gcTime||3e5}return i},getCache:()=>b,clear:()=>at(),dropNonLang:e=>{if(!e)return;const t=`:${e}`;for(const[s]of b)s.match(/:([a-z]{2,3})$/i)&&(s.endsWith(t)||at(s))}},Ht={name:"fetch",create(e){const t=e.fetch;t&&(e.parent||B.clear(),gt(t,e,e.state,e.context))}};var Vt=gt;
|
package/dist/esm/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isArray as B,isFunction as l,isObject as Y,isString as G,exec as wt}from"@symbo.ls/utils";const At=["select","rpc","insert","update","delete","subscribe"],it=Symbol.for("@symbo.ls/fetch:BUILTIN_ADAPTERS"),mt=(()=>{if(typeof globalThis<"u"&&globalThis[it])return globalThis[it];const e={supabase:()=>import("./adapters/supabase.js"),rest:()=>import("./adapters/rest.js"),local:()=>import("./adapters/local.js")};if(typeof globalThis<"u")try{return Object.defineProperty(globalThis,it,{value:e,writable:!1,configurable:!1,enumerable:!1}),globalThis[it]}catch{}return e})(),Wt=(e,t)=>{mt[e]=t},Bt=e=>{const t={};for(const s of At)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;const n=mt[r];if(!n)throw new Error(`Unknown db adapter: "${r}". Use registerAdapter() for adapters with optional deps.`);return(await n()).setup(s)},J=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},m=new Map,O=new Map,H=new Map,Mt=(e,t)=>{if(e.cache?.key)return e.cache.key;const s=Nt(e.params),r=`${e.from}:${e.method}:${JSON.stringify(s||"")}`;return t?`${r}:${t}`:r},V=e=>m.get(e)||null,X=(e,t,s)=>{const r=m.get(e),n={data:t,error:s,time:Date.now(),stale:!1};m.set(e,n);const a=O.get(e);if(a)for(const i of a)l(i)&&i(n);return n},Z=e=>{if(e){const t=m.get(e);t&&(t.stale=!0);return}for(const[,t]of m)t.stale=!0},nt=e=>{if(e){m.delete(e);return}m.clear()},jt=(e,t)=>(O.has(e)||O.set(e,new Set),O.get(e).add(t),()=>{const s=O.get(e);s&&(s.delete(t),s.size===0&&O.delete(e))}),ht=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)}:G(e)?{staleTime:J(e),gcTime:3e5}:{staleTime:J(e.stale||e.staleTime)||6e4,gcTime:J(e.gc||e.gcTime||e.expire)||3e5,key:e.key};let ot=null;const $t=()=>{ot||(ot=setInterval(()=>{const e=Date.now();for(const[t,s]of m){const r=O.get(t);!(r&&r.size>0)&&e-s.time>(s.gcTime||3e5)&&m.delete(t)}},3e4),ot.unref&&ot.unref())};$t();const bt=3,pt=e=>Math.min(1e3*2**e,3e4),vt=e=>{const t=e.retry;return t===!1?{count:0}:t===!0||t===void 0?{count:bt,delay:pt}:typeof t=="number"?{count:t,delay:pt}:{count:t.count??bt,delay:l(t.delay)?t.delay:typeof t.delay=="number"?()=>t.delay:pt}},Ft=async(e,t)=>{const{count:s,delay:r}=t;let n;for(let a=0;a<=s;a++)try{const i=await e();if(i?.error){if(n=i.error,a<s){const f=l(r)?r(a,n):r;await new Promise(o=>setTimeout(o,f));continue}return i}return i}catch(i){if(n=i,a<s){const f=l(r)?r(a,i):r;await new Promise(o=>setTimeout(o,f));continue}throw i}return{data:null,error:n}},j={focus:new Set,online:new Set};let Tt=!1;const It=()=>{if(Tt||typeof window>"u")return;Tt=!0;const e=()=>{for(const s of j.focus)s()},t=()=>{for(const s of j.online)s()};window.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&e()}),window.addEventListener("focus",e),window.addEventListener("online",t)},Dt=(e,t)=>{const s=t.__ref;if(e===!0)return{from:s.__state||t.key,method:"select",query:!0,on:"create"};if(G(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},Nt=e=>(!e||l(e),e),ft=(e,t)=>{const s=e?.state?.root||t?.state?.root;if(s?.lang)return s.lang},Ct=(e,t,s)=>{let r;if(!e)r=void 0;else if(l(e))r=e(t,t.state);else{r={};for(const n in e){const a=e[n];r[n]=l(a)?a(t,t.state):a}}return r},_t=async(e,t)=>{if(!e||e.__authInitialized||(e.__authInitialized=!0,!e.getSession))return;const s=(r,n)=>{const a=t.state?.root;a?.update&&a.update({auth:{user:r,session:n,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,n)=>{s(n?.user||null,n)})},yt=async(e,t)=>{if(l(e.select))return e.auth!==!1&&await _t(e,t),e;if(e.__resolved)return e.auth!==!1&&await _t(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 _t(s,t),s):null},v=(e,t,...s)=>{const r=l(e[t])?e[t]:null;r&&r.call(e,...s,e,e.state,e.context)},E=(e,t,s,...r)=>{const n=e&&l(e[s])?e[s]:null;n&&n.call(t,...r,t,t.state,t.context)},tt=e=>{const t={},s=e.node;if(!s)return t;if(s.tagName==="FORM"){const n=new FormData(s);for(const[a,i]of n.entries())t[a]=i;return t}const r=s.querySelectorAll("input, textarea, select");for(let n=0;n<r.length;n++){const a=r[n],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},U=(e,t,s,r={})=>{const n=s&&s.startsWith("~/"),a=n&&e.state?.root||e.state;if(a?.update)if(n){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)},R=async(e,t,s,r={})=>{const n=s?.fetch;if(!n||!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 yt(n,s);if(!a||!t.__ref)return;const i=t.__ref,{from:f,method:o,query:y,params:F,cache:et,transform:T,single:ct,auth:st,fields:I,as:q,limit:K,offset:rt,order:x,headers:N,baseUrl:_,page:g,cursor:b,getNextPageParam:Q,getPreviousPageParam:S,infinite:L,placeholderData:z,initialData:W,select:P,keepPreviousData:M}=e;let D=G(P)?P:void 0;if(y&&l(t.getQuery)){const d=t.getQuery(a.name||"paths");d&&(D=d.select||d.length&&d.join(",")||D)}const A=Ct(F,t,s),C=ht(et),at=vt(e),ut=ft(t,s),Lt=ut?`:${ut}`:"",p=C?et?.key||`${f}:${o}:${JSON.stringify(A||"")}${L?":infinite":""}${g?":p"+JSON.stringify(g):""}${Lt}`:null;if(!i.__fetchInitialized&&p&&(i.__fetchInitialized=!0,W!==void 0)){const d=l(W)?W():W;X(p,d,null)}if((o==="select"||o==="rpc")&&p&&C){const d=V(p);if(d&&!d.error){const u=Date.now()-d.time,h=d.stale||u>(C.staleTime||0);let c=d.data;if(l(P)&&(c=P(c,t,t.state)),T&&(c=T(c,t,t.state)),U(t,c,q),!h){k(t,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!0,error:null,status:"success",fetchStatus:"idle"});return}}else if(z!==void 0){const u=l(z)?z(t,t.state):z;u!==void 0&&U(t,u,q)}}if(p&&H.has(p)&&!r.force){const d=H.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(P)&&(h=P(h,t,t.state)),T&&(h=T(h,t,t.state)),U(t,h,q),v(t,"onFetchComplete",h),E(e,t,"onFetchComplete",h)}}catch{}return}const Pt=!V(p)?.data;k(t,{isFetching:!0,isLoading:Pt,isStale:!1,isSuccess:!1,error:null,status:"pending",fetchStatus:"fetching"}),v(t,"onFetchStart"),E(e,t,"onFetchStart");const $=s?.analyze?.emitNetwork,lt=$?typeof performance<"u"?performance.now():Date.now():0;$&&$({phase:"start",mode:"query",from:f,method:o,cacheKey:p,lang:ut});const St=Ft(async()=>{if(st!==!1&&a.auth!==!1&&a.getSession){const c=await a.getSession();if(st===!0&&!c){const w={message:"Not authenticated"};return k(t,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!1,error:w,status:"error",fetchStatus:"idle"}),v(t,"onFetchError",w),E(e,t,"onFetchError",w),{data:null,error:w}}}const d=a[o];if(!l(d))return{data:null,error:{message:`Method "${o}" not found on adapter`}};const u={from:f,select:D,params:A,single:ct,limit:K,offset:rt,order:x,headers:N,baseUrl:_},h=ft(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(b!==void 0&&(u.params={...u.params,cursor:b}),o==="insert"||o==="update"||o==="upsert"){let c;if(I===!0||e.on==="submit")c=tt(t);else if(B(I)){const w=tt(t);c={};for(const dt of I)c[dt]=w[dt]}else t.state?.parse?c=t.state.parse():Y(t.state)&&(c={...t.state});T&&(c=T(c,t,t.state)),u.data=c}if(o==="rpc"){let c=A;if(e.on==="submit"){const w=tt(t);c=e.transformParams?e.transformParams(w,t,t.state):w}u.params=c}if(o==="subscribe"){const c=a.subscribe({from:f,params:A,on:e.subscribeOn},(w,dt,xt)=>{U(t,w,q),v(t,"onFetchComplete",w),E(e,t,"onFetchComplete",w)});return i.__unsubscribe=c,{data:null,error:null,subscribed:!0}}return d(u)},at);p&&H.set(p,St);try{const d=await St;if(d?.subscribed)return;const{data:u,error:h}=d||{};if(h){p&&X(p,null,h),k(t,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!1,error:h,status:"error",fetchStatus:"idle"}),v(t,"onFetchError",h),E(e,t,"onFetchError",h),$&&$({phase:"error",mode:"query",from:f,method:o,cacheKey:p,error:h.message||h,durationMs:(typeof performance<"u"?performance.now():Date.now())-lt});return}if(u!==void 0){if((o==="select"||o==="rpc")&&p){const w=X(p,u,null);w.gcTime=C?.gcTime||3e5}let c=u;L&&B(u)&&(i.__pages||(i.__pages=[]),r.direction==="previous"?i.__pages.unshift(u):i.__pages.push(u),c=i.__pages.flat(),Q&&(i.__nextPageParam=Q(u,i.__pages),i.__hasNextPage=i.__nextPageParam!=null),S&&(i.__prevPageParam=S(u,i.__pages),i.__hasPreviousPage=i.__prevPageParam!=null)),l(P)&&(c=P(c,t,t.state)),T&&(c=T(c,t,t.state)),(!M||c!==void 0)&&U(t,c,q),k(t,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!0,error:null,status:"success",fetchStatus:"idle"}),v(t,"onFetchComplete",c),E(e,t,"onFetchComplete",c),$&&$({phase:"success",mode:"query",ok:!0,from:f,method:o,cacheKey:p,durationMs:(typeof performance<"u"?performance.now():Date.now())-lt})}}catch(d){k(t,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!1,error:d,status:"error",fetchStatus:"idle"}),v(t,"onFetchError",d),E(e,t,"onFetchError",d),$&&$({phase:"error",mode:"query",from:f,method:o,cacheKey:p,error:d.message||String(d),durationMs:(typeof performance<"u"?performance.now():Date.now())-lt})}finally{p&&H.delete(p)}},Rt=(e,t,s)=>{const r=e.on,n=t.__ref;n.__fetchListeners||(n.__fetchListeners=[]);const a=e.__runner||R;if(r==="submit"){const i=o=>{o.preventDefault(),a(e,t,s)},f=t.node;f&&(f.addEventListener("submit",i),n.__fetchListeners.push(()=>f.removeEventListener("submit",i)))}else if(r==="click"){const i=()=>a(e,t,s),f=t.node;f&&(f.addEventListener("click",i),n.__fetchListeners.push(()=>f.removeEventListener("click",i)))}else r==="stateChange"&&(n.__fetchOnStateChange=()=>a(e,t,s))},qt=(e,t,s)=>{const r=t.__ref;r.__fetchCleanups||(r.__fetchCleanups=[]),It();const n=e.refetchInterval;if(n){const a=typeof n=="number"?n:J(n);if(a>0){const i=setInterval(()=>{(e.refetchIntervalInBackground||typeof document>"u"||document.visibilityState==="visible")&&R(e,t,s,{force:!0})},a);r.__fetchCleanups.push(()=>clearInterval(i))}}if(e.refetchOnWindowFocus!==!1){const a=()=>{const i=ft(t,s),f=Mt(e,i),o=V(f),y=ht(e.cache);(!o||o.stale||Date.now()-o.time>(y?.staleTime||0))&&R(e,t,s,{force:!0})};j.focus.add(a),r.__fetchCleanups.push(()=>j.focus.delete(a))}if(e.refetchOnReconnect!==!1){const a=()=>R(e,t,s,{force:!0});j.online.add(a),r.__fetchCleanups.push(()=>j.online.delete(a))}},zt=(e,t,s)=>{if(!t.optimistic)return null;const r=e.__ref,n=t.as,a=e.state?.parse?e.state.parse():Y(e.state)?{...e.state}:e.state;r.__optimisticSnapshot=a;const i=l(t.optimistic)?t.optimistic(s,a,e):t.optimistic;return i!==void 0&&U(e,i,n),a},gt=(e,t)=>{const s=e.__ref,r=s.__optimisticSnapshot;r!==void 0&&(U(e,r,t.as),delete s.__optimisticSnapshot)},Ot=async(e,t,s)=>{const r=s?.fetch;if(!r)return;const n=await yt(r,s);if(!n)return;const a=t.__ref,{method:i,from:f,fields:o,transform:y,as:F,on:et,auth:T,headers:ct,baseUrl:st,invalidates:I,optimistic:q,onMutate:K,onSuccess:rt,onError:x,onSettled:N}=e;let _;if(o===!0||et==="submit")_=tt(t);else if(B(o)){const S=tt(t);_={};for(const L of o)_[L]=S[L]}else t.state?.parse?_=t.state.parse():Y(t.state)&&(_={...t.state});y&&(_=y(_,t,t.state)),l(K)&&K(_,t,t.state);const g=q?zt(t,e,_):null;a.__fetching=!0,k(t,{isFetching:!0,isLoading:!1,isStale:!1,isSuccess:!1,error:null,status:"pending",fetchStatus:"fetching"}),v(t,"onFetchStart"),E(e,t,"onFetchStart");const b=s?.analyze?.emitNetwork,Q=b?typeof performance<"u"?performance.now():Date.now():0;b&&b({phase:"start",mode:"mutation",from:f,method:i});try{if(T!==!1&&n.auth!==!1&&n.getSession){const A=await n.getSession();if(T===!0&&!A){g!==void 0&>(t,e);const C={message:"Not authenticated"};v(t,"onFetchError",C),E(e,t,"onFetchError",C);return}}const S=n[i];if(!l(S))return;const L={from:f,data:_,headers:ct,baseUrl:st};e.params&&(L.params=Ct(e.params,t,s));const z=ft(t,s);z&&(L.headers={...L.headers,"Accept-Language":z});const W=vt(e),P=await Ft(()=>S(L),W),{data:M,error:D}=P||{};if(D){g!==void 0&>(t,e),k(t,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!1,error:D,status:"error",fetchStatus:"idle"}),v(t,"onFetchError",D),l(x)&&x(D,_,t),l(N)&&N(null,D,_,t),b&&b({phase:"error",mode:"mutation",from:f,method:i,error:D.message||String(D),durationMs:(typeof performance<"u"?performance.now():Date.now())-Q});return}if(delete a.__optimisticSnapshot,M!==void 0){const A=F?{[F]:M}:M;t.state?.update&&t.state.update(A,{preventFetch:!0})}if(k(t,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!0,error:null,status:"success",fetchStatus:"idle"}),v(t,"onFetchComplete",M),E(e,t,"onFetchComplete",M),l(rt)&&rt(M,_,t),l(N)&&N(M,null,_,t),b&&b({phase:"success",mode:"mutation",ok:!0,from:f,method:i,durationMs:(typeof performance<"u"?performance.now():Date.now())-Q}),I){const A=B(I)?I:[I];for(const C of A)if(C===!0||C==="*")for(const[at]of m)at.startsWith(f+":")&&Z(at);else Z(C)}}catch(S){g!==void 0&>(t,e),k(t,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!1,error:S,status:"error",fetchStatus:"idle"}),v(t,"onFetchError",S),E(e,t,"onFetchError",S),l(x)&&x(S,_,t),l(N)&&N(null,S,_,t),b&&b({phase:"error",mode:"mutation",from:f,method:i,error:S.message||String(S),durationMs:(typeof performance<"u"?performance.now():Date.now())-Q})}finally{a.__fetching=!1}},Et=(e,t,s,r)=>{if(!e||!r?.fetch)return;const a=wt(e,t);if(!a)return;const i=B(a)?a.map(o=>Dt(wt(o,t),t)).filter(Boolean):[Dt(a,t)].filter(Boolean);for(const o of i){const y=o.method==="insert"||o.method==="update"||o.method==="upsert"||o.method==="delete",F=y?Ot:R;o.on==="create"?F(o,t,r):Promise.resolve().then(()=>{Rt({...o,__runner:F},t,r)}),!y&&o.on==="create"&&(o.refetchInterval||o.refetchOnWindowFocus!==!1||o.refetchOnReconnect!==!1)&&qt(o,t,r)}const f=t.__ref;f.refetch=o=>{for(const y of i)R(y,t,r,{force:!0,...o})},f.fetchNextPage=()=>{const o=i[0];if(!o||!o.infinite)return;const y=f.__nextPageParam;if(y==null)return;const F={...o,cursor:y};R(F,t,r,{direction:"next",force:!0})},f.fetchPreviousPage=()=>{const o=i[0];if(!o||!o.infinite)return;const y=f.__prevPageParam;if(y==null)return;const F={...o,cursor:y};R(F,t,r,{direction:"previous",force:!0})}},Kt={invalidateQueries:e=>{if(!e){Z();return}if(G(e))for(const[t]of m)(t.startsWith(e)||t.includes(e))&&Z(t);else if(B(e)){const t=e.join(":");for(const[s]of m)s.includes(t)&&Z(s)}},removeQueries:e=>{if(!e){nt();return}if(G(e))for(const[t]of m)(t.startsWith(e)||t.includes(e))&&nt(t)},getQueryData:e=>V(e)?.data??void 0,setQueryData:(e,t)=>{const s=V(e),r=l(t)?t(s?.data):t;X(e,r,null)},prefetchQuery:async(e,t)=>{const s=t?.fetch;if(!s)return;const r=await yt(s,t);if(!r)return;const n=e.cache?.key||`${e.from}:${e.method||"select"}:${JSON.stringify(e.params||"")}`,a=r[e.method||"select"];if(!l(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 f=X(n,i.data,null);f.gcTime=ht(e.cache)?.gcTime||3e5}return i},getCache:()=>m,clear:()=>nt(),dropNonLang:e=>{if(!e)return;const t=`:${e}`;for(const[s]of m)s.match(/:([a-z]{2,3})$/i)&&(s.endsWith(t)||nt(s))}},Yt={name:"fetch",create(e){const t=e.fetch;t&&(e.parent||H.clear(),Et(t,e,e.state,e.context))}};var Gt=Et;export{Bt as createAdapter,Gt as default,Et as executeFetch,Yt as fetchPlugin,_t as initAdapterAuth,J as parseDuration,Kt as queryClient,Wt as registerAdapter,kt as resolveDb};
|
|
1
|
+
import{isArray as W,isFunction as l,isObject as B,isString as G,exec as wt}from"@symbo.ls/utils";const At=["select","rpc","insert","update","delete","subscribe"],kt={supabase:()=>import("./adapters/supabase.js"),rest:()=>import("./adapters/rest.js"),local:()=>import("./adapters/local.js")},it=Symbol.for("@symbo.ls/fetch:CUSTOM_ADAPTERS"),bt=(()=>{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})(),Wt=(e,t)=>{bt[e]=t},Kt=e=>{const t={};for(const s of At)e[s]&&(t[s]=e[s]);return t.name=e.name||"custom",t},Mt=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;const n=bt[r]||kt[r];if(!n)throw new Error(`Unknown db adapter: "${r}". Use registerAdapter() for adapters with optional deps.`);const a=await n();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)},J=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,z=new Map,H=new Map,$t=(e,t)=>{if(e.cache?.key)return e.cache.key;const s=Nt(e.params),r=`${e.from}:${e.method}:${JSON.stringify(s||"")}`;return t?`${r}:${t}`:r},V=e=>b.get(e)||null,X=(e,t,s)=>{const r=b.get(e),n={data:t,error:s,time:Date.now(),stale:!1};b.set(e,n);const a=z.get(e);if(a)for(const i of a)l(i)&&i(n);return n},Z=e=>{if(e){const t=b.get(e);t&&(t.stale=!0);return}for(const[,t]of b)t.stale=!0},nt=e=>{if(e){b.delete(e);return}b.clear()},Yt=(e,t)=>(z.has(e)||z.set(e,new Set),z.get(e).add(t),()=>{const s=z.get(e);s&&(s.delete(t),s.size===0&&z.delete(e))}),ht=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)}:G(e)?{staleTime:J(e),gcTime:3e5}:{staleTime:J(e.stale||e.staleTime)||6e4,gcTime:J(e.gc||e.gcTime||e.expire)||3e5,key:e.key};let ot=null;const Rt=()=>{ot||(ot=setInterval(()=>{const e=Date.now();for(const[t,s]of b){const r=z.get(t);!(r&&r.size>0)&&e-s.time>(s.gcTime||3e5)&&b.delete(t)}},3e4),ot.unref&&ot.unref())};Rt();const mt=3,pt=e=>Math.min(1e3*2**e,3e4),vt=e=>{const t=e.retry;return t===!1?{count:0}:t===!0||t===void 0?{count:mt,delay:pt}:typeof t=="number"?{count:t,delay:pt}:{count:t.count??mt,delay:l(t.delay)?t.delay:typeof t.delay=="number"?()=>t.delay:pt}},Ft=async(e,t)=>{const{count:s,delay:r}=t;let n;for(let a=0;a<=s;a++)try{const i=await e();if(i?.error){if(n=i.error,a<s){const f=l(r)?r(a,n):r;await new Promise(o=>setTimeout(o,f));continue}return i}return i}catch(i){if(n=i,a<s){const f=l(r)?r(a,i):r;await new Promise(o=>setTimeout(o,f));continue}throw i}return{data:null,error:n}},K={focus:new Set,online:new Set};let Tt=!1;const It=()=>{if(Tt||typeof window>"u")return;Tt=!0;const e=()=>{for(const s of K.focus)s()},t=()=>{for(const s of K.online)s()};window.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&e()}),window.addEventListener("focus",e),window.addEventListener("online",t)},Dt=(e,t)=>{const s=t.__ref;if(e===!0)return{from:s.__state||t.key,method:"select",query:!0,on:"create"};if(G(e))return{from:e,method:"select",query:!0,on:"create"};if(B(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},Nt=e=>(!e||l(e),e),ft=(e,t)=>{const s=e?.state?.root||t?.state?.root;if(s?.lang)return s.lang},Ct=(e,t,s)=>{let r;if(!e)r=void 0;else if(l(e))r=e(t,t.state);else{r={};for(const n in e){const a=e[n];r[n]=l(a)?a(t,t.state):a}}return r},_t=async(e,t)=>{if(!e||e.__authInitialized||(e.__authInitialized=!0,!e.getSession))return;const s=(r,n)=>{const a=t.state?.root;a?.update&&a.update({auth:{user:r,session:n,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,n)=>{s(n?.user||null,n)})},yt=async(e,t)=>{if(l(e.select))return e.auth!==!1&&await _t(e,t),e;if(e.__resolved)return e.auth!==!1&&await _t(e.__resolved,t),e.__resolved;if(e.__resolving)return e.__resolving;e.__resolving=Mt(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 _t(s,t),s):null},v=(e,t,...s)=>{const r=l(e[t])?e[t]:null;r&&r.call(e,...s,e,e.state,e.context)},E=(e,t,s,...r)=>{const n=e&&l(e[s])?e[s]:null;n&&n.call(t,...r,t,t.state,t.context)},tt=e=>{const t={},s=e.node;if(!s)return t;if(s.tagName==="FORM"){const n=new FormData(s);for(const[a,i]of n.entries())t[a]=i;return t}const r=s.querySelectorAll("input, textarea, select");for(let n=0;n<r.length;n++){const a=r[n],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},U=(e,t,s,r={})=>{const n=s&&s.startsWith("~/"),a=n&&e.state?.root||e.state;if(a?.update)if(n){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)},N=async(e,t,s,r={})=>{const n=s?.fetch;if(!n||!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 yt(n,s);if(!a||!t.__ref)return;const i=t.__ref,{from:f,method:o,query:y,params:F,cache:et,transform:T,single:ct,auth:st,fields:R,as:q,limit:Y,offset:rt,order:x,headers:I,baseUrl:_,page:g,cursor:m,getNextPageParam:Q,getPreviousPageParam:S,infinite:P,placeholderData:O,initialData:j,select:L,keepPreviousData:M}=e;let D=G(L)?L:void 0;if(y&&l(t.getQuery)){const d=t.getQuery(a.name||"paths");d&&(D=d.select||d.length&&d.join(",")||D)}const A=Ct(F,t,s),C=ht(et),at=vt(e),ut=ft(t,s),Pt=ut?`:${ut}`:"",p=C?et?.key||`${f}:${o}:${JSON.stringify(A||"")}${P?":infinite":""}${g?":p"+JSON.stringify(g):""}${Pt}`:null;if(!i.__fetchInitialized&&p&&(i.__fetchInitialized=!0,j!==void 0)){const d=l(j)?j():j;X(p,d,null)}if((o==="select"||o==="rpc")&&p&&C){const d=V(p);if(d&&!d.error){const u=Date.now()-d.time,h=d.stale||u>(C.staleTime||0);let c=d.data;if(l(L)&&(c=L(c,t,t.state)),T&&(c=T(c,t,t.state)),U(t,c,q),!h){k(t,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!0,error:null,status:"success",fetchStatus:"idle"});return}}else if(O!==void 0){const u=l(O)?O(t,t.state):O;u!==void 0&&U(t,u,q)}}if(p&&H.has(p)&&!r.force){const d=H.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(L)&&(h=L(h,t,t.state)),T&&(h=T(h,t,t.state)),U(t,h,q),v(t,"onFetchComplete",h),E(e,t,"onFetchComplete",h)}}catch{}return}const Lt=!V(p)?.data;k(t,{isFetching:!0,isLoading:Lt,isStale:!1,isSuccess:!1,error:null,status:"pending",fetchStatus:"fetching"}),v(t,"onFetchStart"),E(e,t,"onFetchStart");const $=s?.analyze?.emitNetwork,lt=$?typeof performance<"u"?performance.now():Date.now():0;$&&$({phase:"start",mode:"query",from:f,method:o,cacheKey:p,lang:ut});const St=Ft(async()=>{if(st!==!1&&a.auth!==!1&&a.getSession){const c=await a.getSession();if(st===!0&&!c){const w={message:"Not authenticated"};return k(t,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!1,error:w,status:"error",fetchStatus:"idle"}),v(t,"onFetchError",w),E(e,t,"onFetchError",w),{data:null,error:w}}}const d=a[o];if(!l(d))return{data:null,error:{message:`Method "${o}" not found on adapter`}};const u={from:f,select:D,params:A,single:ct,limit:Y,offset:rt,order:x,headers:I,baseUrl:_},h=ft(t,s);if(h&&(u.headers={...u.headers,"Accept-Language":h}),g!==void 0){if(B(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||Y||20;u.offset=(g-1)*c,u.limit=c}}if(m!==void 0&&(u.params={...u.params,cursor:m}),o==="insert"||o==="update"||o==="upsert"){let c;if(R===!0||e.on==="submit")c=tt(t);else if(W(R)){const w=tt(t);c={};for(const dt of R)c[dt]=w[dt]}else t.state?.parse?c=t.state.parse():B(t.state)&&(c={...t.state});T&&(c=T(c,t,t.state)),u.data=c}if(o==="rpc"){let c=A;if(e.on==="submit"){const w=tt(t);c=e.transformParams?e.transformParams(w,t,t.state):w}u.params=c}if(o==="subscribe"){const c=a.subscribe({from:f,params:A,on:e.subscribeOn},(w,dt,Qt)=>{U(t,w,q),v(t,"onFetchComplete",w),E(e,t,"onFetchComplete",w)});return i.__unsubscribe=c,{data:null,error:null,subscribed:!0}}return d(u)},at);p&&H.set(p,St);try{const d=await St;if(d?.subscribed)return;const{data:u,error:h}=d||{};if(h){p&&X(p,null,h),k(t,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!1,error:h,status:"error",fetchStatus:"idle"}),v(t,"onFetchError",h),E(e,t,"onFetchError",h),$&&$({phase:"error",mode:"query",from:f,method:o,cacheKey:p,error:h.message||h,durationMs:(typeof performance<"u"?performance.now():Date.now())-lt});return}if(u!==void 0){if((o==="select"||o==="rpc")&&p){const w=X(p,u,null);w.gcTime=C?.gcTime||3e5}let c=u;P&&W(u)&&(i.__pages||(i.__pages=[]),r.direction==="previous"?i.__pages.unshift(u):i.__pages.push(u),c=i.__pages.flat(),Q&&(i.__nextPageParam=Q(u,i.__pages),i.__hasNextPage=i.__nextPageParam!=null),S&&(i.__prevPageParam=S(u,i.__pages),i.__hasPreviousPage=i.__prevPageParam!=null)),l(L)&&(c=L(c,t,t.state)),T&&(c=T(c,t,t.state)),(!M||c!==void 0)&&U(t,c,q),k(t,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!0,error:null,status:"success",fetchStatus:"idle"}),v(t,"onFetchComplete",c),E(e,t,"onFetchComplete",c),$&&$({phase:"success",mode:"query",ok:!0,from:f,method:o,cacheKey:p,durationMs:(typeof performance<"u"?performance.now():Date.now())-lt})}}catch(d){k(t,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!1,error:d,status:"error",fetchStatus:"idle"}),v(t,"onFetchError",d),E(e,t,"onFetchError",d),$&&$({phase:"error",mode:"query",from:f,method:o,cacheKey:p,error:d.message||String(d),durationMs:(typeof performance<"u"?performance.now():Date.now())-lt})}finally{p&&H.delete(p)}},qt=(e,t,s)=>{const r=e.on,n=t.__ref;n.__fetchListeners||(n.__fetchListeners=[]);const a=e.__runner||N;if(r==="submit"){const i=o=>{o.preventDefault(),a(e,t,s)},f=t.node;f&&(f.addEventListener("submit",i),n.__fetchListeners.push(()=>f.removeEventListener("submit",i)))}else if(r==="click"){const i=()=>a(e,t,s),f=t.node;f&&(f.addEventListener("click",i),n.__fetchListeners.push(()=>f.removeEventListener("click",i)))}else r==="stateChange"&&(n.__fetchOnStateChange=()=>a(e,t,s))},Ot=(e,t,s)=>{const r=t.__ref;r.__fetchCleanups||(r.__fetchCleanups=[]),It();const n=e.refetchInterval;if(n){const a=typeof n=="number"?n:J(n);if(a>0){const i=setInterval(()=>{(e.refetchIntervalInBackground||typeof document>"u"||document.visibilityState==="visible")&&N(e,t,s,{force:!0})},a);r.__fetchCleanups.push(()=>clearInterval(i))}}if(e.refetchOnWindowFocus!==!1){const a=()=>{const i=ft(t,s),f=$t(e,i),o=V(f),y=ht(e.cache);(!o||o.stale||Date.now()-o.time>(y?.staleTime||0))&&N(e,t,s,{force:!0})};K.focus.add(a),r.__fetchCleanups.push(()=>K.focus.delete(a))}if(e.refetchOnReconnect!==!1){const a=()=>N(e,t,s,{force:!0});K.online.add(a),r.__fetchCleanups.push(()=>K.online.delete(a))}},zt=(e,t,s)=>{if(!t.optimistic)return null;const r=e.__ref,n=t.as,a=e.state?.parse?e.state.parse():B(e.state)?{...e.state}:e.state;r.__optimisticSnapshot=a;const i=l(t.optimistic)?t.optimistic(s,a,e):t.optimistic;return i!==void 0&&U(e,i,n),a},gt=(e,t)=>{const s=e.__ref,r=s.__optimisticSnapshot;r!==void 0&&(U(e,r,t.as),delete s.__optimisticSnapshot)},Ut=async(e,t,s)=>{const r=s?.fetch;if(!r)return;const n=await yt(r,s);if(!n)return;const a=t.__ref,{method:i,from:f,fields:o,transform:y,as:F,on:et,auth:T,headers:ct,baseUrl:st,invalidates:R,optimistic:q,onMutate:Y,onSuccess:rt,onError:x,onSettled:I}=e;let _;if(o===!0||et==="submit")_=tt(t);else if(W(o)){const S=tt(t);_={};for(const P of o)_[P]=S[P]}else t.state?.parse?_=t.state.parse():B(t.state)&&(_={...t.state});y&&(_=y(_,t,t.state)),l(Y)&&Y(_,t,t.state);const g=q?zt(t,e,_):null;a.__fetching=!0,k(t,{isFetching:!0,isLoading:!1,isStale:!1,isSuccess:!1,error:null,status:"pending",fetchStatus:"fetching"}),v(t,"onFetchStart"),E(e,t,"onFetchStart");const m=s?.analyze?.emitNetwork,Q=m?typeof performance<"u"?performance.now():Date.now():0;m&&m({phase:"start",mode:"mutation",from:f,method:i});try{if(T!==!1&&n.auth!==!1&&n.getSession){const A=await n.getSession();if(T===!0&&!A){g!==void 0&>(t,e);const C={message:"Not authenticated"};v(t,"onFetchError",C),E(e,t,"onFetchError",C);return}}const S=n[i];if(!l(S))return;const P={from:f,data:_,headers:ct,baseUrl:st};e.params&&(P.params=Ct(e.params,t,s));const O=ft(t,s);O&&(P.headers={...P.headers,"Accept-Language":O});const j=vt(e),L=await Ft(()=>S(P),j),{data:M,error:D}=L||{};if(D){g!==void 0&>(t,e),k(t,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!1,error:D,status:"error",fetchStatus:"idle"}),v(t,"onFetchError",D),l(x)&&x(D,_,t),l(I)&&I(null,D,_,t),m&&m({phase:"error",mode:"mutation",from:f,method:i,error:D.message||String(D),durationMs:(typeof performance<"u"?performance.now():Date.now())-Q});return}if(delete a.__optimisticSnapshot,M!==void 0){const A=F?{[F]:M}:M;t.state?.update&&t.state.update(A,{preventFetch:!0})}if(k(t,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!0,error:null,status:"success",fetchStatus:"idle"}),v(t,"onFetchComplete",M),E(e,t,"onFetchComplete",M),l(rt)&&rt(M,_,t),l(I)&&I(M,null,_,t),m&&m({phase:"success",mode:"mutation",ok:!0,from:f,method:i,durationMs:(typeof performance<"u"?performance.now():Date.now())-Q}),R){const A=W(R)?R:[R];for(const C of A)if(C===!0||C==="*")for(const[at]of b)at.startsWith(f+":")&&Z(at);else Z(C)}}catch(S){g!==void 0&>(t,e),k(t,{isFetching:!1,isLoading:!1,isStale:!1,isSuccess:!1,error:S,status:"error",fetchStatus:"idle"}),v(t,"onFetchError",S),E(e,t,"onFetchError",S),l(x)&&x(S,_,t),l(I)&&I(null,S,_,t),m&&m({phase:"error",mode:"mutation",from:f,method:i,error:S.message||String(S),durationMs:(typeof performance<"u"?performance.now():Date.now())-Q})}finally{a.__fetching=!1}},Et=(e,t,s,r)=>{if(!e||!r?.fetch)return;const a=wt(e,t);if(!a)return;const i=W(a)?a.map(o=>Dt(wt(o,t),t)).filter(Boolean):[Dt(a,t)].filter(Boolean);for(const o of i){const y=o.method==="insert"||o.method==="update"||o.method==="upsert"||o.method==="delete",F=y?Ut:N;o.on==="create"?F(o,t,r):Promise.resolve().then(()=>{qt({...o,__runner:F},t,r)}),!y&&o.on==="create"&&(o.refetchInterval||o.refetchOnWindowFocus!==!1||o.refetchOnReconnect!==!1)&&Ot(o,t,r)}const f=t.__ref;f.refetch=o=>{for(const y of i)N(y,t,r,{force:!0,...o})},f.fetchNextPage=()=>{const o=i[0];if(!o||!o.infinite)return;const y=f.__nextPageParam;if(y==null)return;const F={...o,cursor:y};N(F,t,r,{direction:"next",force:!0})},f.fetchPreviousPage=()=>{const o=i[0];if(!o||!o.infinite)return;const y=f.__prevPageParam;if(y==null)return;const F={...o,cursor:y};N(F,t,r,{direction:"previous",force:!0})}},Bt={invalidateQueries:e=>{if(!e){Z();return}if(G(e))for(const[t]of b)(t.startsWith(e)||t.includes(e))&&Z(t);else if(W(e)){const t=e.join(":");for(const[s]of b)s.includes(t)&&Z(s)}},removeQueries:e=>{if(!e){nt();return}if(G(e))for(const[t]of b)(t.startsWith(e)||t.includes(e))&&nt(t)},getQueryData:e=>V(e)?.data??void 0,setQueryData:(e,t)=>{const s=V(e),r=l(t)?t(s?.data):t;X(e,r,null)},prefetchQuery:async(e,t)=>{const s=t?.fetch;if(!s)return;const r=await yt(s,t);if(!r)return;const n=e.cache?.key||`${e.from}:${e.method||"select"}:${JSON.stringify(e.params||"")}`,a=r[e.method||"select"];if(!l(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 f=X(n,i.data,null);f.gcTime=ht(e.cache)?.gcTime||3e5}return i},getCache:()=>b,clear:()=>nt(),dropNonLang:e=>{if(!e)return;const t=`:${e}`;for(const[s]of b)s.match(/:([a-z]{2,3})$/i)&&(s.endsWith(t)||nt(s))}},Gt={name:"fetch",create(e){const t=e.fetch;t&&(e.parent||H.clear(),Et(t,e,e.state,e.context))}};var Jt=Et;export{Kt as createAdapter,Jt as default,Et as executeFetch,Gt as fetchPlugin,_t as initAdapterAuth,J as parseDuration,Bt as queryClient,Wt as registerAdapter,Mt as resolveDb};
|
package/index.js
CHANGED
|
@@ -19,32 +19,52 @@ const ADAPTER_METHODS = ['select', 'rpc', 'insert', 'update', 'delete', 'subscri
|
|
|
19
19
|
// Publishing the registry on `globalThis` under a `Symbol.for` slot
|
|
20
20
|
// guarantees every module instance shares the same backing object — a
|
|
21
21
|
// `registerAdapter` from any copy is visible to every `resolveDb`.
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
22
|
+
// Built-in adapter loaders MUST stay module-local. Each loader's
|
|
23
|
+
// `import('./adapters/<name>.js')` resolves relative to THE BUNDLE THAT
|
|
24
|
+
// CREATED THE LOADER — share these across copies via globalThis (the
|
|
25
|
+
// pre-fix approach) and the loader closure captured by Copy A is later
|
|
26
|
+
// invoked from Copy B, where Copy A's relative path lands on a missing
|
|
27
|
+
// chunk in Copy A's bundle. Parcel returns an empty module wrapper for
|
|
28
|
+
// the missing chunk, `mod.setup(options)` becomes the wrong function
|
|
29
|
+
// (or undefined), and resolveDb hands back `{}` — every `fetch:`
|
|
30
|
+
// declaration silently dies (SMBLS-FETCH-RESOLVEDB-EMPTY-RESULT-1).
|
|
31
|
+
// Keeping these local is safe because every copy of this file ships
|
|
32
|
+
// its own adapters/ chunks; the imports always resolve in-bundle.
|
|
33
|
+
const BUILTIN_ADAPTERS = {
|
|
34
|
+
supabase: () => import('./adapters/supabase.js'),
|
|
35
|
+
rest: () => import('./adapters/rest.js'),
|
|
36
|
+
local: () => import('./adapters/local.js')
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// Custom adapters registered via registerAdapter() DO need cross-copy
|
|
40
|
+
// visibility — a consumer that imports `@symbo.ls/fetch` from one copy
|
|
41
|
+
// and calls registerAdapter('myAdapter', loader) expects the loader to
|
|
42
|
+
// be reachable when `resolveDb` runs in a different copy. The custom
|
|
43
|
+
// loader closure carries its OWN import path resolution, so the cross-
|
|
44
|
+
// copy hop is safe here (the loader was authored in the caller's
|
|
45
|
+
// realm and resolves its own paths).
|
|
46
|
+
const _CUSTOM_REGISTRY_KEY = Symbol.for('@symbo.ls/fetch:CUSTOM_ADAPTERS')
|
|
47
|
+
const CUSTOM_ADAPTERS = (() => {
|
|
48
|
+
if (typeof globalThis !== 'undefined' && globalThis[_CUSTOM_REGISTRY_KEY]) {
|
|
49
|
+
return globalThis[_CUSTOM_REGISTRY_KEY]
|
|
31
50
|
}
|
|
51
|
+
const fresh = {}
|
|
32
52
|
if (typeof globalThis !== 'undefined') {
|
|
33
53
|
try {
|
|
34
|
-
Object.defineProperty(globalThis,
|
|
54
|
+
Object.defineProperty(globalThis, _CUSTOM_REGISTRY_KEY, {
|
|
35
55
|
value: fresh,
|
|
36
56
|
writable: false,
|
|
37
57
|
configurable: false,
|
|
38
58
|
enumerable: false
|
|
39
59
|
})
|
|
40
|
-
return globalThis[
|
|
60
|
+
return globalThis[_CUSTOM_REGISTRY_KEY]
|
|
41
61
|
} catch (_) { /* sealed globalThis — fall through to module-local */ }
|
|
42
62
|
}
|
|
43
63
|
return fresh
|
|
44
64
|
})()
|
|
45
65
|
|
|
46
66
|
export const registerAdapter = (name, loader) => {
|
|
47
|
-
|
|
67
|
+
CUSTOM_ADAPTERS[name] = loader
|
|
48
68
|
}
|
|
49
69
|
|
|
50
70
|
export const createAdapter = (config) => {
|
|
@@ -64,10 +84,23 @@ export const resolveDb = async (config) => {
|
|
|
64
84
|
const name = typeof adapter === 'string' ? adapter : typeof config === 'string' ? config : null
|
|
65
85
|
if (!name) return null
|
|
66
86
|
|
|
67
|
-
|
|
87
|
+
// Custom registrations win over built-ins — a consumer that
|
|
88
|
+
// registerAdapter('supabase', myCustom) gets to shadow the built-in.
|
|
89
|
+
const loader = CUSTOM_ADAPTERS[name] || BUILTIN_ADAPTERS[name]
|
|
68
90
|
if (!loader) throw new Error(`Unknown db adapter: "${name}". Use registerAdapter() for adapters with optional deps.`)
|
|
69
91
|
|
|
70
92
|
const mod = await loader()
|
|
93
|
+
if (!mod || typeof mod.setup !== 'function') {
|
|
94
|
+
// Defense in depth: if the loader resolved to an empty / wrong
|
|
95
|
+
// module (regression of the old globalThis-bridge bug, or any
|
|
96
|
+
// future bundler quirk), surface it loudly instead of silently
|
|
97
|
+
// returning `{}` and leaving every `fetch:` declaration dead.
|
|
98
|
+
throw new Error(
|
|
99
|
+
`Adapter "${name}" loader returned a module without a setup() function. ` +
|
|
100
|
+
`Got keys: [${Object.keys(mod || {}).join(', ')}]. ` +
|
|
101
|
+
`Likely a bundler chunk-resolution issue.`
|
|
102
|
+
)
|
|
103
|
+
}
|
|
71
104
|
return mod.setup(options)
|
|
72
105
|
}
|
|
73
106
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@symbo.ls/fetch",
|
|
3
|
-
"version": "3.14.
|
|
3
|
+
"version": "3.14.11",
|
|
4
4
|
"license": "CC-BY-NC-4.0",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"module": "./dist/esm/index.js",
|
|
@@ -41,7 +41,7 @@
|
|
|
41
41
|
"adapters"
|
|
42
42
|
],
|
|
43
43
|
"dependencies": {
|
|
44
|
-
"@symbo.ls/utils": "^3.14.
|
|
44
|
+
"@symbo.ls/utils": "^3.14.16"
|
|
45
45
|
},
|
|
46
46
|
"peerDependencies": {
|
|
47
47
|
"@supabase/supabase-js": "^2.0.0"
|