@electric-sql/client 1.5.2 → 1.5.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/index.cjs +760 -271
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/cjs/index.d.cts +2 -2
- package/dist/index.browser.mjs +3 -3
- package/dist/index.browser.mjs.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.legacy-esm.js +760 -271
- package/dist/index.legacy-esm.js.map +1 -1
- package/dist/index.mjs +760 -271
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
- package/src/client.ts +304 -375
- package/src/pause-lock.ts +112 -0
- package/src/shape-stream-state.ts +781 -0
package/dist/cjs/index.d.cts
CHANGED
|
@@ -739,13 +739,13 @@ declare class ShapeStream<T extends Row<unknown> = Row> implements ShapeStreamIn
|
|
|
739
739
|
get mode(): LogMode;
|
|
740
740
|
subscribe(callback: (messages: Message<T>[]) => MaybePromise<void>, onError?: (error: Error) => void): () => void;
|
|
741
741
|
unsubscribeAll(): void;
|
|
742
|
-
/** Unix time at which we last synced. Undefined
|
|
742
|
+
/** Unix time at which we last synced. Undefined until first successful up-to-date. */
|
|
743
743
|
lastSyncedAt(): number | undefined;
|
|
744
744
|
/** Time elapsed since last sync (in ms). Infinity if we did not yet sync. */
|
|
745
745
|
lastSynced(): number;
|
|
746
746
|
/** Indicates if we are connected to the Electric sync service. */
|
|
747
747
|
isConnected(): boolean;
|
|
748
|
-
/** True during initial fetch. False
|
|
748
|
+
/** True during initial fetch. False afterwards. */
|
|
749
749
|
isLoading(): boolean;
|
|
750
750
|
hasStarted(): boolean;
|
|
751
751
|
isPaused(): boolean;
|
package/dist/index.browser.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
var
|
|
2
|
-
`;
|
|
1
|
+
var Fs=Object.defineProperty,Ns=Object.defineProperties;var qs=Object.getOwnPropertyDescriptors;var Je=Object.getOwnPropertySymbols;var rs=Object.prototype.hasOwnProperty,ns=Object.prototype.propertyIsEnumerable;var as=n=>{throw TypeError(n)};var ss=(n,t,e)=>t in n?Fs(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e,E=(n,t)=>{for(var e in t||(t={}))rs.call(t,e)&&ss(n,e,t[e]);if(Je)for(var e of Je(t))ns.call(t,e)&&ss(n,e,t[e]);return n},w=(n,t)=>Ns(n,qs(t));var we=(n,t)=>{var e={};for(var s in n)rs.call(n,s)&&t.indexOf(s)<0&&(e[s]=n[s]);if(n!=null&&Je)for(var s of Je(n))t.indexOf(s)<0&&ns.call(n,s)&&(e[s]=n[s]);return e};var wt=(n,t,e)=>t.has(n)||as("Cannot "+e);var r=(n,t,e)=>(wt(n,t,"read from private field"),e?e.call(n):t.get(n)),p=(n,t,e)=>t.has(n)?as("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(n):t.set(n,e),h=(n,t,e,s)=>(wt(n,t,"write to private field"),s?s.call(n,e):t.set(n,e),e),f=(n,t,e)=>(wt(n,t,"access private method"),e);var re=(n,t,e,s)=>({set _(a){h(n,t,a,e)},get _(){return r(n,t,s)}});var P=class n extends Error{constructor(e,s,a,o,i,l){super(l||`HTTP Error ${e} at ${i}: ${s!=null?s:JSON.stringify(a)}`);this.url=i;this.name="FetchError",this.status=e,this.text=s,this.json=a,this.headers=o}static async fromResponse(e,s){let a=e.status,o=Object.fromEntries([...e.headers.entries()]),i,l,u=e.headers.get("content-type");return e.bodyUsed||(u&&u.includes("application/json")?l=await e.json():i=await e.text()),new n(a,i,l,o,s)}},H=class extends Error{constructor(){super("Fetch with backoff aborted"),this.name="FetchBackoffAbortError"}};var Xe=class extends Error{constructor(){super("Invalid shape options: missing required url parameter"),this.name="MissingShapeUrlError"}},Ze=class extends Error{constructor(){super("Invalid signal option. It must be an instance of AbortSignal."),this.name="InvalidSignalError"}},et=class extends Error{constructor(){super("shapeHandle is required if this isn't an initial fetch (i.e. offset > -1)"),this.name="MissingShapeHandleError"}},tt=class extends Error{constructor(t){super(`Cannot use reserved Electric parameter names in custom params: ${t.join(", ")}`),this.name="ReservedParamError"}},st=class extends Error{constructor(t){super(`Column "${t!=null?t:"unknown"}" does not allow NULL values`),this.name="ParserNullValueError"}};var G=class extends Error{constructor(t,e){let s=`The response for the shape request to ${t} didn't include the following required headers:
|
|
2
|
+
`;e.forEach(a=>{s+=`- ${a}
|
|
3
3
|
`}),s+=`
|
|
4
4
|
This is often due to a proxy not setting CORS correctly so that all Electric headers can be read by the client.`,s+=`
|
|
5
|
-
For more information visit the troubleshooting guide: /docs/guides/troubleshooting/missing-headers`,super(s)}},Oe=class extends Error{constructor(e){super(e),this.name="StaleCacheError"}};var tt=r=>Number(r),Os=r=>r==="true"||r==="t",Ls=r=>BigInt(r),Xt=r=>JSON.parse(r),Ds=r=>r,Hs={int2:tt,int4:tt,int8:Ls,bool:Os,float4:tt,float8:tt,json:Xt,jsonb:Xt};function Is(r,e){let t=0,s=null,i="",o=!1,a=0,h;function u(l,g,S){let R=l.slice(g,S);return R=R==="NULL"?null:R,e?e(R):R}function m(l){let g=[];for(;t<l.length;t++){if(s=l[t],o)s==="\\"?i+=l[++t]:s==='"'?(g.push(e?e(i):i),i="",o=l[t+1]==='"',a=t+2):i+=s;else if(s==='"')o=!0;else if(s==="{")a=++t,g.push(m(l));else if(s==="}"){o=!1,a<t&&g.push(u(l,a,t)),a=t+1;break}else s===","&&h!=="}"&&h!=='"'&&(g.push(u(l,a,t)),a=t+1);h=s}return a<t&&g.push(g.push(u(l,a,t+1))),g}return m(r)[0]}var st=class{constructor(e,t){this.parser=y(y({},Hs),e),this.transformer=t}parse(e,t){return JSON.parse(e,(s,i)=>(s==="value"||s==="old_value")&&typeof i=="object"&&i!==null?this.transformMessageValue(i,t):i)}parseSnapshotData(e,t){return e.map(s=>{let i=s;return i.value&&typeof i.value=="object"&&i.value!==null&&(i.value=this.transformMessageValue(i.value,t)),i.old_value&&typeof i.old_value=="object"&&i.old_value!==null&&(i.old_value=this.transformMessageValue(i.old_value,t)),i})}transformMessageValue(e,t){let s=e;return Object.keys(s).forEach(i=>{s[i]=this.parseRow(i,s[i],t)}),this.transformer?this.transformer(s):s}parseRow(e,t,s){var g;let i=s[e];if(!i)return t;let l=i,{type:o,dims:a}=l,h=Jt(l,["type","dims"]),u=(g=this.parser[o])!=null?g:Ds,m=Zt(u,i,e);return a&&a>0?Zt((R,E)=>Is(R,m),i,e)(t):m(t,h)}};function Zt(r,e,t){var i;let s=!((i=e.not_null)!=null&&i);return o=>{if(o===null){if(!s)throw new et(t!=null?t:"unknown");return null}return r(o,e)}}function Le(r){return`"${r.replace(/"/g,'""')}"`}function yt(r){var h,u,m,l;let e=(u=(h=r.match(/^_+/))==null?void 0:h[0])!=null?u:"",t=r.slice(e.length),s=(l=(m=t.match(/_+$/))==null?void 0:m[0])!=null?l:"",a=(s?t.slice(0,t.length-s.length):t).toLowerCase().replace(/_+([a-z])/g,(g,S)=>S.toUpperCase());return e+a+s}function es(r){return r.replace(/([a-z])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").toLowerCase()}function ts(r){let e={};for(let[t,s]of Object.entries(r))e[s]=t;return{decode:t=>{var s;return(s=r[t])!=null?s:t},encode:t=>{var s;return(s=e[t])!=null?s:t}}}function le(r,e){if(!r||!e)return r!=null?r:"";let t=new Set(["SELECT","FROM","WHERE","AND","OR","NOT","IN","IS","NULL","NULLS","FIRST","LAST","TRUE","FALSE","LIKE","ILIKE","BETWEEN","ASC","DESC","LIMIT","OFFSET","ORDER","BY","GROUP","HAVING","DISTINCT","AS","ON","JOIN","LEFT","RIGHT","INNER","OUTER","CROSS","CASE","WHEN","THEN","ELSE","END","CAST","LOWER","UPPER","COALESCE","NULLIF"]),s=[],i=0;for(;i<r.length;){let h=r[i];if(h==="'"||h==='"'){let u=i,m=h;for(i++;i<r.length;)if(r[i]===m)if(r[i+1]===m)i+=2;else{i++;break}else i++;s.push({start:u,end:i})}else i++}let o=h=>s.some(u=>h>=u.start&&h<u.end),a=new RegExp("(?<![a-zA-Z0-9_])([a-zA-Z_][a-zA-Z0-9_]*)(?![a-zA-Z0-9_])","g");return r.replace(a,(h,u,m)=>o(m)||t.has(h.toUpperCase())||h.startsWith("$")?h:e(h))}function Bs(r){if(r){let e={};for(let t of Object.keys(r))e[t]=yt(t);return ts(e)}return{decode:e=>yt(e),encode:e=>es(e)}}function ue(r){return"key"in r}function rt(r){return!ue(r)}function St(r){return rt(r)&&r.headers.control==="up-to-date"}function ss(r){if(r.headers.control!="up-to-date")return;let e=r.headers.global_last_seen_lsn;return e?`${e}_0`:void 0}function Rt(r,e){let t=BigInt(r),s=BigInt(e.xmin),i=BigInt(e.xmax),o=e.xip_list.map(BigInt);return t<s||t<i&&!o.includes(t)}var rs="electric-cursor",de="electric-handle",nt="electric-offset",bt="electric-schema",ns="electric-up-to-date",_t="columns",it="cursor",De="expired_handle",fe="handle",H="live",pe="offset",is="table",as="where",os="replica",cs="params",hs="experimental_live_sse",xt="live_sse",At="force-disconnect-and-refresh",wt="pause-stream",Tt="system-wake",Pt="log",me="subset__where",He="subset__limit",Ie="subset__offset",ge="subset__order_by",Be="subset__params",Mt="subset__where_expr",vt="subset__order_by_expr",at="cache-buster",Ct=[H,xt,fe,pe,it,De,Pt,me,He,Ie,ge,Be,Mt,vt,at];var Ns=[429],ct={initialDelay:100,maxDelay:6e4,multiplier:1.3,maxRetries:1/0};function Fs(r){if(!r)return 0;let e=Number(r);if(Number.isFinite(e)&&e>0)return e*1e3;let t=Date.parse(r);if(!isNaN(t)){let s=t-Date.now();return Math.max(0,Math.min(s,36e5))}return 0}function ls(r,e=ct){let{initialDelay:t,maxDelay:s,multiplier:i,debug:o=!1,onFailedAttempt:a,maxRetries:h=1/0}=e;return async(...u)=>{var R;let m=u[0],l=u[1],g=t,S=0;for(;;)try{let E=await r(...u);if(E.ok)return E;throw await w.fromResponse(E,m.toString())}catch(E){if(a==null||a(),(R=l==null?void 0:l.signal)!=null&&R.aborted)throw new D;if(E instanceof w&&!Ns.includes(E.status)&&E.status>=400&&E.status<500)throw E;{if(S++,S>h)throw o&&console.log(`Max retries reached (${S}/${h}), giving up`),E;let b=E instanceof w&&E.headers?Fs(E.headers["retry-after"]):0,_=Math.random()*g,L=Math.min(_,s),W=Math.max(b,L);if(o){let ke=b>0?"server+client":"client";console.log(`Retry attempt #${S} after ${W}ms (${ke}, serverMin=${b}ms, clientBackoff=${L}ms)`)}await new Promise(ke=>setTimeout(ke,W)),g=Math.min(g*i,s)}}}}var qs=[201,204,205];function us(r){return async(...e)=>{var i,o;let t=e[0],s=await r(...e);try{if(s.status<200||qs.includes(s.status))return s;let a=await s.text();return new Response(a,s)}catch(a){throw(o=(i=e[1])==null?void 0:i.signal)!=null&&o.aborted?new D:new w(s.status,void 0,void 0,Object.fromEntries([...s.headers.entries()]),t.toString(),a instanceof Error?a.message:typeof a=="string"?a:"failed to read body")}}}var $s={maxChunksToPrefetch:2};function ds(r,e=$s){let{maxChunksToPrefetch:t}=e,s;return async(...o)=>{let a=o[0].toString(),h=s==null?void 0:s.consume(...o);if(h)return h;s==null||s.abort(),s=void 0;let u=await r(...o),m=Ut(a,u);return m&&(s=new kt({fetchClient:r,maxPrefetchedRequests:t,url:m,requestInit:o[1]})),u}}var js=["electric-offset","electric-handle"],Ys=["electric-cursor"],Vs=["electric-schema"];function fs(r){return async(...e)=>{let t=await r(...e);if(t.ok){let s=t.headers,i=[],o=l=>i.push(...l.filter(g=>!s.has(g))),h=e[0].toString(),u=new URL(h);if([me,Be,He,Ie,ge].some(l=>u.searchParams.has(l)))return t;if(o(js),u.searchParams.get(H)==="true"&&o(Ys),(!u.searchParams.has(H)||u.searchParams.get(H)==="false")&&o(Vs),i.length>0)throw new ae(h,i)}return t}}var Ne,Fe,k,oe,I,Ee,ot,kt=class{constructor(e){f(this,Ee);f(this,Ne);f(this,Fe);f(this,k,new Map);f(this,oe);f(this,I);var t;c(this,Ne,(t=e.fetchClient)!=null?t:(...s)=>fetch(...s)),c(this,Fe,e.maxPrefetchedRequests),c(this,oe,e.url.toString()),c(this,I,n(this,oe)),p(this,Ee,ot).call(this,e.url,e.requestInit)}abort(){n(this,k).forEach(([e,t])=>t.abort()),n(this,k).clear()}consume(...e){let t=e[0].toString(),s=n(this,k).get(t);if(!s||t!==n(this,oe))return;let[i,o]=s;if(o.signal.aborted){n(this,k).delete(t);return}return n(this,k).delete(t),i.then(a=>{let h=Ut(t,a);c(this,oe,h),n(this,I)&&!n(this,k).has(n(this,I))&&p(this,Ee,ot).call(this,n(this,I),e[1])}).catch(()=>{}),i}};Ne=new WeakMap,Fe=new WeakMap,k=new WeakMap,oe=new WeakMap,I=new WeakMap,Ee=new WeakSet,ot=function(...e){var i,o;let t=e[0].toString();if(n(this,k).size>=n(this,Fe))return;let s=new AbortController;try{let{signal:a,cleanup:h}=Ws(s,(i=e[1])==null?void 0:i.signal),u=n(this,Ne).call(this,t,ie(y({},(o=e[1])!=null?o:{}),{signal:a}));n(this,k).set(t,[u,s]),u.then(m=>{if(!m.ok||s.signal.aborted)return;let l=Ut(t,m);if(!l||l===t){c(this,I,void 0);return}return c(this,I,l),p(this,Ee,ot).call(this,l,e[1])}).catch(()=>{}).finally(h)}catch(a){}};function Ut(r,e){let t=e.headers.get(de),s=e.headers.get(nt),i=e.headers.has(ns);if(!t||!s||i)return;let o=new URL(r);if(o.searchParams.has(H))return;let a=o.searchParams.get(De);if(a&&t===a){console.warn(`[Electric] Received stale cached response with expired shape handle. This should not happen and indicates a proxy/CDN caching misconfiguration. The response contained handle "${t}" which was previously marked as expired. Check that your proxy includes all query parameters (especially 'handle' and 'offset') in its cache key. Skipping prefetch to prevent infinite 409 loop.`);return}return o.searchParams.set(fe,t),o.searchParams.set(pe,s),o.searchParams.sort(),o.toString()}function Ws(r,e){let t=Ks;if(e)if(e.aborted)r.abort();else{let s=()=>r.abort();e.addEventListener("abort",s,{once:!0,signal:r.signal}),t=()=>e.removeEventListener("abort",s)}return{signal:r.signal,cleanup:t}}function Ks(){}function qe(r,e){switch(r.type){case"ref":{let t=e?e(r.column):r.column;return Le(t)}case"val":return`$${r.paramIndex}`;case"func":return Qs(r,e);default:{let t=r;throw new Error(`Unknown expression type: ${JSON.stringify(t)}`)}}}function Qs(r,e){let t=r.args.map(s=>qe(s,e));switch(r.name){case"eq":return`${t[0]} = ${t[1]}`;case"gt":return`${t[0]} > ${t[1]}`;case"gte":return`${t[0]} >= ${t[1]}`;case"lt":return`${t[0]} < ${t[1]}`;case"lte":return`${t[0]} <= ${t[1]}`;case"and":return t.map(s=>`(${s})`).join(" AND ");case"or":return t.map(s=>`(${s})`).join(" OR ");case"not":return`NOT (${t[0]})`;case"in":return`${t[0]} = ANY(${t[1]})`;case"like":return`${t[0]} LIKE ${t[1]}`;case"ilike":return`${t[0]} ILIKE ${t[1]}`;case"isNull":case"isUndefined":return`${t[0]} IS NULL`;case"upper":return`UPPER(${t[0]})`;case"lower":return`LOWER(${t[0]})`;case"length":return`LENGTH(${t[0]})`;case"concat":return`CONCAT(${t.join(", ")})`;case"coalesce":return`COALESCE(${t.join(", ")})`;default:throw new Error(`Unknown function: ${r.name}`)}}function ht(r,e){return r.map(t=>{let s=e?e(t.column):t.column,i=Le(s);return t.direction==="desc"&&(i+=" DESC"),t.nulls==="first"&&(i+=" NULLS FIRST"),t.nulls==="last"&&(i+=" NULLS LAST"),i}).join(", ")}import{fetchEventSource as Gs}from"@microsoft/fetch-event-source";var Ot=class{constructor(){this.data={};this.max=250;this.storageKey="electric_expired_shapes";this.load()}getExpiredHandle(e){let t=this.data[e];return t?(t.lastUsed=Date.now(),this.save(),t.expiredHandle):null}markExpired(e,t){this.data[e]={expiredHandle:t,lastUsed:Date.now()};let s=Object.keys(this.data);if(s.length>this.max){let i=s.reduce((o,a)=>this.data[a].lastUsed<this.data[o].lastUsed?a:o);delete this.data[i]}this.save()}save(){if(typeof localStorage!="undefined")try{localStorage.setItem(this.storageKey,JSON.stringify(this.data))}catch(e){}}load(){if(typeof localStorage!="undefined")try{let e=localStorage.getItem(this.storageKey);e&&(this.data=JSON.parse(e))}catch(e){this.data={}}}clear(){this.data={},this.save()}},$e=new Ot;var Lt=class{constructor(){this.data={};this.storageKey="electric_up_to_date_tracker";this.cacheTTL=6e4;this.maxEntries=250;this.writeThrottleMs=6e4;this.lastWriteTime=0;this.load(),this.cleanup()}recordUpToDate(e,t){this.data[e]={timestamp:Date.now(),cursor:t};let s=Object.keys(this.data);if(s.length>this.maxEntries){let i=s.reduce((o,a)=>this.data[a].timestamp<this.data[o].timestamp?a:o);delete this.data[i]}this.scheduleSave()}scheduleSave(){let e=Date.now(),t=e-this.lastWriteTime;if(t>=this.writeThrottleMs)this.lastWriteTime=e,this.save();else if(!this.pendingSaveTimer){let s=this.writeThrottleMs-t;this.pendingSaveTimer=setTimeout(()=>{this.lastWriteTime=Date.now(),this.pendingSaveTimer=void 0,this.save()},s)}}shouldEnterReplayMode(e){let t=this.data[e];return!t||Date.now()-t.timestamp>=this.cacheTTL?null:t.cursor}cleanup(){let e=Date.now(),t=Object.keys(this.data),s=!1;for(let i of t)e-this.data[i].timestamp>this.cacheTTL&&(delete this.data[i],s=!0);s&&this.save()}save(){if(typeof localStorage!="undefined")try{localStorage.setItem(this.storageKey,JSON.stringify(this.data))}catch(e){}}load(){if(typeof localStorage!="undefined")try{let e=localStorage.getItem(this.storageKey);e&&(this.data=JSON.parse(e))}catch(e){this.data={}}}clear(){this.data={},this.pendingSaveTimer&&(clearTimeout(this.pendingSaveTimer),this.pendingSaveTimer=void 0),this.save()}},Dt=new Lt;var lt=class{constructor(){this.activeSnapshots=new Map;this.xmaxSnapshots=new Map;this.snapshotsByDatabaseLsn=new Map}addSnapshot(e,t){var o,a,h,u;this.activeSnapshots.set(e.snapshot_mark,{xmin:BigInt(e.xmin),xmax:BigInt(e.xmax),xip_list:e.xip_list.map(BigInt),keys:t});let s=(a=(o=this.xmaxSnapshots.get(BigInt(e.xmax)))==null?void 0:o.add(e.snapshot_mark))!=null?a:new Set([e.snapshot_mark]);this.xmaxSnapshots.set(BigInt(e.xmax),s);let i=(u=(h=this.snapshotsByDatabaseLsn.get(BigInt(e.database_lsn)))==null?void 0:h.add(e.snapshot_mark))!=null?u:new Set([e.snapshot_mark]);this.snapshotsByDatabaseLsn.set(BigInt(e.database_lsn),i)}removeSnapshot(e){this.activeSnapshots.delete(e)}shouldRejectMessage(e){let t=e.headers.txids||[];if(t.length===0)return!1;let s=Math.max(...t);for(let[i,o]of this.xmaxSnapshots.entries())if(s>=i)for(let a of o)this.removeSnapshot(a);return[...this.activeSnapshots.values()].some(i=>i.keys.has(e.key)&&Rt(s,i))}lastSeenUpdate(e){for(let[t,s]of this.snapshotsByDatabaseLsn.entries())if(t<=e)for(let i of s)this.removeSnapshot(i)}};var zs=new Set([it,fe,H,pe,at]);async function Yt(r){return typeof r=="function"?r():r}async function Js(r){let e=Object.entries(r),t=await Promise.all(e.map(async([s,i])=>{if(i===void 0)return[s,void 0];let o=await Yt(i);return[s,Array.isArray(o)?o.join(","):o]}));return Object.fromEntries(t.filter(([s,i])=>i!==void 0))}async function Xs(r){if(!r)return{};let e=Object.entries(r),t=await Promise.all(e.map(async([s,i])=>[s,await Yt(i)]));return Object.fromEntries(t)}function ye(r){let e=new URL(r.origin+r.pathname);for(let[t,s]of r.searchParams)Ct.includes(t)||e.searchParams.set(t,s);return e.searchParams.sort(),e.toString()}var Re,be,_e,ce,K,O,A,B,N,Q,C,he,U,T,G,F,xe,M,q,$,Ae,z,we,Ye,J,j,Te,X,Y,Ve,We,Z,ft,Pe,pt,mt,Ke,ee,V,te,Me,d,It,je,Se,ut,ms,Bt,dt,gs,Es,ys,Nt,Ft,Ss,Rs,qt,$t,jt,bs,_s,xs,As,Ht=class{constructor(e){f(this,d);f(this,Re,null);f(this,be);f(this,_e);f(this,ce);f(this,K,new Map);f(this,O,!1);f(this,A,"active");f(this,B);f(this,N);f(this,Q);f(this,C,!1);f(this,he,!0);f(this,U,!1);f(this,T);f(this,G);f(this,F);f(this,xe);f(this,M);f(this,q,!1);f(this,$);f(this,Ae);f(this,z);f(this,we,Promise.resolve([]));f(this,Ye,new lt);f(this,J,0);f(this,j);f(this,Te);f(this,X);f(this,Y);f(this,Ve);f(this,We,1e3);f(this,Z,0);f(this,ft,3);f(this,Pe,!1);f(this,pt,100);f(this,mt,5e3);f(this,Ke);f(this,ee);f(this,V);f(this,te,0);f(this,Me,3);var a,h,u,m;this.options=y({subscribe:!0},e),Zs(this.options),c(this,B,(a=this.options.offset)!=null?a:"-1"),c(this,N,""),c(this,T,this.options.handle);let t;if(e.columnMapper){let l=g=>{let S={};for(let[R,E]of Object.entries(g)){let b=e.columnMapper.decode(R);S[b]=E}return S};t=e.transformer?g=>e.transformer(l(g)):l}else t=e.transformer;c(this,ce,new st(e.parser,t)),c(this,xe,this.options.onError),c(this,G,(h=this.options.log)!=null?h:"full");let s=(u=e.fetchClient)!=null?u:(...l)=>fetch(...l),i=ie(y({},(m=e.backoffOptions)!=null?m:ct),{onFailedAttempt:()=>{var l,g;c(this,U,!1),(g=(l=e.backoffOptions)==null?void 0:l.onFailedAttempt)==null||g.call(l)}}),o=ls(s,i);c(this,_e,fs(ds(o))),c(this,be,us(n(this,_e))),p(this,d,bs).call(this),p(this,d,_s).call(this)}get shapeHandle(){return n(this,T)}get error(){return n(this,Re)}get isUpToDate(){return n(this,C)}get lastOffset(){return n(this,B)}get mode(){return n(this,G)}subscribe(e,t=()=>{}){let s={};return n(this,K).set(s,[e,t]),n(this,O)||p(this,d,je).call(this),()=>{n(this,K).delete(s)}}unsubscribeAll(){var e,t;n(this,K).clear(),(e=n(this,Ke))==null||e.call(this),(t=n(this,ee))==null||t.call(this)}lastSyncedAt(){return n(this,Q)}lastSynced(){return n(this,Q)===void 0?1/0:Date.now()-n(this,Q)}isConnected(){return n(this,U)}isLoading(){return!n(this,C)}hasStarted(){return n(this,O)}isPaused(){return n(this,A)==="paused"}async forceDisconnectAndRefresh(){var e,t;c(this,q,!0),n(this,C)&&!((e=n(this,M))!=null&&e.signal.aborted)&&((t=n(this,M))==null||t.abort(At)),await p(this,d,Ss).call(this),c(this,q,!1)}async requestSnapshot(e){if(n(this,G)==="full")throw new Error(`Snapshot requests are not supported in ${n(this,G)} mode, as the consumer is guaranteed to observe all data`);n(this,O)||await p(this,d,je).call(this),await p(this,d,Rs).call(this),Ue(this,J)._++;try{n(this,J)===1&&p(this,d,Nt).call(this);let{metadata:t,data:s}=await this.fetchSnapshot(e),i=s.concat([{headers:y({control:"snapshot-end"},t)},{headers:y({control:"subset-end"},e)}]);return n(this,Ye).addSnapshot(t,new Set(s.map(o=>o.key))),p(this,d,dt).call(this,i,!1),{metadata:t,data:s}}finally{Ue(this,J)._--,n(this,J)===0&&p(this,d,Ft).call(this)}}async fetchSnapshot(e){var S,R,E;let s=((R=(S=e.method)!=null?S:this.options.subsetMethod)!=null?R:"GET")==="POST",i,o;if(s){let b=await p(this,d,ut).call(this,this.options.url,!0);i=b.fetchUrl,o={method:"POST",headers:ie(y({},b.requestHeaders),{"Content-Type":"application/json"}),body:JSON.stringify(p(this,d,As).call(this,e))}}else{let b=await p(this,d,ut).call(this,this.options.url,!0,e);i=b.fetchUrl,o={headers:b.requestHeaders}}let a=n(this,T),h;try{h=await n(this,be).call(this,i.toString(),o)}catch(b){if(b instanceof w&&b.status===409){if(a){let _=ye(i);$e.markExpired(_,a)}return c(this,T,b.headers[de]||`${a!=null?a:"handle"}-next`),this.fetchSnapshot(e)}throw b}if(!h.ok)throw await w.fromResponse(h,i.toString());let u=(E=n(this,F))!=null?E:ps(h.headers,{required:!0,url:i.toString()}),{metadata:m,data:l}=await h.json(),g=n(this,ce).parseSnapshotData(l,u);return{metadata:m,data:g}}};Re=new WeakMap,be=new WeakMap,_e=new WeakMap,ce=new WeakMap,K=new WeakMap,O=new WeakMap,A=new WeakMap,B=new WeakMap,N=new WeakMap,Q=new WeakMap,C=new WeakMap,he=new WeakMap,U=new WeakMap,T=new WeakMap,G=new WeakMap,F=new WeakMap,xe=new WeakMap,M=new WeakMap,q=new WeakMap,$=new WeakMap,Ae=new WeakMap,z=new WeakMap,we=new WeakMap,Ye=new WeakMap,J=new WeakMap,j=new WeakMap,Te=new WeakMap,X=new WeakMap,Y=new WeakMap,Ve=new WeakMap,We=new WeakMap,Z=new WeakMap,ft=new WeakMap,Pe=new WeakMap,pt=new WeakMap,mt=new WeakMap,Ke=new WeakMap,ee=new WeakMap,V=new WeakMap,te=new WeakMap,Me=new WeakMap,d=new WeakSet,It=function(){return n(this,X)!==void 0},je=async function(){var e,t,s,i,o,a,h,u;c(this,O,!0);try{await p(this,d,Se).call(this)}catch(m){if(c(this,Re,m),n(this,xe)){let l=await n(this,xe).call(this,m),g=!(m instanceof ae);if(l&&typeof l=="object"&&g){l.params&&(this.options.params=y(y({},(e=this.options.params)!=null?e:{}),l.params)),l.headers&&(this.options.headers=y(y({},(t=this.options.headers)!=null?t:{}),l.headers)),c(this,Re,null),c(this,O,!1),await p(this,d,je).call(this);return}m instanceof Error&&p(this,d,$t).call(this,m),c(this,U,!1),(s=n(this,z))==null||s.call(this),(i=n(this,ee))==null||i.call(this);return}throw m instanceof Error&&p(this,d,$t).call(this,m),c(this,U,!1),(o=n(this,z))==null||o.call(this),(a=n(this,ee))==null||a.call(this),m}c(this,U,!1),(h=n(this,z))==null||h.call(this),(u=n(this,ee))==null||u.call(this)},Se=async function(){var u,m;if(n(this,A)==="pause-requested"){c(this,A,"paused");return}if(!this.options.subscribe&&((u=this.options.signal)!=null&&u.aborted||n(this,C)))return;let e=n(this,A)==="paused";c(this,A,"active");let{url:t,signal:s}=this.options,{fetchUrl:i,requestHeaders:o}=await p(this,d,ut).call(this,t,e),a=await p(this,d,ms).call(this,s),h=n(this,M);try{await p(this,d,gs).call(this,{fetchUrl:i,requestAbortController:h,headers:o,resumingFromPause:e})}catch(l){let g=h.signal.reason,S=h.signal.aborted&&(g===At||g===Tt);if((l instanceof w||l instanceof D)&&S)return p(this,d,Se).call(this);if(l instanceof D){let R=n(this,A);h.signal.aborted&&h.signal.reason===wt&&R==="pause-requested"&&c(this,A,"paused");return}if(l instanceof Oe)return p(this,d,Se).call(this);if(!(l instanceof w))throw l;if(l.status==409){if(n(this,T)){let E=ye(i);$e.markExpired(E,n(this,T))}let R=l.headers[de]||`${n(this,T)}-next`;return p(this,d,xs).call(this,R),await p(this,d,qt).call(this,Array.isArray(l.json)?l.json:[l.json]),p(this,d,Se).call(this)}else throw l}finally{a&&s&&s.removeEventListener("abort",a),c(this,M,void 0)}return(m=n(this,Ae))==null||m.call(this),p(this,d,Se).call(this)},ut=async function(e,t,s){var l,g,S,R,E,b;let[i,o]=await Promise.all([Xs(this.options.headers),this.options.params?Js(er(this.options.params)):void 0]);o&&ws(o);let a=new URL(e);if(o){if(o.table&&P(a,is,o.table),o.where&&typeof o.where=="string"){let L=le(o.where,(l=this.options.columnMapper)==null?void 0:l.encode);P(a,as,L)}if(o.columns){let L=await Yt((g=this.options.params)==null?void 0:g.columns);if(Array.isArray(L)){let W=L.map(String);this.options.columnMapper&&(W=W.map(this.options.columnMapper.encode));let ke=W.map(Le).join(",");P(a,_t,ke)}else P(a,_t,o.columns)}o.replica&&P(a,os,o.replica),o.params&&P(a,cs,o.params);let _=y({},o);delete _.table,delete _.where,delete _.columns,delete _.replica,delete _.params;for(let[L,W]of Object.entries(_))P(a,L,W)}if(s){if(s.whereExpr){let _=qe(s.whereExpr,(S=this.options.columnMapper)==null?void 0:S.encode);P(a,me,_),a.searchParams.set(Mt,JSON.stringify(s.whereExpr))}else if(s.where&&typeof s.where=="string"){let _=le(s.where,(R=this.options.columnMapper)==null?void 0:R.encode);P(a,me,_)}if(s.params&&a.searchParams.set(Be,JSON.stringify(s.params)),s.limit&&P(a,He,s.limit),s.offset&&P(a,Ie,s.offset),s.orderByExpr){let _=ht(s.orderByExpr,(E=this.options.columnMapper)==null?void 0:E.encode);P(a,ge,_),a.searchParams.set(vt,JSON.stringify(s.orderByExpr))}else if(s.orderBy&&typeof s.orderBy=="string"){let _=le(s.orderBy,(b=this.options.columnMapper)==null?void 0:b.encode);P(a,ge,_)}}a.searchParams.set(pe,n(this,B)),a.searchParams.set(Pt,n(this,G));let h=s!==void 0;n(this,C)&&!h&&(!n(this,q)&&!t&&a.searchParams.set(H,"true"),a.searchParams.set(it,n(this,N))),n(this,T)&&a.searchParams.set(fe,n(this,T));let u=ye(a),m=$e.getExpiredHandle(u);return m&&a.searchParams.set(De,m),n(this,V)&&a.searchParams.set(at,n(this,V)),a.searchParams.sort(),{fetchUrl:a,requestHeaders:i}},ms=async function(e){var t;if(c(this,M,new AbortController),e){let s=()=>{var i;(i=n(this,M))==null||i.abort(e.reason)};return e.addEventListener("abort",s,{once:!0}),e.aborted&&((t=n(this,M))==null||t.abort(e.reason)),s}},Bt=async function(e){var h,u,m,l;let{headers:t,status:s}=e,i=t.get(de);if(i){let g=n(this,Y)?ye(n(this,Y)):null,S=g?$e.getExpiredHandle(g):null;if(i!==S)c(this,T,i),n(this,V)&&(c(this,V,void 0),c(this,te,0));else{if(n(this,T)===void 0)throw Ue(this,te)._++,await((h=e.body)==null?void 0:h.cancel()),n(this,te)>n(this,Me)?new w(502,void 0,void 0,{},(m=(u=n(this,Y))==null?void 0:u.toString())!=null?m:"",`CDN continues serving stale cached responses after ${n(this,Me)} retry attempts. This indicates a severe proxy/CDN misconfiguration. Check that your proxy includes all query parameters (especially 'handle' and 'offset') in its cache key. For more information visit the troubleshooting guide: https://electric-sql.com/docs/guides/troubleshooting`):(console.warn(`[Electric] Received stale cached response with expired shape handle. This should not happen and indicates a proxy/CDN caching misconfiguration. The response contained handle "${i}" which was previously marked as expired. Check that your proxy includes all query parameters (especially 'handle' and 'offset') in its cache key. For more information visit the troubleshooting guide: https://electric-sql.com/docs/guides/troubleshooting Retrying with a random cache buster to bypass the stale cache (attempt ${n(this,te)}/${n(this,Me)}).`),c(this,V,`${Date.now()}-${Math.random().toString(36).substring(2,9)}`),new Oe(`Received stale cached response with expired handle "${i}". This indicates a proxy/CDN caching misconfiguration. Check that your proxy includes all query parameters (especially 'handle' and 'offset') in its cache key.`));console.warn(`[Electric] Received stale cached response with expired shape handle. This should not happen and indicates a proxy/CDN caching misconfiguration. The response contained handle "${i}" which was previously marked as expired. Check that your proxy includes all query parameters (especially 'handle' and 'offset') in its cache key. Ignoring the stale response and continuing with handle "${n(this,T)}".`);return}}let o=t.get(nt);o&&c(this,B,o);let a=t.get(rs);a&&c(this,N,a),c(this,F,(l=n(this,F))!=null?l:ps(t)),s===204&&c(this,Q,Date.now())},dt=async function(e,t=!1){var s;if(e.length>0){c(this,he,!0);let i=e[e.length-1];if(St(i)){if(t){let a=ss(i);a&&c(this,B,a)}if(c(this,Q,Date.now()),c(this,C,!0),c(this,he,!1),(s=n(this,Te))==null||s.call(this),n(this,d,It)&&!t&&n(this,N)===n(this,X)){c(this,X,void 0);return}if(c(this,X,void 0),n(this,Y)){let a=ye(n(this,Y));Dt.recordUpToDate(a,n(this,N))}}let o=e.filter(a=>ue(a)?!n(this,Ye).shouldRejectMessage(a):!0);await p(this,d,qt).call(this,o)}},gs=async function(e){var s;if(c(this,Y,e.fetchUrl),!n(this,C)&&!n(this,d,It)){let i=ye(e.fetchUrl),o=Dt.shouldEnterReplayMode(i);o&&c(this,X,o)}let t=(s=this.options.liveSse)!=null?s:this.options.experimentalLiveSse;return n(this,C)&&t&&!n(this,q)&&!e.resumingFromPause&&!n(this,Pe)?(e.fetchUrl.searchParams.set(hs,"true"),e.fetchUrl.searchParams.set(xt,"true"),p(this,d,ys).call(this,e)):p(this,d,Es).call(this,e)},Es=async function(e){let{fetchUrl:t,requestAbortController:s,headers:i}=e,o=await n(this,be).call(this,t.toString(),{signal:s.signal,headers:i});c(this,U,!0),await p(this,d,Bt).call(this,o);let a=n(this,F),u=await o.text()||"[]",m=n(this,ce).parse(u,a);await p(this,d,dt).call(this,m)},ys=async function(e){let{fetchUrl:t,requestAbortController:s,headers:i}=e,o=n(this,_e);c(this,Ve,Date.now());let a=ie(y({},i),{Accept:"text/event-stream"});try{let h=[];await Gs(t.toString(),{headers:a,fetch:o,onopen:async u=>{c(this,U,!0),await p(this,d,Bt).call(this,u)},onmessage:u=>{if(u.data){let m=n(this,F),l=n(this,ce).parse(u.data,m);h.push(l),St(l)&&(p(this,d,dt).call(this,h,!0),h=[])}},onerror:u=>{throw u},signal:s.signal})}catch(h){throw s.signal.aborted?new D:h}finally{let h=Date.now()-n(this,Ve),u=s.signal.aborted;if(h<n(this,We)&&!u)if(Ue(this,Z)._++,n(this,Z)>=n(this,ft))c(this,Pe,!0),console.warn("[Electric] SSE connections are closing immediately (possibly due to proxy buffering or misconfiguration). Falling back to long polling. Your proxy must support streaming SSE responses (not buffer the complete response). Configuration: Nginx add 'X-Accel-Buffering: no', Caddy add 'flush_interval -1' to reverse_proxy. Note: Do NOT disable caching entirely - Electric uses cache headers to enable request collapsing for efficiency.");else{let m=Math.min(n(this,mt),n(this,pt)*Math.pow(2,n(this,Z))),l=Math.floor(Math.random()*m);await new Promise(g=>setTimeout(g,l))}else h>=n(this,We)&&c(this,Z,0)}},Nt=function(){var e;n(this,O)&&n(this,A)==="active"&&(c(this,A,"pause-requested"),(e=n(this,M))==null||e.abort(wt))},Ft=function(){var e;if(n(this,O)&&(n(this,A)==="paused"||n(this,A)==="pause-requested")){if((e=this.options.signal)!=null&&e.aborted)return;n(this,A)==="pause-requested"&&c(this,A,"active"),p(this,d,je).call(this)}},Ss=async function(){return n(this,$)?n(this,$):(c(this,$,new Promise((e,t)=>{c(this,Ae,e),c(this,z,t)})),n(this,$).finally(()=>{c(this,$,void 0),c(this,Ae,void 0),c(this,z,void 0)}),n(this,$))},Rs=async function(){if(n(this,he))return n(this,j)?n(this,j):(c(this,j,new Promise(e=>{c(this,Te,e)})),n(this,j).finally(()=>{c(this,j,void 0),c(this,Te,void 0)}),n(this,j))},qt=async function(e){return c(this,we,n(this,we).then(()=>Promise.all(Array.from(n(this,K).values()).map(async([t,s])=>{try{await t(e)}catch(i){queueMicrotask(()=>{throw i})}})))),n(this,we)},$t=function(e){n(this,K).forEach(([t,s])=>{s==null||s(e)})},jt=function(){return typeof document=="object"&&typeof document.hidden=="boolean"&&typeof document.addEventListener=="function"},bs=function(){if(p(this,d,jt).call(this)){let e=()=>{document.hidden?p(this,d,Nt).call(this):p(this,d,Ft).call(this)};document.addEventListener("visibilitychange",e),c(this,Ke,()=>{document.removeEventListener("visibilitychange",e)})}},_s=function(){if(p(this,d,jt).call(this))return;let e=2e3,t=4e3,s=Date.now(),i=setInterval(()=>{let o=Date.now(),a=o-s;s=o,a>e+t&&n(this,A)==="active"&&n(this,M)&&(c(this,q,!0),n(this,M).abort(Tt),queueMicrotask(()=>{c(this,q,!1)}))},e);typeof i=="object"&&"unref"in i&&i.unref(),c(this,ee,()=>{clearInterval(i)})},xs=function(e){c(this,B,"-1"),c(this,N,""),c(this,T,e),c(this,C,!1),c(this,he,!0),c(this,U,!1),c(this,F,void 0),c(this,J,0),c(this,Z,0),c(this,Pe,!1),c(this,V,void 0),c(this,te,0)},As=function(e){var s,i,o,a;let t={};return e.whereExpr?(t.where=qe(e.whereExpr,(s=this.options.columnMapper)==null?void 0:s.encode),t.where_expr=e.whereExpr):e.where&&typeof e.where=="string"&&(t.where=le(e.where,(i=this.options.columnMapper)==null?void 0:i.encode)),e.params&&(t.params=e.params),e.limit!==void 0&&(t.limit=e.limit),e.offset!==void 0&&(t.offset=e.offset),e.orderByExpr?(t.order_by=ht(e.orderByExpr,(o=this.options.columnMapper)==null?void 0:o.encode),t.order_by_expr=e.orderByExpr):e.orderBy&&typeof e.orderBy=="string"&&(t.order_by=le(e.orderBy,(a=this.options.columnMapper)==null?void 0:a.encode)),t},Ht.Replica={FULL:"full",DEFAULT:"default"};function ps(r,e){let t=r.get(bt);if(!t){if(e!=null&&e.required&&(e!=null&&e.url))throw new ae(e.url,[bt]);return{}}return JSON.parse(t)}function ws(r){if(!r)return;let e=Object.keys(r).filter(t=>zs.has(t));if(e.length>0)throw new Ze(e)}function Zs(r){if(!r.url)throw new ze;if(r.signal&&!(r.signal instanceof AbortSignal))throw new Je;if(r.offset!==void 0&&r.offset!=="-1"&&r.offset!=="now"&&!r.handle)throw new Xe;ws(r.params)}function P(r,e,t){if(!(t===void 0||t==null))if(typeof t=="string")r.searchParams.set(e,t);else if(typeof t=="object")for(let[s,i]of Object.entries(t))r.searchParams.set(`${e}[${s}]`,i);else r.searchParams.set(e,t.toString())}function er(r){return Array.isArray(r.params)?ie(y({},r),{params:Object.fromEntries(r.params.map((e,t)=>[t+1,e]))}):r}var v,se,re,Qe,ve,Ce,ne,x,Ps,Ms,Vt,gt,vs,Wt,Ts=class{constructor(e){f(this,x);f(this,v,new Map);f(this,se,new Map);f(this,re,new Set);f(this,Qe,new Set);f(this,ve,!1);f(this,Ce,"syncing");f(this,ne,!1);this.stream=e,this.stream.subscribe(p(this,x,Ps).bind(this),p(this,x,vs).bind(this))}get isUpToDate(){return n(this,Ce)==="up-to-date"}get lastOffset(){return this.stream.lastOffset}get handle(){return this.stream.shapeHandle}get rows(){return this.value.then(e=>Array.from(e.values()))}get currentRows(){return Array.from(this.currentValue.values())}get value(){return new Promise((e,t)=>{if(this.stream.isUpToDate)e(this.currentValue);else{let s=this.subscribe(({value:i})=>{s(),n(this,ne)&&t(n(this,ne)),e(i)})}})}get currentValue(){return n(this,v)}get error(){return n(this,ne)}lastSyncedAt(){return this.stream.lastSyncedAt()}lastSynced(){return this.stream.lastSynced()}isLoading(){return this.stream.isLoading()}isConnected(){return this.stream.isConnected()}get mode(){return this.stream.mode}async requestSnapshot(e){let t=JSON.stringify(e);n(this,Qe).add(t),await p(this,x,Vt).call(this),await this.stream.requestSnapshot(e)}subscribe(e){let t={};return n(this,se).set(t,e),()=>{n(this,se).delete(t)}}unsubscribeAll(){n(this,se).clear()}get numSubscribers(){return n(this,se).size}};v=new WeakMap,se=new WeakMap,re=new WeakMap,Qe=new WeakMap,ve=new WeakMap,Ce=new WeakMap,ne=new WeakMap,x=new WeakSet,Ps=function(e){let t=!1;e.forEach(s=>{if(ue(s))if(t=p(this,x,gt).call(this,"syncing"),this.mode==="full")switch(s.headers.operation){case"insert":n(this,v).set(s.key,s.value);break;case"update":n(this,v).set(s.key,y(y({},n(this,v).get(s.key)),s.value));break;case"delete":n(this,v).delete(s.key);break}else switch(s.headers.operation){case"insert":n(this,re).add(s.key),n(this,v).set(s.key,s.value);break;case"update":n(this,re).has(s.key)&&n(this,v).set(s.key,y(y({},n(this,v).get(s.key)),s.value));break;case"delete":n(this,re).has(s.key)&&(n(this,v).delete(s.key),n(this,re).delete(s.key));break}if(rt(s))switch(s.headers.control){case"up-to-date":t=p(this,x,gt).call(this,"up-to-date"),n(this,ve)&&(c(this,ve,!1),p(this,x,Ms).call(this));break;case"must-refetch":n(this,v).clear(),n(this,re).clear(),c(this,ne,!1),t=p(this,x,gt).call(this,"syncing"),c(this,ve,!0);break}}),t&&p(this,x,Wt).call(this)},Ms=async function(){await p(this,x,Vt).call(this),await Promise.all(Array.from(n(this,Qe)).map(async e=>{try{let t=JSON.parse(e);await this.stream.requestSnapshot(t)}catch(t){}}))},Vt=async function(){this.stream.isUpToDate||await new Promise(e=>{let t=()=>{this.stream.isUpToDate&&(clearInterval(s),i(),e())},s=setInterval(t,10),i=this.stream.subscribe(()=>t(),()=>t());t()})},gt=function(e){let t=n(this,Ce)!==e;return c(this,Ce,e),t&&e==="up-to-date"},vs=function(e){e instanceof w&&(c(this,ne,e),p(this,x,Wt).call(this))},Wt=function(){n(this,se).forEach(e=>{e({value:this.currentValue,rows:this.currentRows})})};export{ct as BackoffDefaults,Ct as ELECTRIC_PROTOCOL_QUERY_PARAMS,w as FetchError,Ts as Shape,Ht as ShapeStream,es as camelToSnake,qe as compileExpression,ht as compileOrderBy,ts as createColumnMapper,ue as isChangeMessage,rt as isControlMessage,Rt as isVisibleInSnapshot,Yt as resolveValue,Bs as snakeCamelMapper,yt as snakeToCamel};
|
|
5
|
+
For more information visit the troubleshooting guide: /docs/guides/troubleshooting/missing-headers`,super(s)}},Pe=class extends Error{constructor(t){super(t),this.name="StaleCacheError"}};var rt=n=>Number(n),$s=n=>n==="true"||n==="t",js=n=>BigInt(n),os=n=>JSON.parse(n),Ys=n=>n,Vs={int2:rt,int4:rt,int8:js,bool:$s,float4:rt,float8:rt,json:os,jsonb:os};function Ws(n,t){let e=0,s=null,a="",o=!1,i=0,l;function u(c,S,x){let A=c.slice(S,x);return A=A==="NULL"?null:A,t?t(A):A}function g(c){let S=[];for(;e<c.length;e++){if(s=c[e],o)s==="\\"?a+=c[++e]:s==='"'?(S.push(t?t(a):a),a="",o=c[e+1]==='"',i=e+2):a+=s;else if(s==='"')o=!0;else if(s==="{")i=++e,S.push(g(c));else if(s==="}"){o=!1,i<e&&S.push(u(c,i,e)),i=e+1;break}else s===","&&l!=="}"&&l!=='"'&&(S.push(u(c,i,e)),i=e+1);l=s}return i<e&&S.push(S.push(u(c,i,e+1))),S}return g(n)[0]}var nt=class{constructor(t,e){this.parser=E(E({},Vs),t),this.transformer=e}parse(t,e){return JSON.parse(t,(s,a)=>(s==="value"||s==="old_value")&&typeof a=="object"&&a!==null?this.transformMessageValue(a,e):a)}parseSnapshotData(t,e){return t.map(s=>{let a=s;return a.value&&typeof a.value=="object"&&a.value!==null&&(a.value=this.transformMessageValue(a.value,e)),a.old_value&&typeof a.old_value=="object"&&a.old_value!==null&&(a.old_value=this.transformMessageValue(a.old_value,e)),a})}transformMessageValue(t,e){let s=t;return Object.keys(s).forEach(a=>{s[a]=this.parseRow(a,s[a],e)}),this.transformer?this.transformer(s):s}parseRow(t,e,s){var S;let a=s[t];if(!a)return e;let c=a,{type:o,dims:i}=c,l=we(c,["type","dims"]),u=(S=this.parser[o])!=null?S:Ys,g=is(u,a,t);return i&&i>0?is((A,R)=>Ws(A,g),a,t)(e):g(e,l)}};function is(n,t,e){var a;let s=!((a=t.not_null)!=null&&a);return o=>{if(o===null){if(!s)throw new st(e!=null?e:"unknown");return null}return n(o,t)}}function _e(n){return`"${n.replace(/"/g,'""')}"`}function Pt(n){var l,u,g,c;let t=(u=(l=n.match(/^_+/))==null?void 0:l[0])!=null?u:"",e=n.slice(t.length),s=(c=(g=e.match(/_+$/))==null?void 0:g[0])!=null?c:"",i=(s?e.slice(0,e.length-s.length):e).toLowerCase().replace(/_+([a-z])/g,(S,x)=>x.toUpperCase());return t+i+s}function cs(n){return n.replace(/([a-z])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").toLowerCase()}function ls(n){let t={};for(let[e,s]of Object.entries(n))t[s]=e;return{decode:e=>{var s;return(s=n[e])!=null?s:e},encode:e=>{var s;return(s=t[e])!=null?s:e}}}function ne(n,t){if(!n||!t)return n!=null?n:"";let e=new Set(["SELECT","FROM","WHERE","AND","OR","NOT","IN","IS","NULL","NULLS","FIRST","LAST","TRUE","FALSE","LIKE","ILIKE","BETWEEN","ASC","DESC","LIMIT","OFFSET","ORDER","BY","GROUP","HAVING","DISTINCT","AS","ON","JOIN","LEFT","RIGHT","INNER","OUTER","CROSS","CASE","WHEN","THEN","ELSE","END","CAST","LOWER","UPPER","COALESCE","NULLIF"]),s=[],a=0;for(;a<n.length;){let l=n[a];if(l==="'"||l==='"'){let u=a,g=l;for(a++;a<n.length;)if(n[a]===g)if(n[a+1]===g)a+=2;else{a++;break}else a++;s.push({start:u,end:a})}else a++}let o=l=>s.some(u=>l>=u.start&&l<u.end),i=new RegExp("(?<![a-zA-Z0-9_])([a-zA-Z_][a-zA-Z0-9_]*)(?![a-zA-Z0-9_])","g");return n.replace(i,(l,u,g)=>o(g)||e.has(l.toUpperCase())||l.startsWith("$")?l:t(l))}function Ks(n){if(n){let t={};for(let e of Object.keys(n))t[e]=Pt(e);return ls(t)}return{decode:t=>Pt(t),encode:t=>cs(t)}}function ae(n){return"key"in n}function at(n){return!ae(n)}function _t(n){return at(n)&&n.headers.control==="up-to-date"}function hs(n){if(n.headers.control!="up-to-date")return;let t=n.headers.global_last_seen_lsn;return t?`${t}_0`:void 0}function Ct(n,t){let e=BigInt(n),s=BigInt(t.xmin),a=BigInt(t.xmax),o=t.xip_list.map(BigInt);return e<s||e<a&&!o.includes(e)}var us="electric-cursor",oe="electric-handle",ot="electric-offset",vt="electric-schema",ds="electric-up-to-date",Mt="columns",Ce="cursor",ve="expired_handle",J="handle",D="live",X="offset",ps="table",fs="where",ms="replica",gs="params",Ss="experimental_live_sse",Ut="live_sse",kt="force-disconnect-and-refresh",ys="pause-stream",Lt="system-wake",Bt="log",ie="subset__where",Me="subset__limit",Ue="subset__offset",ce="subset__order_by",ke="subset__params",Dt="subset__where_expr",Ot="subset__order_by_expr",Le="cache-buster",Ht=[D,Ut,J,X,Ce,ve,Bt,ie,Me,Ue,ce,ke,Dt,Ot,Le];var Qs=[429],ct={initialDelay:100,maxDelay:6e4,multiplier:1.3,maxRetries:1/0};function zs(n){if(!n)return 0;let t=Number(n);if(Number.isFinite(t)&&t>0)return t*1e3;let e=Date.parse(n);if(!isNaN(e)){let s=e-Date.now();return Math.max(0,Math.min(s,36e5))}return 0}function Es(n,t=ct){let{initialDelay:e,maxDelay:s,multiplier:a,debug:o=!1,onFailedAttempt:i,maxRetries:l=1/0}=t;return async(...u)=>{var A;let g=u[0],c=u[1],S=e,x=0;for(;;)try{let R=await n(...u);if(R.ok)return R;throw await P.fromResponse(R,g.toString())}catch(R){if(i==null||i(),(A=c==null?void 0:c.signal)!=null&&A.aborted)throw new H;if(R instanceof P&&!Qs.includes(R.status)&&R.status>=400&&R.status<500)throw R;{if(x++,x>l)throw o&&console.log(`Max retries reached (${x}/${l}), giving up`),R;let y=R instanceof P&&R.headers?zs(R.headers["retry-after"]):0,L=Math.random()*S,B=Math.min(L,s),Ge=Math.max(y,B);if(o){let Tt=y>0?"server+client":"client";console.log(`Retry attempt #${x} after ${Ge}ms (${Tt}, serverMin=${y}ms, clientBackoff=${B}ms)`)}await new Promise(Tt=>setTimeout(Tt,Ge)),S=Math.min(S*a,s)}}}}var Gs=[201,204,205];function Rs(n){return async(...t)=>{var a,o;let e=t[0],s=await n(...t);try{if(s.status<200||Gs.includes(s.status))return s;let i=await s.text();return new Response(i,s)}catch(i){throw(o=(a=t[1])==null?void 0:a.signal)!=null&&o.aborted?new H:new P(s.status,void 0,void 0,Object.fromEntries([...s.headers.entries()]),e.toString(),i instanceof Error?i.message:typeof i=="string"?i:"failed to read body")}}}var Js={maxChunksToPrefetch:2};function bs(n,t=Js){let{maxChunksToPrefetch:e}=t,s;return async(...o)=>{let i=o[0].toString(),l=s==null?void 0:s.consume(...o);if(l)return l;s==null||s.abort(),s=void 0;let u=await n(...o),g=Ft(i,u);return g&&(s=new It({fetchClient:n,maxPrefetchedRequests:e,url:g,requestInit:o[1]})),u}}var Xs=["electric-offset","electric-handle"],Zs=["electric-cursor"],er=["electric-schema"];function xs(n){return async(...t)=>{let e=await n(...t);if(e.ok){let s=e.headers,a=[],o=c=>a.push(...c.filter(S=>!s.has(S))),l=t[0].toString(),u=new URL(l);if([ie,ke,Me,Ue,ce].some(c=>u.searchParams.has(c)))return e;if(o(Xs),u.searchParams.get(D)==="true"&&o(Zs),(!u.searchParams.has(D)||u.searchParams.get(D)==="false")&&o(er),a.length>0)throw new G(l,a)}return e}}var Be,De,k,Z,I,le,it,It=class{constructor(t){p(this,le);p(this,Be);p(this,De);p(this,k,new Map);p(this,Z);p(this,I);var e;h(this,Be,(e=t.fetchClient)!=null?e:(...s)=>fetch(...s)),h(this,De,t.maxPrefetchedRequests),h(this,Z,t.url.toString()),h(this,I,r(this,Z)),f(this,le,it).call(this,t.url,t.requestInit)}abort(){r(this,k).forEach(([t,e])=>e.abort()),r(this,k).clear()}consume(...t){let e=t[0].toString(),s=r(this,k).get(e);if(!s||e!==r(this,Z))return;let[a,o]=s;if(o.signal.aborted){r(this,k).delete(e);return}return r(this,k).delete(e),a.then(i=>{let l=Ft(e,i);h(this,Z,l),r(this,I)&&!r(this,k).has(r(this,I))&&f(this,le,it).call(this,r(this,I),t[1])}).catch(()=>{}),a}};Be=new WeakMap,De=new WeakMap,k=new WeakMap,Z=new WeakMap,I=new WeakMap,le=new WeakSet,it=function(...t){var a,o;let e=t[0].toString();if(r(this,k).size>=r(this,De))return;let s=new AbortController;try{let{signal:i,cleanup:l}=tr(s,(a=t[1])==null?void 0:a.signal),u=r(this,Be).call(this,e,w(E({},(o=t[1])!=null?o:{}),{signal:i}));r(this,k).set(e,[u,s]),u.then(g=>{if(!g.ok||s.signal.aborted)return;let c=Ft(e,g);if(!c||c===e){h(this,I,void 0);return}return h(this,I,c),f(this,le,it).call(this,c,t[1])}).catch(()=>{}).finally(l)}catch(i){}};function Ft(n,t){let e=t.headers.get(oe),s=t.headers.get(ot),a=t.headers.has(ds);if(!e||!s||a)return;let o=new URL(n);if(o.searchParams.has(D))return;let i=o.searchParams.get(ve);if(i&&e===i){console.warn(`[Electric] Received stale cached response with expired shape handle. This should not happen and indicates a proxy/CDN caching misconfiguration. The response contained handle "${e}" which was previously marked as expired. Check that your proxy includes all query parameters (especially 'handle' and 'offset') in its cache key. Skipping prefetch to prevent infinite 409 loop.`);return}return o.searchParams.set(J,e),o.searchParams.set(X,s),o.searchParams.sort(),o.toString()}function tr(n,t){let e=sr;if(t)if(t.aborted)n.abort();else{let s=()=>n.abort();t.addEventListener("abort",s,{once:!0,signal:n.signal}),e=()=>t.removeEventListener("abort",s)}return{signal:n.signal,cleanup:e}}function sr(){}function Oe(n,t){switch(n.type){case"ref":{let e=t?t(n.column):n.column;return _e(e)}case"val":return`$${n.paramIndex}`;case"func":return rr(n,t);default:{let e=n;throw new Error(`Unknown expression type: ${JSON.stringify(e)}`)}}}function rr(n,t){let e=n.args.map(s=>Oe(s,t));switch(n.name){case"eq":return`${e[0]} = ${e[1]}`;case"gt":return`${e[0]} > ${e[1]}`;case"gte":return`${e[0]} >= ${e[1]}`;case"lt":return`${e[0]} < ${e[1]}`;case"lte":return`${e[0]} <= ${e[1]}`;case"and":return e.map(s=>`(${s})`).join(" AND ");case"or":return e.map(s=>`(${s})`).join(" OR ");case"not":return`NOT (${e[0]})`;case"in":return`${e[0]} = ANY(${e[1]})`;case"like":return`${e[0]} LIKE ${e[1]}`;case"ilike":return`${e[0]} ILIKE ${e[1]}`;case"isNull":case"isUndefined":return`${e[0]} IS NULL`;case"upper":return`UPPER(${e[0]})`;case"lower":return`LOWER(${e[0]})`;case"length":return`LENGTH(${e[0]})`;case"concat":return`CONCAT(${e.join(", ")})`;case"coalesce":return`COALESCE(${e.join(", ")})`;default:throw new Error(`Unknown function: ${n.name}`)}}function lt(n,t){return n.map(e=>{let s=t?t(e.column):e.column,a=_e(s);return e.direction==="desc"&&(a+=" DESC"),e.nulls==="first"&&(a+=" NULLS FIRST"),e.nulls==="last"&&(a+=" NULLS LAST"),a}).join(", ")}import{fetchEventSource as nr}from"@microsoft/fetch-event-source";var Nt=class{constructor(){this.data={};this.max=250;this.storageKey="electric_expired_shapes";this.load()}getExpiredHandle(t){let e=this.data[t];return e?(e.lastUsed=Date.now(),this.save(),e.expiredHandle):null}markExpired(t,e){this.data[t]={expiredHandle:e,lastUsed:Date.now()};let s=Object.keys(this.data);if(s.length>this.max){let a=s.reduce((o,i)=>this.data[i].lastUsed<this.data[o].lastUsed?i:o);delete this.data[a]}this.save()}save(){if(typeof localStorage!="undefined")try{localStorage.setItem(this.storageKey,JSON.stringify(this.data))}catch(t){}}load(){if(typeof localStorage!="undefined")try{let t=localStorage.getItem(this.storageKey);t&&(this.data=JSON.parse(t))}catch(t){this.data={}}}clear(){this.data={},this.save()}},He=new Nt;var qt=class{constructor(){this.data={};this.storageKey="electric_up_to_date_tracker";this.cacheTTL=6e4;this.maxEntries=250;this.writeThrottleMs=6e4;this.lastWriteTime=0;this.load(),this.cleanup()}recordUpToDate(t,e){this.data[t]={timestamp:Date.now(),cursor:e};let s=Object.keys(this.data);if(s.length>this.maxEntries){let a=s.reduce((o,i)=>this.data[i].timestamp<this.data[o].timestamp?i:o);delete this.data[a]}this.scheduleSave()}scheduleSave(){let t=Date.now(),e=t-this.lastWriteTime;if(e>=this.writeThrottleMs)this.lastWriteTime=t,this.save();else if(!this.pendingSaveTimer){let s=this.writeThrottleMs-e;this.pendingSaveTimer=setTimeout(()=>{this.lastWriteTime=Date.now(),this.pendingSaveTimer=void 0,this.save()},s)}}shouldEnterReplayMode(t){let e=this.data[t];return!e||Date.now()-e.timestamp>=this.cacheTTL?null:e.cursor}cleanup(){let t=Date.now(),e=Object.keys(this.data),s=!1;for(let a of e)t-this.data[a].timestamp>this.cacheTTL&&(delete this.data[a],s=!0);s&&this.save()}save(){if(typeof localStorage!="undefined")try{localStorage.setItem(this.storageKey,JSON.stringify(this.data))}catch(t){}}load(){if(typeof localStorage!="undefined")try{let t=localStorage.getItem(this.storageKey);t&&(this.data=JSON.parse(t))}catch(t){this.data={}}}clear(){this.data={},this.pendingSaveTimer&&(clearTimeout(this.pendingSaveTimer),this.pendingSaveTimer=void 0),this.save()}},$t=new qt;var ht=class{constructor(){this.activeSnapshots=new Map;this.xmaxSnapshots=new Map;this.snapshotsByDatabaseLsn=new Map}addSnapshot(t,e){var o,i,l,u;this.activeSnapshots.set(t.snapshot_mark,{xmin:BigInt(t.xmin),xmax:BigInt(t.xmax),xip_list:t.xip_list.map(BigInt),keys:e});let s=(i=(o=this.xmaxSnapshots.get(BigInt(t.xmax)))==null?void 0:o.add(t.snapshot_mark))!=null?i:new Set([t.snapshot_mark]);this.xmaxSnapshots.set(BigInt(t.xmax),s);let a=(u=(l=this.snapshotsByDatabaseLsn.get(BigInt(t.database_lsn)))==null?void 0:l.add(t.snapshot_mark))!=null?u:new Set([t.snapshot_mark]);this.snapshotsByDatabaseLsn.set(BigInt(t.database_lsn),a)}removeSnapshot(t){this.activeSnapshots.delete(t)}shouldRejectMessage(t){let e=t.headers.txids||[];if(e.length===0)return!1;let s=Math.max(...e);for(let[a,o]of this.xmaxSnapshots.entries())if(s>=a)for(let i of o)this.removeSnapshot(i);return[...this.activeSnapshots.values()].some(a=>a.keys.has(t.key)&&Ct(s,a))}lastSeenUpdate(t){for(let[e,s]of this.snapshotsByDatabaseLsn.entries())if(e<=t)for(let a of s)this.removeSnapshot(a)}};var Ie=class{get isUpToDate(){return!1}get staleCacheBuster(){}get staleCacheRetryCount(){return 0}get sseFallbackToLongPolling(){return!1}get consecutiveShortSseConnections(){return 0}get replayCursor(){}canEnterReplayMode(){return!1}enterReplayMode(t){return this}shouldUseSse(t){return!1}handleSseConnectionClosed(t){return{state:this,fellBackToLongPolling:!1,wasShortConnection:!1}}applyUrlParams(t,e){}handleResponseMetadata(t){return{action:"ignored",state:this}}handleMessageBatch(t){return{state:this,suppressBatch:!1,becameUpToDate:!1}}pause(){return new qe(this)}toErrorState(t){return new $e(this,t)}markMustRefetch(t){return new ut({handle:t,offset:"-1",liveCacheBuster:"",lastSyncedAt:this.lastSyncedAt,schema:void 0})}},b,Fe=class extends Ie{constructor(e){super();p(this,b);h(this,b,e)}get handle(){return r(this,b).handle}get offset(){return r(this,b).offset}get schema(){return r(this,b).schema}get liveCacheBuster(){return r(this,b).liveCacheBuster}get lastSyncedAt(){return r(this,b).lastSyncedAt}get currentFields(){return r(this,b)}applyUrlParams(e,s){e.searchParams.set(X,r(this,b).offset),r(this,b).handle&&e.searchParams.set(J,r(this,b).handle)}parseResponseFields(e){var g,c,S;let s=e.responseHandle,a=s&&s!==e.expiredHandle?s:r(this,b).handle,o=(g=e.responseOffset)!=null?g:r(this,b).offset,i=(c=e.responseCursor)!=null?c:r(this,b).liveCacheBuster,l=(S=r(this,b).schema)!=null?S:e.responseSchema,u=e.status===204?e.now:r(this,b).lastSyncedAt;return{handle:a,offset:o,schema:l,liveCacheBuster:i,lastSyncedAt:u}}checkStaleResponse(e){let s=e.responseHandle,a=e.expiredHandle;if(!s||s!==a)return null;if(r(this,b).handle===void 0||r(this,b).handle===a){let o=this.staleCacheRetryCount+1;return{action:"stale-retry",state:new Yt(w(E({},this.currentFields),{staleCacheBuster:e.createCacheBuster(),staleCacheRetryCount:o})),exceededMaxRetries:o>e.maxStaleCacheRetries}}return{action:"ignored",state:this}}handleMessageBatch(e){if(!e.hasMessages||!e.hasUpToDateMessage)return{state:this,suppressBatch:!1,becameUpToDate:!1};let s=r(this,b).offset;e.isSse&&e.upToDateOffset&&(s=e.upToDateOffset);let a={handle:r(this,b).handle,offset:s,schema:r(this,b).schema,liveCacheBuster:r(this,b).liveCacheBuster,lastSyncedAt:e.now};return this.onUpToDate(a,e)}onUpToDate(e,s){return{state:new dt(e),suppressBatch:!1,becameUpToDate:!0}}};b=new WeakMap;var Ne=class extends Fe{handleResponseMetadata(t){let e=this.checkStaleResponse(t);if(e)return e;let s=this.parseResponseFields(t);return{action:"accepted",state:new jt(s)}}canEnterReplayMode(){return!0}enterReplayMode(t){return new Vt(w(E({},this.currentFields),{replayCursor:t}))}},ut=class n extends Ne{constructor(e){super(e);this.kind="initial"}withHandle(e){return new n(w(E({},this.currentFields),{handle:e}))}},jt=class n extends Ne{constructor(e){super(e);this.kind="syncing"}withHandle(e){return new n(w(E({},this.currentFields),{handle:e}))}},ee,ue,Wt=class Wt extends Ne{constructor(e){let i=e,{staleCacheBuster:s,staleCacheRetryCount:a}=i,o=we(i,["staleCacheBuster","staleCacheRetryCount"]);super(o);this.kind="stale-retry";p(this,ee);p(this,ue);h(this,ee,s),h(this,ue,a)}get staleCacheBuster(){return r(this,ee)}get staleCacheRetryCount(){return r(this,ue)}canEnterReplayMode(){return!1}withHandle(e){return new Wt(w(E({},this.currentFields),{handle:e,staleCacheBuster:r(this,ee),staleCacheRetryCount:r(this,ue)}))}applyUrlParams(e,s){super.applyUrlParams(e,s),e.searchParams.set(Le,r(this,ee))}};ee=new WeakMap,ue=new WeakMap;var Yt=Wt,te,$,he=class he extends Fe{constructor(e,s){var a,o;super(e);this.kind="live";p(this,te);p(this,$);h(this,te,(a=s==null?void 0:s.consecutiveShortSseConnections)!=null?a:0),h(this,$,(o=s==null?void 0:s.sseFallbackToLongPolling)!=null?o:!1)}get isUpToDate(){return!0}get consecutiveShortSseConnections(){return r(this,te)}get sseFallbackToLongPolling(){return r(this,$)}withHandle(e){return new he(w(E({},this.currentFields),{handle:e}),this.sseState)}applyUrlParams(e,s){super.applyUrlParams(e,s),s.isSnapshotRequest||(e.searchParams.set(Ce,this.liveCacheBuster),s.canLongPoll&&e.searchParams.set(D,"true"))}get sseState(){return{consecutiveShortSseConnections:r(this,te),sseFallbackToLongPolling:r(this,$)}}handleResponseMetadata(e){let s=this.checkStaleResponse(e);if(s)return s;let a=this.parseResponseFields(e);return{action:"accepted",state:new he(a,this.sseState)}}onUpToDate(e,s){return{state:new he(e,this.sseState),suppressBatch:!1,becameUpToDate:!0}}shouldUseSse(e){return e.liveSseEnabled&&!e.isRefreshing&&!e.resumingFromPause&&!r(this,$)}handleSseConnectionClosed(e){let s=r(this,te),a=r(this,$),o=!1,i=!1;return e.connectionDuration<e.minConnectionDuration&&!e.wasAborted?(i=!0,s=s+1,s>=e.maxShortConnections&&(a=!0,o=!0)):e.connectionDuration>=e.minConnectionDuration&&(s=0),{state:new he(this.currentFields,{consecutiveShortSseConnections:s,sseFallbackToLongPolling:a}),fellBackToLongPolling:o,wasShortConnection:i}}};te=new WeakMap,$=new WeakMap;var dt=he,j,pt=class pt extends Fe{constructor(e){let o=e,{replayCursor:s}=o,a=we(o,["replayCursor"]);super(a);this.kind="replaying";p(this,j);h(this,j,s)}get replayCursor(){return r(this,j)}withHandle(e){return new pt(w(E({},this.currentFields),{handle:e,replayCursor:r(this,j)}))}handleResponseMetadata(e){let s=this.checkStaleResponse(e);if(s)return s;let a=this.parseResponseFields(e);return{action:"accepted",state:new pt(w(E({},a),{replayCursor:r(this,j)}))}}onUpToDate(e,s){let a=!s.isSse&&r(this,j)===s.currentCursor;return{state:new dt(e),suppressBatch:a,becameUpToDate:!0}}};j=new WeakMap;var Vt=pt,qe=class n extends Ie{constructor(e){super();this.kind="paused";this.previousState=e}get handle(){return this.previousState.handle}get offset(){return this.previousState.offset}get schema(){return this.previousState.schema}get liveCacheBuster(){return this.previousState.liveCacheBuster}get lastSyncedAt(){return this.previousState.lastSyncedAt}get isUpToDate(){return this.previousState.isUpToDate}get staleCacheBuster(){return this.previousState.staleCacheBuster}get staleCacheRetryCount(){return this.previousState.staleCacheRetryCount}get sseFallbackToLongPolling(){return this.previousState.sseFallbackToLongPolling}get consecutiveShortSseConnections(){return this.previousState.consecutiveShortSseConnections}get replayCursor(){return this.previousState.replayCursor}withHandle(e){return new n(this.previousState.withHandle(e))}applyUrlParams(e,s){this.previousState.applyUrlParams(e,s)}pause(){return this}resume(){return this.previousState}},$e=class n extends Ie{constructor(e,s){super();this.kind="error";this.previousState=e,this.error=s}get handle(){return this.previousState.handle}get offset(){return this.previousState.offset}get schema(){return this.previousState.schema}get liveCacheBuster(){return this.previousState.liveCacheBuster}get lastSyncedAt(){return this.previousState.lastSyncedAt}get isUpToDate(){return this.previousState.isUpToDate}withHandle(e){return new n(this.previousState.withHandle(e),this.error)}applyUrlParams(e,s){this.previousState.applyUrlParams(e,s)}retry(){return this.previousState}reset(e){return this.previousState.markMustRefetch(e)}};function As(n){return new ut({handle:n.handle,offset:n.offset,liveCacheBuster:"",lastSyncedAt:void 0,schema:void 0})}var U,je,Ye,ft=class{constructor(t){p(this,U,new Set);p(this,je);p(this,Ye);h(this,je,t.onAcquired),h(this,Ye,t.onReleased)}acquire(t){if(r(this,U).has(t)){console.warn(`[Electric] PauseLock: "${t}" already held \u2014 ignoring duplicate acquire`);return}let e=r(this,U).size===0;r(this,U).add(t),e&&r(this,je).call(this)}release(t){if(!r(this,U).delete(t)){console.warn(`[Electric] PauseLock: "${t}" not held \u2014 ignoring release (possible acquire/release mismatch)`);return}r(this,U).size===0&&r(this,Ye).call(this)}get isPaused(){return r(this,U).size>0}isHeldBy(t){return r(this,U).has(t)}releaseAllMatching(t){for(let e of r(this,U))e.startsWith(t)&&r(this,U).delete(e)}};U=new WeakMap,je=new WeakMap,Ye=new WeakMap;var ar=new Set([Ce,J,D,X,Le]);async function Zt(n){return typeof n=="function"?n():n}async function or(n){let t=Object.entries(n),e=await Promise.all(t.map(async([s,a])=>{if(a===void 0)return[s,void 0];let o=await Zt(a);return[s,Array.isArray(o)?o.join(","):o]}));return Object.fromEntries(e.filter(([s,a])=>a!==void 0))}async function ir(n){if(!n)return{};let t=Object.entries(n),e=await Promise.all(t.map(async([s,a])=>[s,await Zt(a)]));return Object.fromEntries(e)}function de(n){let t=new URL(n.origin+n.pathname);for(let[e,s]of n.searchParams)Ht.includes(e)||t.searchParams.set(e,s);return t.searchParams.sort(),t.toString()}var fe,me,ge,se,Y,O,m,F,V,Se,_,W,yt,d,Qt,N,ye,Ee,Re,We,C,q,Ke,Et,Rt,bt,xt,Qe,be,xe,Ve,mt,pe,gt,ws,zt,St,Ps,_s,Cs,vs,Gt,Jt,Xt,Ms,Us,ks,Ls,Kt=class{constructor(t){p(this,d);p(this,fe,null);p(this,me);p(this,ge);p(this,se);p(this,Y,new Map);p(this,O,!1);p(this,m);p(this,F,!1);p(this,V);p(this,Se);p(this,_);p(this,W,0);p(this,yt,0);p(this,N);p(this,ye);p(this,Ee);p(this,Re,Promise.resolve([]));p(this,We,new ht);p(this,C);p(this,q);p(this,Ke);p(this,Et,1e3);p(this,Rt,3);p(this,bt,100);p(this,xt,5e3);p(this,Qe);p(this,be);p(this,xe,3);var i,l,u,g;this.options=E({subscribe:!0},t),cr(this.options),h(this,m,As({offset:(i=this.options.offset)!=null?i:"-1",handle:this.options.handle})),h(this,C,new ft({onAcquired:()=>{var c;h(this,m,r(this,m).pause()),r(this,O)&&((c=r(this,_))==null||c.abort(ys))},onReleased:()=>{var c;r(this,O)&&((c=this.options.signal)!=null&&c.aborted||f(this,d,Ve).call(this).catch(()=>{}))}}));let e;if(t.columnMapper){let c=S=>{let x={};for(let[A,R]of Object.entries(S)){let y=t.columnMapper.decode(A);x[y]=R}return x};e=t.transformer?S=>t.transformer(c(S)):c}else e=t.transformer;h(this,se,new nt(t.parser,e)),h(this,Se,this.options.onError),h(this,V,(l=this.options.log)!=null?l:"full");let s=(u=t.fetchClient)!=null?u:(...c)=>fetch(...c),a=w(E({},(g=t.backoffOptions)!=null?g:ct),{onFailedAttempt:()=>{var c,S;h(this,F,!1),(S=(c=t.backoffOptions)==null?void 0:c.onFailedAttempt)==null||S.call(c)}}),o=Es(s,a);h(this,ge,xs(bs(o))),h(this,me,Rs(r(this,ge))),f(this,d,Ms).call(this),f(this,d,Us).call(this)}get shapeHandle(){return r(this,m).handle}get error(){return r(this,fe)}get isUpToDate(){return r(this,m).isUpToDate}get lastOffset(){return r(this,m).offset}get mode(){return r(this,V)}subscribe(t,e=()=>{}){let s={};return r(this,Y).set(s,[t,e]),r(this,O)||f(this,d,Ve).call(this),()=>{r(this,Y).delete(s)}}unsubscribeAll(){var t,e;r(this,Y).clear(),(t=r(this,Qe))==null||t.call(this),(e=r(this,be))==null||e.call(this)}lastSyncedAt(){return r(this,m).lastSyncedAt}lastSynced(){return r(this,m).lastSyncedAt===void 0?1/0:Date.now()-r(this,m).lastSyncedAt}isConnected(){return r(this,F)}isLoading(){return!r(this,m).isUpToDate}hasStarted(){return r(this,O)}isPaused(){return r(this,C).isPaused}async forceDisconnectAndRefresh(){var t,e;re(this,W)._++;try{r(this,m).isUpToDate&&!((t=r(this,_))!=null&&t.signal.aborted)&&((e=r(this,_))==null||e.abort(kt)),await f(this,d,vs).call(this)}finally{re(this,W)._--}}async requestSnapshot(t){if(r(this,V)==="full")throw new Error(`Snapshot requests are not supported in ${r(this,V)} mode, as the consumer is guaranteed to observe all data`);r(this,O)||f(this,d,Ve).call(this).catch(()=>{});let e=`snapshot-${++re(this,yt)._}`;r(this,C).acquire(e);let s=setTimeout(()=>{console.warn(`[Electric] Snapshot "${e}" has held the pause lock for 30s \u2014 possible hung request or leaked lock. Current holders: ${[...new Set([e])].join(", ")}`)},3e4);try{let{metadata:a,data:o}=await this.fetchSnapshot(t),i=o.concat([{headers:E({control:"snapshot-end"},a)},{headers:E({control:"subset-end"},t)}]);return r(this,We).addSnapshot(a,new Set(o.map(l=>l.key))),f(this,d,St).call(this,i,!1),{metadata:a,data:o}}finally{clearTimeout(s),r(this,C).release(e)}}async fetchSnapshot(t){var x,A,R;let s=((A=(x=t.method)!=null?x:this.options.subsetMethod)!=null?A:"GET")==="POST",a,o;if(s){let y=await f(this,d,gt).call(this,this.options.url,!0);a=y.fetchUrl,o={method:"POST",headers:w(E({},y.requestHeaders),{"Content-Type":"application/json"}),body:JSON.stringify(f(this,d,Ls).call(this,t))}}else{let y=await f(this,d,gt).call(this,this.options.url,!0,t);a=y.fetchUrl,o={headers:y.requestHeaders}}let i=r(this,m).handle,l;try{l=await r(this,me).call(this,a.toString(),o)}catch(y){if(y instanceof P&&y.status===409){if(i){let B=de(a);He.markExpired(B,i)}let L=y.headers[oe]||`${i!=null?i:"handle"}-next`;return h(this,m,r(this,m).withHandle(L)),this.fetchSnapshot(t)}throw y}if(!l.ok)throw await P.fromResponse(l,a.toString());let u=(R=r(this,m).schema)!=null?R:Ts(l.headers,{required:!0,url:a.toString()}),{metadata:g,data:c}=await l.json(),S=r(this,se).parseSnapshotData(c,u);return{metadata:g,data:S}}};fe=new WeakMap,me=new WeakMap,ge=new WeakMap,se=new WeakMap,Y=new WeakMap,O=new WeakMap,m=new WeakMap,F=new WeakMap,V=new WeakMap,Se=new WeakMap,_=new WeakMap,W=new WeakMap,yt=new WeakMap,d=new WeakSet,Qt=function(){return r(this,W)>0},N=new WeakMap,ye=new WeakMap,Ee=new WeakMap,Re=new WeakMap,We=new WeakMap,C=new WeakMap,q=new WeakMap,Ke=new WeakMap,Et=new WeakMap,Rt=new WeakMap,bt=new WeakMap,xt=new WeakMap,Qe=new WeakMap,be=new WeakMap,xe=new WeakMap,Ve=async function(){var t,e;h(this,O,!0);try{await f(this,d,pe).call(this)}catch(s){if(h(this,fe,s),s instanceof Error&&h(this,m,r(this,m).toErrorState(s)),r(this,Se)){let a=await r(this,Se).call(this,s),o=!(s instanceof G);if(a&&typeof a=="object"&&o){a.params&&(this.options.params=E(E({},(t=this.options.params)!=null?t:{}),a.params)),a.headers&&(this.options.headers=E(E({},(e=this.options.headers)!=null?e:{}),a.headers)),h(this,fe,null),r(this,m)instanceof $e&&h(this,m,r(this,m).retry()),h(this,O,!1),await f(this,d,Ve).call(this);return}s instanceof Error&&f(this,d,Jt).call(this,s),f(this,d,mt).call(this);return}throw s instanceof Error&&f(this,d,Jt).call(this,s),f(this,d,mt).call(this),s}f(this,d,mt).call(this)},mt=function(){var t,e;h(this,F,!1),(t=r(this,Ee))==null||t.call(this),(e=r(this,be))==null||e.call(this)},pe=async function(){var u,g;if(r(this,C).isPaused||!this.options.subscribe&&((u=this.options.signal)!=null&&u.aborted||r(this,m).isUpToDate))return;let t=!1;r(this,m)instanceof qe&&(t=!0,h(this,m,r(this,m).resume()));let{url:e,signal:s}=this.options,{fetchUrl:a,requestHeaders:o}=await f(this,d,gt).call(this,e,t),i=await f(this,d,ws).call(this,s),l=r(this,_);if(r(this,C).isPaused){i&&s&&s.removeEventListener("abort",i),h(this,_,void 0);return}try{await f(this,d,Ps).call(this,{fetchUrl:a,requestAbortController:l,headers:o,resumingFromPause:t})}catch(c){let S=l.signal.reason,x=l.signal.aborted&&(S===kt||S===Lt);if((c instanceof P||c instanceof H)&&x)return f(this,d,pe).call(this);if(c instanceof H)return;if(c instanceof Pe)return f(this,d,pe).call(this);if(!(c instanceof P))throw c;if(c.status==409){if(r(this,m).handle){let R=de(a);He.markExpired(R,r(this,m).handle)}let A=c.headers[oe]||`${r(this,m).handle}-next`;return f(this,d,ks).call(this,A),await f(this,d,Gt).call(this,Array.isArray(c.json)?c.json:[c.json]),f(this,d,pe).call(this)}else throw c}finally{i&&s&&s.removeEventListener("abort",i),h(this,_,void 0)}return(g=r(this,ye))==null||g.call(this),f(this,d,pe).call(this)},gt=async function(t,e,s){var g,c,S,x,A,R;let[a,o]=await Promise.all([ir(this.options.headers),this.options.params?or(lr(this.options.params)):void 0]);o&&Bs(o);let i=new URL(t);if(o){if(o.table&&v(i,ps,o.table),o.where&&typeof o.where=="string"){let L=ne(o.where,(g=this.options.columnMapper)==null?void 0:g.encode);v(i,fs,L)}if(o.columns){let L=await Zt((c=this.options.params)==null?void 0:c.columns);if(Array.isArray(L)){let B=L.map(String);this.options.columnMapper&&(B=B.map(this.options.columnMapper.encode));let Ge=B.map(_e).join(",");v(i,Mt,Ge)}else v(i,Mt,o.columns)}o.replica&&v(i,ms,o.replica),o.params&&v(i,gs,o.params);let y=E({},o);delete y.table,delete y.where,delete y.columns,delete y.replica,delete y.params;for(let[L,B]of Object.entries(y))v(i,L,B)}if(s){if(s.whereExpr){let y=Oe(s.whereExpr,(S=this.options.columnMapper)==null?void 0:S.encode);v(i,ie,y),i.searchParams.set(Dt,JSON.stringify(s.whereExpr))}else if(s.where&&typeof s.where=="string"){let y=ne(s.where,(x=this.options.columnMapper)==null?void 0:x.encode);v(i,ie,y)}if(s.params&&i.searchParams.set(ke,JSON.stringify(s.params)),s.limit&&v(i,Me,s.limit),s.offset&&v(i,Ue,s.offset),s.orderByExpr){let y=lt(s.orderByExpr,(A=this.options.columnMapper)==null?void 0:A.encode);v(i,ce,y),i.searchParams.set(Ot,JSON.stringify(s.orderByExpr))}else if(s.orderBy&&typeof s.orderBy=="string"){let y=ne(s.orderBy,(R=this.options.columnMapper)==null?void 0:R.encode);v(i,ce,y)}}r(this,m).applyUrlParams(i,{isSnapshotRequest:s!==void 0,canLongPoll:!r(this,d,Qt)&&!e}),i.searchParams.set(Bt,r(this,V));let l=de(i),u=He.getExpiredHandle(l);return u&&i.searchParams.set(ve,u),i.searchParams.sort(),{fetchUrl:i,requestHeaders:a}},ws=async function(t){var e;if(h(this,_,new AbortController),t){let s=()=>{var a;(a=r(this,_))==null||a.abort(t.reason)};return t.addEventListener("abort",s,{once:!0}),t.aborted&&((e=r(this,_))==null||e.abort(t.reason)),s}},zt=async function(t){var u,g,c;let{headers:e,status:s}=t,a=e.get(oe),o=r(this,q)?de(r(this,q)):null,i=o?He.getExpiredHandle(o):null,l=r(this,m).handleResponseMetadata({status:s,responseHandle:a,responseOffset:e.get(ot),responseCursor:e.get(us),responseSchema:Ts(e),expiredHandle:i,now:Date.now(),maxStaleCacheRetries:r(this,xe),createCacheBuster:()=>`${Date.now()}-${Math.random().toString(36).substring(2,9)}`});if(h(this,m,l.state),l.action==="stale-retry")throw await((u=t.body)==null?void 0:u.cancel()),l.exceededMaxRetries?new P(502,void 0,void 0,{},(c=(g=r(this,q))==null?void 0:g.toString())!=null?c:"",`CDN continues serving stale cached responses after ${r(this,xe)} retry attempts. This indicates a severe proxy/CDN misconfiguration. Check that your proxy includes all query parameters (especially 'handle' and 'offset') in its cache key. For more information visit the troubleshooting guide: https://electric-sql.com/docs/guides/troubleshooting`):(console.warn(`[Electric] Received stale cached response with expired shape handle. This should not happen and indicates a proxy/CDN caching misconfiguration. The response contained handle "${a}" which was previously marked as expired. Check that your proxy includes all query parameters (especially 'handle' and 'offset') in its cache key. For more information visit the troubleshooting guide: https://electric-sql.com/docs/guides/troubleshooting Retrying with a random cache buster to bypass the stale cache (attempt ${r(this,m).staleCacheRetryCount}/${r(this,xe)}).`),new Pe(`Received stale cached response with expired handle "${a}". This indicates a proxy/CDN caching misconfiguration. Check that your proxy includes all query parameters (especially 'handle' and 'offset') in its cache key.`));return l.action==="ignored"?(console.warn(`[Electric] Received stale cached response with expired shape handle. This should not happen and indicates a proxy/CDN caching misconfiguration. The response contained handle "${a}" which was previously marked as expired. Check that your proxy includes all query parameters (especially 'handle' and 'offset') in its cache key. Ignoring the stale response and continuing with handle "${r(this,m).handle}".`),!1):!0},St=async function(t,e=!1){if(t.length===0)return;let s=t[t.length-1],a=_t(s),o=a?hs(s):void 0,i=r(this,m).handleMessageBatch({hasMessages:!0,hasUpToDateMessage:a,isSse:e,upToDateOffset:o,now:Date.now(),currentCursor:r(this,m).liveCacheBuster});if(h(this,m,i.state),a){if(i.suppressBatch)return;if(r(this,q)){let u=de(r(this,q));$t.recordUpToDate(u,r(this,m).liveCacheBuster)}}let l=t.filter(u=>ae(u)?!r(this,We).shouldRejectMessage(u):!0);await f(this,d,Gt).call(this,l)},Ps=async function(t){var s;if(h(this,q,t.fetchUrl),!r(this,m).isUpToDate&&r(this,m).canEnterReplayMode()){let a=de(t.fetchUrl),o=$t.shouldEnterReplayMode(a);o&&h(this,m,r(this,m).enterReplayMode(o))}let e=(s=this.options.liveSse)!=null?s:this.options.experimentalLiveSse;return r(this,m).shouldUseSse({liveSseEnabled:!!e,isRefreshing:r(this,d,Qt),resumingFromPause:!!t.resumingFromPause})?(t.fetchUrl.searchParams.set(Ss,"true"),t.fetchUrl.searchParams.set(Ut,"true"),f(this,d,Cs).call(this,t)):f(this,d,_s).call(this,t)},_s=async function(t){let{fetchUrl:e,requestAbortController:s,headers:a}=t,o=await r(this,me).call(this,e.toString(),{signal:s.signal,headers:a});if(h(this,F,!0),!await f(this,d,zt).call(this,o))return;let l=r(this,m).schema,g=await o.text()||"[]",c=r(this,se).parse(g,l);await f(this,d,St).call(this,c)},Cs=async function(t){let{fetchUrl:e,requestAbortController:s,headers:a}=t,o=r(this,ge);h(this,Ke,Date.now());let i=w(E({},a),{Accept:"text/event-stream"}),l=!1;try{let u=[];await nr(e.toString(),{headers:i,fetch:o,onopen:async g=>{if(h(this,F,!0),!await f(this,d,zt).call(this,g))throw l=!0,new Error("stale response ignored")},onmessage:g=>{if(g.data){let c=r(this,m).schema,S=r(this,se).parse(g.data,c);u.push(S),_t(S)&&(f(this,d,St).call(this,u,!0),u=[])}},onerror:g=>{throw g},signal:s.signal})}catch(u){if(l)return;throw s.signal.aborted?new H:u}finally{let u=Date.now()-r(this,Ke),g=s.signal.aborted,c=r(this,m).handleSseConnectionClosed({connectionDuration:u,wasAborted:g,minConnectionDuration:r(this,Et),maxShortConnections:r(this,Rt)});if(h(this,m,c.state),c.fellBackToLongPolling)console.warn("[Electric] SSE connections are closing immediately (possibly due to proxy buffering or misconfiguration). Falling back to long polling. Your proxy must support streaming SSE responses (not buffer the complete response). Configuration: Nginx add 'X-Accel-Buffering: no', Caddy add 'flush_interval -1' to reverse_proxy. Note: Do NOT disable caching entirely - Electric uses cache headers to enable request collapsing for efficiency.");else if(c.wasShortConnection){let S=Math.min(r(this,xt),r(this,bt)*Math.pow(2,r(this,m).consecutiveShortSseConnections)),x=Math.floor(Math.random()*S);await new Promise(A=>setTimeout(A,x))}}},vs=async function(){if(r(this,C).isPaused)throw new Error("Cannot wait for next tick while PauseLock is held \u2014 this would deadlock because the request loop is paused");return r(this,N)?r(this,N):(h(this,N,new Promise((t,e)=>{h(this,ye,t),h(this,Ee,e)})),r(this,N).finally(()=>{h(this,N,void 0),h(this,ye,void 0),h(this,Ee,void 0)}),r(this,N))},Gt=async function(t){return h(this,Re,r(this,Re).then(()=>Promise.all(Array.from(r(this,Y).values()).map(async([e,s])=>{try{await e(t)}catch(a){queueMicrotask(()=>{throw a})}})))),r(this,Re)},Jt=function(t){r(this,Y).forEach(([e,s])=>{s==null||s(t)})},Xt=function(){return typeof document=="object"&&typeof document.hidden=="boolean"&&typeof document.addEventListener=="function"},Ms=function(){if(f(this,d,Xt).call(this)){let t=()=>{document.hidden?r(this,C).acquire("visibility"):r(this,C).release("visibility")};document.addEventListener("visibilitychange",t),h(this,Qe,()=>{document.removeEventListener("visibilitychange",t)})}},Us=function(){if(f(this,d,Xt).call(this))return;let t=2e3,e=4e3,s=Date.now(),a=setInterval(()=>{let o=Date.now(),i=o-s;s=o,i>t+e&&!r(this,C).isPaused&&r(this,_)&&(re(this,W)._++,r(this,_).abort(Lt),queueMicrotask(()=>{re(this,W)._--}))},t);typeof a=="object"&&"unref"in a&&a.unref(),h(this,be,()=>{clearInterval(a)})},ks=function(t){h(this,m,r(this,m).markMustRefetch(t)),h(this,F,!1),r(this,C).releaseAllMatching("snapshot")},Ls=function(t){var s,a,o,i;let e={};return t.whereExpr?(e.where=Oe(t.whereExpr,(s=this.options.columnMapper)==null?void 0:s.encode),e.where_expr=t.whereExpr):t.where&&typeof t.where=="string"&&(e.where=ne(t.where,(a=this.options.columnMapper)==null?void 0:a.encode)),t.params&&(e.params=t.params),t.limit!==void 0&&(e.limit=t.limit),t.offset!==void 0&&(e.offset=t.offset),t.orderByExpr?(e.order_by=lt(t.orderByExpr,(o=this.options.columnMapper)==null?void 0:o.encode),e.order_by_expr=t.orderByExpr):t.orderBy&&typeof t.orderBy=="string"&&(e.order_by=ne(t.orderBy,(i=this.options.columnMapper)==null?void 0:i.encode)),e},Kt.Replica={FULL:"full",DEFAULT:"default"};function Ts(n,t){let e=n.get(vt);if(!e){if(t!=null&&t.required&&(t!=null&&t.url))throw new G(t.url,[vt]);return{}}return JSON.parse(e)}function Bs(n){if(!n)return;let t=Object.keys(n).filter(e=>ar.has(e));if(t.length>0)throw new tt(t)}function cr(n){if(!n.url)throw new Xe;if(n.signal&&!(n.signal instanceof AbortSignal))throw new Ze;if(n.offset!==void 0&&n.offset!=="-1"&&n.offset!=="now"&&!n.handle)throw new et;Bs(n.params)}function v(n,t,e){if(!(e===void 0||e==null))if(typeof e=="string")n.searchParams.set(t,e);else if(typeof e=="object")for(let[s,a]of Object.entries(e))n.searchParams.set(`${t}[${s}]`,a);else n.searchParams.set(t,e.toString())}function lr(n){return Array.isArray(n.params)?w(E({},n),{params:Object.fromEntries(n.params.map((t,e)=>[e+1,t]))}):n}var M,K,Q,ze,Ae,Te,z,T,Os,Hs,es,At,Is,ts,Ds=class{constructor(t){p(this,T);p(this,M,new Map);p(this,K,new Map);p(this,Q,new Set);p(this,ze,new Set);p(this,Ae,!1);p(this,Te,"syncing");p(this,z,!1);this.stream=t,this.stream.subscribe(f(this,T,Os).bind(this),f(this,T,Is).bind(this))}get isUpToDate(){return r(this,Te)==="up-to-date"}get lastOffset(){return this.stream.lastOffset}get handle(){return this.stream.shapeHandle}get rows(){return this.value.then(t=>Array.from(t.values()))}get currentRows(){return Array.from(this.currentValue.values())}get value(){return new Promise((t,e)=>{if(this.stream.isUpToDate)t(this.currentValue);else{let s=this.subscribe(({value:a})=>{s(),r(this,z)&&e(r(this,z)),t(a)})}})}get currentValue(){return r(this,M)}get error(){return r(this,z)}lastSyncedAt(){return this.stream.lastSyncedAt()}lastSynced(){return this.stream.lastSynced()}isLoading(){return this.stream.isLoading()}isConnected(){return this.stream.isConnected()}get mode(){return this.stream.mode}async requestSnapshot(t){let e=JSON.stringify(t);r(this,ze).add(e),await f(this,T,es).call(this),await this.stream.requestSnapshot(t)}subscribe(t){let e={};return r(this,K).set(e,t),()=>{r(this,K).delete(e)}}unsubscribeAll(){r(this,K).clear()}get numSubscribers(){return r(this,K).size}};M=new WeakMap,K=new WeakMap,Q=new WeakMap,ze=new WeakMap,Ae=new WeakMap,Te=new WeakMap,z=new WeakMap,T=new WeakSet,Os=function(t){let e=!1;t.forEach(s=>{if(ae(s))if(e=f(this,T,At).call(this,"syncing"),this.mode==="full")switch(s.headers.operation){case"insert":r(this,M).set(s.key,s.value);break;case"update":r(this,M).set(s.key,E(E({},r(this,M).get(s.key)),s.value));break;case"delete":r(this,M).delete(s.key);break}else switch(s.headers.operation){case"insert":r(this,Q).add(s.key),r(this,M).set(s.key,s.value);break;case"update":r(this,Q).has(s.key)&&r(this,M).set(s.key,E(E({},r(this,M).get(s.key)),s.value));break;case"delete":r(this,Q).has(s.key)&&(r(this,M).delete(s.key),r(this,Q).delete(s.key));break}if(at(s))switch(s.headers.control){case"up-to-date":e=f(this,T,At).call(this,"up-to-date"),r(this,Ae)&&(h(this,Ae,!1),f(this,T,Hs).call(this));break;case"must-refetch":r(this,M).clear(),r(this,Q).clear(),h(this,z,!1),e=f(this,T,At).call(this,"syncing"),h(this,Ae,!0);break}}),e&&f(this,T,ts).call(this)},Hs=async function(){await f(this,T,es).call(this),await Promise.all(Array.from(r(this,ze)).map(async t=>{try{let e=JSON.parse(t);await this.stream.requestSnapshot(e)}catch(e){}}))},es=async function(){this.stream.isUpToDate||await new Promise(t=>{let e=()=>{this.stream.isUpToDate&&(clearInterval(s),a(),t())},s=setInterval(e,10),a=this.stream.subscribe(()=>e(),()=>e());e()})},At=function(t){let e=r(this,Te)!==t;return h(this,Te,t),e&&t==="up-to-date"},Is=function(t){t instanceof P&&(h(this,z,t),f(this,T,ts).call(this))},ts=function(){r(this,K).forEach(t=>{t({value:this.currentValue,rows:this.currentRows})})};export{ct as BackoffDefaults,Ht as ELECTRIC_PROTOCOL_QUERY_PARAMS,P as FetchError,Ds as Shape,Kt as ShapeStream,cs as camelToSnake,Oe as compileExpression,lt as compileOrderBy,ls as createColumnMapper,ae as isChangeMessage,at as isControlMessage,Ct as isVisibleInSnapshot,Zt as resolveValue,Ks as snakeCamelMapper,Pt as snakeToCamel};
|
|
6
6
|
//# sourceMappingURL=index.browser.mjs.map
|