@electric-sql/client
Version:
Postgres everywhere - your data, in sync, wherever you need it.
10 lines • 55.9 kB
JavaScript
var Ar=Object.defineProperty,Pr=Object.defineProperties;var _r=Object.getOwnPropertyDescriptors;var xt=Object.getOwnPropertySymbols;var Fs=Object.prototype.hasOwnProperty,Ns=Object.prototype.propertyIsEnumerable;var $s=n=>{throw TypeError(n)};var Is=(n,t,e)=>t in n?Ar(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e,E=(n,t)=>{for(var e in t||(t={}))Fs.call(t,e)&&Is(n,e,t[e]);if(xt)for(var e of xt(t))Ns.call(t,e)&&Is(n,e,t[e]);return n},_=(n,t)=>Pr(n,_r(t));var Ke=(n,t)=>{var e={};for(var s in n)Fs.call(n,s)&&t.indexOf(s)<0&&(e[s]=n[s]);if(n!=null&&xt)for(var s of xt(n))t.indexOf(s)<0&&Ns.call(n,s)&&(e[s]=n[s]);return e};var ss=(n,t,e)=>t.has(n)||$s("Cannot "+e);var r=(n,t,e)=>(ss(n,t,"read from private field"),e?e.call(n):t.get(n)),f=(n,t,e)=>t.has(n)?$s("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(n):t.set(n,e),h=(n,t,e,s)=>(ss(n,t,"write to private field"),s?s.call(n,e):t.set(n,e),e),p=(n,t,e)=>(ss(n,t,"access private method"),e);var z=(n,t,e,s)=>({set _(a){h(n,t,a,e)},get _(){return r(n,t,s)}});var x=class n extends Error{constructor(e,s,a,o,i,c){super(c||`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,c,l=e.headers.get("content-type");return e.bodyUsed||(l&&l.includes("application/json")?c=await e.json():i=await e.text()),new n(a,i,c,o,s)}},j=class extends Error{constructor(){super("Fetch with backoff aborted"),this.name="FetchBackoffAbortError"}};var vt=class extends Error{constructor(){super("Invalid shape options: missing required url parameter"),this.name="MissingShapeUrlError"}},Tt=class extends Error{constructor(){super("Invalid signal option. It must be an instance of AbortSignal."),this.name="InvalidSignalError"}},Ct=class extends Error{constructor(){super("shapeHandle is required if this isn't an initial fetch (i.e. offset > -1)"),this.name="MissingShapeHandleError"}},At=class extends Error{constructor(t){super(`Cannot use reserved Electric parameter names in custom params: ${t.join(", ")}`),this.name="ReservedParamError"}},Pt=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:
`;e.forEach(a=>{s+=`- ${a}
`}),s+=`
This is often due to a proxy not setting CORS correctly so that all Electric headers can be read by the client.`,s+=`
For more information visit the troubleshooting guide: /docs/guides/troubleshooting/missing-headers`,super(s)}},le=class extends Error{constructor(t){super(t),this.name="StaleCacheError"}};var _t=n=>Number(n),Mr=n=>n==="true"||n==="t",kr=n=>BigInt(n),qs=n=>JSON.parse(n),Ur=n=>n,Or={int2:_t,int4:_t,int8:kr,bool:Mr,float4:_t,float8:_t,json:qs,jsonb:qs};function Lr(n,t){let e=0,s=null,a="",o=!1,i=0,c;function l(d,S,y){let b=d.slice(S,y);return b=b==="NULL"?null:b,t?t(b):b}function u(d){let S=[];for(;e<d.length;e++){if(s=d[e],o)s==="\\"?a+=d[++e]:s==='"'?(S.push(t?t(a):a),a="",o=d[e+1]==='"',i=e+2):a+=s;else if(s==='"')o=!0;else if(s==="{")i=++e,S.push(u(d));else if(s==="}"){o=!1,i<e&&S.push(l(d,i,e)),i=e+1;break}else s===","&&c!=="}"&&c!=='"'&&(S.push(l(d,i,e)),i=e+1);c=s}return i<e&&S.push(S.push(l(d,i,e+1))),S}return u(n)[0]}var Mt=class{constructor(t,e){this.parser=E(E({},Or),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 d=a,{type:o,dims:i}=d,c=Ke(d,["type","dims"]),l=(S=this.parser[o])!=null?S:Ur,u=js(l,a,t);return i&&i>0?js((b,R)=>Lr(b,u),a,t)(e):u(e,c)}};function js(n,t,e){var a;let s=!((a=t.not_null)!=null&&a);return o=>{if(o===null){if(!s)throw new Pt(e!=null?e:"unknown");return null}return n(o,t)}}function Qe(n){return`"${n.replace(/"/g,'""')}"`}function rs(n){var c,l,u,d;let t=(l=(c=n.match(/^_+/))==null?void 0:c[0])!=null?l:"",e=n.slice(t.length),s=(d=(u=e.match(/_+$/))==null?void 0:u[0])!=null?d:"",i=(s?e.slice(0,e.length-s.length):e).toLowerCase().replace(/_+([a-z])/g,(S,y)=>"_".repeat(S.length-2)+y.toUpperCase());return t+i+s}function Ws(n){return n.replace(/([a-z_])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").toLowerCase()}function Ys(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 ve(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 c=n[a];if(c==="'"||c==='"'){let l=a,u=c;for(a++;a<n.length;)if(n[a]===u)if(n[a+1]===u)a+=2;else{a++;break}else a++;s.push({start:l,end:a})}else a++}let o=c=>s.some(l=>c>=l.start&&c<l.end),i=new RegExp("(?<![a-zA-Z0-9_])([a-zA-Z_][a-zA-Z0-9_]*)(?![a-zA-Z0-9_])","g");return n.replace(i,(c,l,u)=>o(u)||e.has(c.toUpperCase())||c.startsWith("$")?c:t(c))}function Dr(n){if(n){let t={};for(let e of Object.keys(n))t[e]=rs(e);return Ys(t)}return{decode:t=>rs(t),encode:t=>Ws(t)}}function ze(n){return n!=null&&"key"in n}function kt(n){return n!=null&&"headers"in n&&"control"in n.headers}function as(n){return kt(n)&&n.headers.control==="up-to-date"}function Vs(n){if(n.headers.control!="up-to-date")return;let t=n.headers.global_last_seen_lsn;return t?`${t}_0`:void 0}function Hr(n,t){return typeof t=="bigint"?t.toString():t}function Ut(n){return JSON.stringify(n,Hr)}function Ks(n){return JSON.stringify(ns(n))}function ns(n){if(typeof n=="bigint")return n.toString();if(n===null||typeof n!="object")return n;if(Array.isArray(n))return n.map(ns);let t={};for(let e of Object.keys(n).sort())t[e]=ns(n[e]);return t}function os(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 Ot="electric-cursor",J="electric-handle",Te="electric-offset",Ge="electric-schema",Qs="electric-up-to-date",is="columns",Je="cursor",Xe="expired_handle",he="handle",$="live",de="offset",zs="table",Gs="where",Js="replica",Xs="params",cs="experimental_live_sse",ls="live_sse",hs="force-disconnect-and-refresh",Zs="pause-stream",ds="system-wake",us="log",Ce="subset__where",Ze="subset__limit",et="subset__offset",Ae="subset__order_by",tt="subset__params",fs="subset__where_expr",ps="subset__order_by_expr",ue="cache-buster",ms=[$,ls,cs,he,de,Je,Xe,us,Ce,Ze,et,Ae,tt,fs,ps,ue];var Br=[429],Dt={initialDelay:1e3,maxDelay:32e3,multiplier:2,maxRetries:1/0};function Ir(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 er(n,t=Dt){let{initialDelay:e,maxDelay:s,multiplier:a,debug:o=!1,onFailedAttempt:i,maxRetries:c=1/0}=t;return async(...l)=>{var b;let u=l[0],d=l[1],S=e,y=0;for(;;)try{let R=await n(...l);if(R.ok)return R;throw await x.fromResponse(R,u.toString())}catch(R){if(i==null||i(),(b=d==null?void 0:d.signal)!=null&&b.aborted)throw new j;if(R instanceof x&&!Br.includes(R.status)&&R.status>=400&&R.status<500)throw R;{if(y++,y>c)throw o&&console.log(`Max retries reached (${y}/${c}), giving up`),R;let w=R instanceof x&&R.headers?Ir(R.headers["retry-after"]):0,A=Math.random()*S,C=Math.min(A,s),D=Math.max(w,C);if(o){let P=w>0?"server+client":"client";console.log(`Retry attempt #${y} after ${D}ms (${P}, serverMin=${w}ms, clientBackoff=${C}ms)`)}await new Promise(P=>setTimeout(P,D)),S=Math.min(S*a,s)}}}}var Fr=[201,204,205];function tr(n){return async(...t)=>{var a,o;let e=t[0],s=await n(...t);try{if(s.status<200||Fr.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 j:new x(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 Nr={maxChunksToPrefetch:2};function sr(n,t=Nr){let{maxChunksToPrefetch:e}=t,s;return async(...o)=>{let i=o[0].toString();if(Vr(o[0],o[1])!=="GET")return s==null||s.abort(),s=void 0,n(...o);let l=s==null?void 0:s.consume(...o);if(l)return l;s==null||s.abort(),s=void 0;let u=await n(...o),d=Ss(i,u);return d&&(s=new gs({fetchClient:n,maxPrefetchedRequests:e,url:d,requestInit:o[1]})),u}}var $r=[Te,J],qr=[Ot],jr=[Ge];function rr(n){return async(...t)=>{let e=await n(...t);if(e.ok){let s=e.headers,a=[],o=d=>a.push(...d.filter(S=>!s.has(S))),c=t[0].toString(),l=new URL(c);if([Ce,tt,Ze,et,Ae].some(d=>l.searchParams.has(d)))return e;if(o($r),l.searchParams.get($)==="true"&&o(qr),(!l.searchParams.has($)||l.searchParams.get($)==="false")&&o(jr),a.length>0)throw new G(c,a)}return e}}var st,rt,B,fe,W,Pe,Lt,gs=class{constructor(t){f(this,Pe);f(this,st);f(this,rt);f(this,B,new Map);f(this,fe);f(this,W);var e;h(this,st,(e=t.fetchClient)!=null?e:(...s)=>fetch(...s)),h(this,rt,t.maxPrefetchedRequests),h(this,fe,t.url.toString()),h(this,W,r(this,fe)),p(this,Pe,Lt).call(this,t.url,t.requestInit)}abort(){r(this,B).forEach(([t,e])=>e.abort()),r(this,B).clear()}consume(...t){let e=t[0].toString(),s=r(this,B).get(e);if(!s||e!==r(this,fe))return;let[a,o]=s;if(o.signal.aborted){r(this,B).delete(e);return}return r(this,B).delete(e),a.then(i=>{let c=Ss(e,i);h(this,fe,c),r(this,W)&&!r(this,B).has(r(this,W))&&p(this,Pe,Lt).call(this,r(this,W),t[1])}).catch(()=>{}),a}};st=new WeakMap,rt=new WeakMap,B=new WeakMap,fe=new WeakMap,W=new WeakMap,Pe=new WeakSet,Lt=function(...t){var a,o;let e=t[0].toString();if(r(this,B).size>=r(this,rt))return;let s=new AbortController;try{let{signal:i,cleanup:c}=Wr(s,(a=t[1])==null?void 0:a.signal),l=r(this,st).call(this,e,_(E({},(o=t[1])!=null?o:{}),{signal:i}));r(this,B).set(e,[l,s]),l.then(u=>{if(!u.ok||s.signal.aborted)return;let d=Ss(e,u);if(!d||d===e){h(this,W,void 0);return}return h(this,W,d),p(this,Pe,Lt).call(this,d,t[1])}).catch(()=>{}).finally(c)}catch(i){}};function Ss(n,t){let e=t.headers.get(J),s=t.headers.get(Te),a=t.headers.has(Qs);if(!e||!s||a)return;let o=new URL(n);if(o.searchParams.has($))return;let i=o.searchParams.get(Xe);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(he,e),o.searchParams.set(de,s),o.searchParams.sort(),o.toString()}function Wr(n,t){let e=Yr;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 Yr(){}function Vr(n,t){return t!=null&&t.method?t.method.toUpperCase():typeof Request!="undefined"&&n instanceof Request?n.method.toUpperCase():"GET"}function nt(n,t){switch(n.type){case"ref":{let e=t?t(n.column):n.column;return Qe(e)}case"val":return`$${n.paramIndex}`;case"func":return Kr(n,t);default:{let e=n;throw new Error(`Unknown expression type: ${JSON.stringify(e)}`)}}}function Kr(n,t){let e=n.args.map(s=>nt(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 Ht(n,t){return n.map(e=>{let s=t?t(e.column):e.column,a=Qe(s);return e.direction==="desc"&&(a+=" DESC"),e.nulls==="first"&&(a+=" NULLS FIRST"),e.nulls==="last"&&(a+=" NULLS LAST"),a}).join(", ")}async function ar(n,t){let e=n.getReader(),s;for(;!(s=await e.read()).done;)t(s.value)}function or(n){let t,e,s,a=!1;return function(i){t===void 0?(t=i,e=0,s=-1):t=Qr(t,i);let c=t.length,l=0;for(;e<c;){a&&(t[e]===10&&(l=++e),a=!1);let u=-1;for(;e<c&&u===-1;++e)switch(t[e]){case 58:s===-1&&(s=e-l);break;case 13:a=!0;case 10:u=e;break}if(u===-1)break;n(t.subarray(l,u),s),l=e,s=-1}l===c?t=void 0:l!==0&&(t=t.subarray(l),e-=l)}}function ir(n,t,e){let s=nr(),a=new TextDecoder;return function(i,c){if(i.length===0)e==null||e(s),s=nr();else if(c>0){let l=a.decode(i.subarray(0,c)),u=c+(i[c+1]===32?2:1),d=a.decode(i.subarray(u));switch(l){case"data":s.data=s.data?s.data+`
`+d:d;break;case"event":s.event=d;break;case"id":n(s.id=d);break;case"retry":let S=parseInt(d,10);isNaN(S)||t(s.retry=S);break}}}}function Qr(n,t){let e=new Uint8Array(n.length+t.length);return e.set(n),e.set(t,n.length),e}function nr(){return{data:"",event:"",id:"",retry:void 0}}var zr=function(n,t){var e={};for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&t.indexOf(s)<0&&(e[s]=n[s]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var a=0,s=Object.getOwnPropertySymbols(n);a<s.length;a++)t.indexOf(s[a])<0&&Object.prototype.propertyIsEnumerable.call(n,s[a])&&(e[s[a]]=n[s[a]]);return e},Bt="text/event-stream",Gr=1e3,cr="last-event-id";function ys(n,t){var{signal:e,headers:s,onopen:a,onmessage:o,onclose:i,onerror:c,openWhenHidden:l,fetch:u}=t,d=zr(t,["signal","headers","onopen","onmessage","onclose","onerror","openWhenHidden","fetch"]);return new Promise((S,y)=>{let b=Object.assign({},s);b.accept||(b.accept=Bt);let R;function w(){R.abort(),typeof document!="undefined"&&!document.hidden&&xe()}typeof document!="undefined"&&!l&&document.addEventListener("visibilitychange",w);let A=Gr,C=0;function D(){typeof document!="undefined"&&document.removeEventListener("visibilitychange",w),clearTimeout(C),R.abort()}e==null||e.addEventListener("abort",()=>{D()});let P=u!=null?u:window.fetch,Rt=a!=null?a:Jr;async function xe(){var Ye;R=new AbortController;let wt=e.aborted?e:R.signal;try{let Ve=await P(n,Object.assign(Object.assign({},d),{headers:b,signal:wt}));await Rt(Ve),await ar(Ve.body,or(ir(Q=>{Q?b[cr]=Q:delete b[cr]},Q=>{A=Q},o))),i==null||i(),D(),S()}catch(Ve){if(wt.aborted)D(),y(Ve);else if(!R.signal.aborted)try{let Q=(Ye=c==null?void 0:c(Ve))!==null&&Ye!==void 0?Ye:A;clearTimeout(C),C=setTimeout(xe,Q)}catch(Q){D(),y(Q)}}}xe()})}function Jr(n){let t=n.headers.get("content-type");if(!(t!=null&&t.startsWith(Bt)))throw new Error(`Expected content-type to be ${Bt}, Actual: ${t}`)}var Es=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()}delete(t){delete this.data[t],this.save()}},X=new Es;var bs=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()}delete(t){delete this.data[t],this.save()}},at=new bs;var I,Rs,ws,xs,It=class{constructor(){f(this,I);this.activeSnapshots=new Map;this.xmaxSnapshots=new Map;this.snapshotsByDatabaseLsn=new Map}addSnapshot(t,e){p(this,I,Rs).call(this,t.snapshot_mark);let s=BigInt(t.xmax),a=BigInt(t.database_lsn);this.activeSnapshots.set(t.snapshot_mark,{xmin:BigInt(t.xmin),xmax:s,xip_list:t.xip_list.map(BigInt),keys:e,databaseLsn:a}),p(this,I,ws).call(this,this.xmaxSnapshots,s,t.snapshot_mark),p(this,I,ws).call(this,this.snapshotsByDatabaseLsn,a,t.snapshot_mark)}removeSnapshot(t){p(this,I,Rs).call(this,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)&&os(s,a))}lastSeenUpdate(t){for(let[e,s]of this.snapshotsByDatabaseLsn.entries())if(e<=t)for(let a of s)this.removeSnapshot(a)}};I=new WeakSet,Rs=function(t){let e=this.activeSnapshots.get(t);e&&(p(this,I,xs).call(this,this.xmaxSnapshots,e.xmax,t),p(this,I,xs).call(this,this.snapshotsByDatabaseLsn,e.databaseLsn,t))},ws=function(t,e,s){let a=t.get(e);a?a.add(s):t.set(e,new Set([s]))},xs=function(t,e,s){let a=t.get(e);a&&(a.delete(s),a.size===0&&t.delete(e))};var ot=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 ht(this)}toErrorState(t){return new ke(this,t)}markMustRefetch(t){return new Ft({handle:t,offset:"-1",liveCacheBuster:"",lastSyncedAt:this.lastSyncedAt,schema:void 0})}},v,it=class extends ot{constructor(e){super();f(this,v);h(this,v,e)}get handle(){return r(this,v).handle}get offset(){return r(this,v).offset}get schema(){return r(this,v).schema}get liveCacheBuster(){return r(this,v).liveCacheBuster}get lastSyncedAt(){return r(this,v).lastSyncedAt}get currentFields(){return r(this,v)}applyUrlParams(e,s){e.searchParams.set(de,r(this,v).offset),r(this,v).handle&&e.searchParams.set(he,r(this,v).handle)}parseResponseFields(e){var u,d,S;let s=e.responseHandle,a=s&&s!==e.expiredHandle?s:r(this,v).handle,o=(u=e.responseOffset)!=null?u:r(this,v).offset,i=(d=e.responseCursor)!=null?d:r(this,v).liveCacheBuster,c=(S=r(this,v).schema)!=null?S:e.responseSchema,l=e.status===204?e.now:r(this,v).lastSyncedAt;return{handle:a,offset:o,schema:c,liveCacheBuster:i,lastSyncedAt:l}}checkStaleResponse(e){let s=e.responseHandle,a=e.expiredHandle;if(!s||s!==a)return null;let o=this.staleCacheRetryCount+1;return{action:"stale-retry",state:new Ts(_(E({},this.currentFields),{staleCacheBuster:e.createCacheBuster(),staleCacheRetryCount:o})),exceededMaxRetries:o>e.maxStaleCacheRetries}}handleMessageBatch(e){if(!e.hasMessages||!e.hasUpToDateMessage)return{state:this,suppressBatch:!1,becameUpToDate:!1};let s=r(this,v).offset;e.isSse&&e.upToDateOffset&&(s=e.upToDateOffset);let a={handle:r(this,v).handle,offset:s,schema:r(this,v).schema,liveCacheBuster:r(this,v).liveCacheBuster,lastSyncedAt:e.now};return this.onUpToDate(a,e)}onUpToDate(e,s){return{state:new lt(e),suppressBatch:!1,becameUpToDate:!0}}};v=new WeakMap;var ct=class extends it{handleResponseMetadata(t){let e=this.checkStaleResponse(t);if(e)return e;let s=this.parseResponseFields(t);return t.status===204?{action:"accepted",state:new lt(s,{sseFallbackToLongPolling:!0})}:{action:"accepted",state:new vs(s)}}canEnterReplayMode(){return!0}enterReplayMode(t){return new Cs(_(E({},this.currentFields),{replayCursor:t}))}},Ft=class n extends ct{constructor(e){super(e);this.kind="initial"}withHandle(e){return new n(_(E({},this.currentFields),{handle:e}))}},vs=class n extends ct{constructor(e){super(e);this.kind="syncing"}withHandle(e){return new n(_(E({},this.currentFields),{handle:e}))}},pe,Me,As=class As extends ct{constructor(e){let i=e,{staleCacheBuster:s,staleCacheRetryCount:a}=i,o=Ke(i,["staleCacheBuster","staleCacheRetryCount"]);super(o);this.kind="stale-retry";f(this,pe);f(this,Me);h(this,pe,s),h(this,Me,a)}get staleCacheBuster(){return r(this,pe)}get staleCacheRetryCount(){return r(this,Me)}canEnterReplayMode(){return!1}withHandle(e){return new As(_(E({},this.currentFields),{handle:e,staleCacheBuster:r(this,pe),staleCacheRetryCount:r(this,Me)}))}applyUrlParams(e,s){super.applyUrlParams(e,s),e.searchParams.set(ue,r(this,pe))}};pe=new WeakMap,Me=new WeakMap;var Ts=As,me,Z,_e=class _e extends it{constructor(e,s){var a,o;super(e);this.kind="live";f(this,me);f(this,Z);h(this,me,(a=s==null?void 0:s.consecutiveShortSseConnections)!=null?a:0),h(this,Z,(o=s==null?void 0:s.sseFallbackToLongPolling)!=null?o:!1)}get isUpToDate(){return!0}get consecutiveShortSseConnections(){return r(this,me)}get sseFallbackToLongPolling(){return r(this,Z)}withHandle(e){return new _e(_(E({},this.currentFields),{handle:e}),this.sseState)}applyUrlParams(e,s){super.applyUrlParams(e,s),s.isSnapshotRequest||(e.searchParams.set(Je,this.liveCacheBuster),s.canLongPoll&&e.searchParams.set($,"true"))}get sseState(){return{consecutiveShortSseConnections:r(this,me),sseFallbackToLongPolling:r(this,Z)}}handleResponseMetadata(e){let s=this.checkStaleResponse(e);if(s)return s;let a=this.parseResponseFields(e);return{action:"accepted",state:new _e(a,this.sseState)}}onUpToDate(e,s){return{state:new _e(e,this.sseState),suppressBatch:!1,becameUpToDate:!0}}shouldUseSse(e){return e.liveSseEnabled&&!e.isRefreshing&&!e.resumingFromPause&&!r(this,Z)}handleSseConnectionClosed(e){let s=r(this,me),a=r(this,Z),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 _e(this.currentFields,{consecutiveShortSseConnections:s,sseFallbackToLongPolling:a}),fellBackToLongPolling:o,wasShortConnection:i}}};me=new WeakMap,Z=new WeakMap;var lt=_e,ee,Nt=class Nt extends it{constructor(e){let o=e,{replayCursor:s}=o,a=Ke(o,["replayCursor"]);super(a);this.kind="replaying";f(this,ee);h(this,ee,s)}get replayCursor(){return r(this,ee)}withHandle(e){return new Nt(_(E({},this.currentFields),{handle:e,replayCursor:r(this,ee)}))}handleResponseMetadata(e){let s=this.checkStaleResponse(e);if(s)return s;let a=this.parseResponseFields(e);return{action:"accepted",state:new Nt(_(E({},a),{replayCursor:r(this,ee)}))}}onUpToDate(e,s){let a=!s.isSse&&r(this,ee)===s.currentCursor;return{state:new lt(e),suppressBatch:a,becameUpToDate:!0}}};ee=new WeakMap;var Cs=Nt,ht=class n extends ot{constructor(e){super();this.kind="paused";this.previousState=e instanceof n?e.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}handleResponseMetadata(e){let s=this.previousState.handleResponseMetadata(e);if(s.action==="accepted")return{action:"accepted",state:new n(s.state)};if(s.action==="ignored")return{action:"ignored",state:this};if(s.action==="stale-retry")return{action:"stale-retry",state:new n(s.state),exceededMaxRetries:s.exceededMaxRetries};let a=s;throw new Error(`PausedState.handleResponseMetadata: unhandled transition action "${a.action}"`)}withHandle(e){return new n(this.previousState.withHandle(e))}applyUrlParams(e,s){this.previousState.applyUrlParams(e,s)}pause(){return this}resume(){return this.previousState}},ke=class n extends ot{constructor(e,s){super();this.kind="error";this.previousState=e instanceof n?e.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}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),this.error)}applyUrlParams(e,s){this.previousState.applyUrlParams(e,s)}retry(){return this.previousState}reset(e){return this.previousState.markMustRefetch(e)}};function lr(n){return new Ft({handle:n.handle,offset:n.offset,liveCacheBuster:"",lastSyncedAt:void 0,schema:void 0})}var H,dt,ut,$t=class{constructor(t){f(this,H,new Set);f(this,dt);f(this,ut);h(this,dt,t.onAcquired),h(this,ut,t.onReleased)}acquire(t){if(r(this,H).has(t)){console.warn(`[Electric] PauseLock: "${t}" already held \u2014 ignoring duplicate acquire`);return}let e=r(this,H).size===0;r(this,H).add(t),e&&r(this,dt).call(this)}release(t){if(!r(this,H).delete(t)){console.warn(`[Electric] PauseLock: "${t}" not held \u2014 ignoring release (possible acquire/release mismatch)`);return}r(this,H).size===0&&r(this,ut).call(this)}get isPaused(){return r(this,H).size>0}isHeldBy(t){return r(this,H).has(t)}releaseAllMatching(t){for(let e of r(this,H))e.startsWith(t)&&r(this,H).delete(e)}};H=new WeakMap,dt=new WeakMap,ut=new WeakMap;var Xr=new Set([Je,he,$,de,ue]),ge="https://electric-sql.com/docs/guides/troubleshooting";function qt(){return`${Date.now()}-${Math.random().toString(36).substring(2,9)}`}async function Ds(n){return typeof n=="function"?n():n}async function Zr(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 Ds(a);return[s,Array.isArray(o)?o.join(","):o]}));return Object.fromEntries(e.filter(([s,a])=>a!==void 0))}async function en(n){if(!n)return{};let t=Object.entries(n),e=await Promise.all(t.map(async([s,a])=>[s,await Ds(a)]));return Object.fromEntries(e)}function Se(n){let t=new URL(n.origin+n.pathname);for(let[e,s]of n.searchParams)ms.includes(e)||t.searchParams.append(e,s);return t.searchParams.sort(),t.toString()}var Le,De,He,ye,te,q,g,Y,se,Be,k,re,Kt,m,_s,V,Ie,Fe,Ne,pt,U,F,mt,Qt,zt,Gt,Jt,$e,ne,ae,N,qe,je,Xt,Zt,K,gt,Ee,St,be,Re,oe,yt,Et,ft,Ue,dr,Oe,ur,jt,fr,Ms,Wt,pr,mr,gr,Sr,ks,Yt,Us,yr,Er,Vt,Os,br,Ps=class{constructor(t){f(this,m);f(this,Le,null);f(this,De);f(this,He);f(this,ye);f(this,te,new Map);f(this,q,!1);f(this,g);f(this,Y,!1);f(this,se);f(this,Be);f(this,k);f(this,re,0);f(this,Kt,0);f(this,V);f(this,Ie);f(this,Fe);f(this,Ne,Promise.resolve([]));f(this,pt,new It);f(this,U);f(this,F);f(this,mt);f(this,Qt,1e3);f(this,zt,3);f(this,Gt,100);f(this,Jt,5e3);f(this,$e);f(this,ne);f(this,ae,3);f(this,N,[]);f(this,qe,500);f(this,je,5);f(this,Xt,100);f(this,Zt,5e3);f(this,K,0);f(this,gt,5);f(this,Ee);f(this,St,5);f(this,be,null);f(this,Re,null);f(this,oe,0);f(this,yt,50);f(this,Et);var i,c,l,u;this.options=E({subscribe:!0},t),nn(this.options),h(this,g,lr({offset:(i=this.options.offset)!=null?i:"-1",handle:this.options.handle})),h(this,U,new $t({onAcquired:()=>{var d;h(this,g,r(this,g).pause()),r(this,q)&&((d=r(this,k))==null||d.abort(Zs))},onReleased:()=>{var d;r(this,q)&&((d=this.options.signal)!=null&&d.aborted||p(this,m,ft).call(this).catch(()=>{}))}}));let e;if(t.columnMapper){let d=S=>{let y={};for(let[b,R]of Object.entries(S)){let w=t.columnMapper.decode(b);y[w]=R}return y};e=t.transformer?S=>t.transformer(d(S)):d}else e=t.transformer;h(this,ye,new Mt(t.parser,e)),h(this,Be,this.options.onError),h(this,se,(c=this.options.log)!=null?c:"full");let s=(l=t.fetchClient)!=null?l:(...d)=>fetch(...d),a=_(E({},(u=t.backoffOptions)!=null?u:Dt),{onFailedAttempt:()=>{var d,S;h(this,Y,!1),(S=(d=t.backoffOptions)==null?void 0:d.onFailedAttempt)==null||S.call(d)}});h(this,Et,{initialDelay:a.initialDelay,maxDelay:a.maxDelay,multiplier:a.multiplier});let o=er(s,a);h(this,He,rr(sr(o))),h(this,De,tr(r(this,He))),p(this,m,yr).call(this)}get shapeHandle(){return r(this,g).handle}get error(){return r(this,Le)}get isUpToDate(){return r(this,g).isUpToDate}get lastOffset(){return r(this,g).offset}get mode(){return r(this,se)}subscribe(t,e=()=>{}){let s={};return r(this,te).set(s,[t,e]),r(this,q)||p(this,m,ft).call(this),()=>{r(this,te).delete(s)}}unsubscribeAll(){var t,e;r(this,te).clear(),(t=r(this,$e))==null||t.call(this),(e=r(this,ne))==null||e.call(this)}lastSyncedAt(){return r(this,g).lastSyncedAt}lastSynced(){return r(this,g).lastSyncedAt===void 0?1/0:Date.now()-r(this,g).lastSyncedAt}isConnected(){return r(this,Y)}isLoading(){return!r(this,g).isUpToDate}hasStarted(){return r(this,q)}isPaused(){return r(this,U).isPaused}async forceDisconnectAndRefresh(){var t,e;z(this,re)._++;try{r(this,g).isUpToDate&&!((t=r(this,k))!=null&&t.signal.aborted)&&((e=r(this,k))==null||e.abort(hs)),await p(this,m,Sr).call(this)}finally{z(this,re)._--}}async requestSnapshot(t){if(r(this,se)==="full")throw new Error(`Snapshot requests are not supported in ${r(this,se)} mode, as the consumer is guaranteed to observe all data`);r(this,q)||p(this,m,ft).call(this).catch(()=>{});let e=`snapshot-${++z(this,Kt)._}`;r(this,U).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(", ")}`,new Error("stack trace"))},3e4);try{let{metadata:a,data:o,responseOffset:i,responseHandle:c}=await this.fetchSnapshot(t),l=o.concat([{headers:E({control:"snapshot-end"},a)},{headers:E({control:"subset-end"},t)}]);if(r(this,pt).addSnapshot(a,new Set(o.map(u=>u.key))),p(this,m,Wt).call(this,l,!1),i!==null||c!==null){let u=r(this,g).handleResponseMetadata({status:200,responseHandle:c,responseOffset:i,responseCursor:null,expiredHandle:null,now:Date.now(),maxStaleCacheRetries:r(this,ae),createCacheBuster:qt});u.action==="accepted"?h(this,g,u.state):console.warn(`[Electric] Snapshot response metadata was not accepted by state "${r(this,g).kind}" (action: ${u.action}). Stream offset was not advanced from snapshot.`,new Error("stack trace"))}return{metadata:a,data:o}}finally{clearTimeout(s),r(this,U).release(e)}}async fetchSnapshot(t){return p(this,m,Os).call(this,t,0)}};Le=new WeakMap,De=new WeakMap,He=new WeakMap,ye=new WeakMap,te=new WeakMap,q=new WeakMap,g=new WeakMap,Y=new WeakMap,se=new WeakMap,Be=new WeakMap,k=new WeakMap,re=new WeakMap,Kt=new WeakMap,m=new WeakSet,_s=function(){return r(this,re)>0},V=new WeakMap,Ie=new WeakMap,Fe=new WeakMap,Ne=new WeakMap,pt=new WeakMap,U=new WeakMap,F=new WeakMap,mt=new WeakMap,Qt=new WeakMap,zt=new WeakMap,Gt=new WeakMap,Jt=new WeakMap,$e=new WeakMap,ne=new WeakMap,ae=new WeakMap,N=new WeakMap,qe=new WeakMap,je=new WeakMap,Xt=new WeakMap,Zt=new WeakMap,K=new WeakMap,gt=new WeakMap,Ee=new WeakMap,St=new WeakMap,be=new WeakMap,Re=new WeakMap,oe=new WeakMap,yt=new WeakMap,Et=new WeakMap,ft=async function(){var t,e,s;h(this,q,!0),p(this,m,Er).call(this);try{await p(this,m,Oe).call(this)}catch(a){if(h(this,Le,a),a instanceof Error&&h(this,g,r(this,g).toErrorState(a)),r(this,Be)){let o=await r(this,Be).call(this,a),i=!(a instanceof G);if(o&&typeof o=="object"&&i){if(o.params&&(this.options.params=E(E({},(t=this.options.params)!=null?t:{}),o.params)),o.headers&&(this.options.headers=E(E({},(e=this.options.headers)!=null?e:{}),o.headers)),z(this,oe)._++,r(this,oe)>r(this,yt)){console.warn(`[Electric] onError retry loop exhausted after ${r(this,yt)} consecutive retries. The error was never resolved by the onError handler. Error: ${a instanceof Error?a.message:String(a)}`,new Error("stack trace")),a instanceof Error&&p(this,m,Yt).call(this,a),p(this,m,Ue).call(this);return}if(h(this,Le,null),r(this,g)instanceof ke&&h(this,g,r(this,g).retry()),h(this,K,0),h(this,N,[]),await p(this,m,dr).call(this,r(this,oe)),(s=this.options.signal)!=null&&s.aborted){p(this,m,Ue).call(this);return}return h(this,q,!1),p(this,m,ft).call(this)}a instanceof Error&&p(this,m,Yt).call(this,a),p(this,m,Ue).call(this);return}throw a instanceof Error&&p(this,m,Yt).call(this,a),p(this,m,Ue).call(this),a}p(this,m,Ue).call(this)},Ue=function(){var t,e;h(this,Y,!1),(t=r(this,Fe))==null||t.call(this),(e=r(this,ne))==null||e.call(this)},dr=async function(t){let{initialDelay:e,maxDelay:s,multiplier:a}=r(this,Et),o=Math.min(s,e*Math.pow(a,t-1)),i=Math.floor(Math.random()*o),c=this.options.signal;i<=0||c!=null&&c.aborted||await new Promise(l=>{let u=!1,d=()=>{u||(u=!0,clearTimeout(S),c==null||c.removeEventListener("abort",d),l())},S=setTimeout(d,i);c==null||c.addEventListener("abort",d,{once:!0}),c!=null&&c.aborted&&d()})},Oe=async function(t){var d,S;if(r(this,g)instanceof ke)throw r(this,g).error;let e=t!=null?t:r(this,Ee);if(r(this,U).isPaused){e&&h(this,Ee,e);return}if(!this.options.subscribe&&((d=this.options.signal)!=null&&d.aborted||r(this,g).isUpToDate))return;r(this,g).isUpToDate?(h(this,K,0),h(this,N,[])):await p(this,m,ur).call(this);let s=!1;r(this,g)instanceof ht&&(s=!0,h(this,g,r(this,g).resume()));let{url:a,signal:o}=this.options,{fetchUrl:i,requestHeaders:c}=await p(this,m,jt).call(this,a,s);e&&(i.searchParams.set(ue,e),i.searchParams.sort());let l=await p(this,m,fr).call(this,o),u=r(this,k);if(r(this,U).isPaused){l&&o&&o.removeEventListener("abort",l),e&&h(this,Ee,e),h(this,k,void 0);return}h(this,Ee,void 0);try{await p(this,m,pr).call(this,{fetchUrl:i,requestAbortController:u,headers:c,resumingFromPause:s})}catch(y){let b=u.signal.reason,R=u.signal.aborted&&(b===hs||b===ds);if((y instanceof x||y instanceof j)&&R)return p(this,m,Oe).call(this);if(y instanceof j)return;if(y instanceof le)return p(this,m,Oe).call(this);if(!(y instanceof x))throw y;if(y.status==409){if(r(this,g).handle){let C=Se(i);X.markExpired(C,r(this,g).handle)}let w=y.headers[J];w||console.warn("[Electric] Received 409 response without a shape handle header. This likely indicates a proxy or CDN stripping required headers.",new Error("stack trace"));let A=qt();return p(this,m,Vt).call(this,w),await p(this,m,ks).call(this,[{headers:{control:"must-refetch"}}]),p(this,m,Oe).call(this,A)}else throw y}finally{l&&o&&o.removeEventListener("abort",l),h(this,k,void 0)}return(S=r(this,Ie))==null||S.call(this),p(this,m,Oe).call(this)},ur=async function(){let t=Date.now(),e=r(this,g).offset;if(h(this,N,r(this,N).filter(i=>t-i.timestamp<r(this,qe))),r(this,N).push({timestamp:t,offset:e}),r(this,N).filter(i=>i.offset===e).length<r(this,je))return;if(z(this,K)._++,r(this,K)>=r(this,gt))throw new x(502,void 0,void 0,{},this.options.url,`Client is stuck in a fast retry loop (${r(this,je)} requests in ${r(this,qe)}ms at the same offset, repeated ${r(this,gt)} times). Client-side caches were cleared automatically on first detection, but the loop persists. This usually indicates a proxy or CDN misconfiguration. Common causes:
- Proxy is not including query parameters (handle, offset) in its cache key
- CDN is serving stale 409 responses
- Proxy is stripping required Electric headers from responses
For more information visit the troubleshooting guide: ${ge}`);if(r(this,K)===1){if(console.warn(`[Electric] Detected fast retry loop (${r(this,je)} requests in ${r(this,qe)}ms at the same offset). Clearing client-side caches and resetting stream to recover. If this persists, check that your proxy includes all query parameters (especially 'handle' and 'offset') in its cache key, and that required Electric headers are forwarded to the client. For more information visit the troubleshooting guide: ${ge}`,new Error("stack trace")),r(this,F)){let i=Se(r(this,F));X.delete(i),at.delete(i)}else X.clear(),at.clear();p(this,m,Vt).call(this),h(this,N,[]);return}let a=Math.min(r(this,Zt),r(this,Xt)*Math.pow(2,r(this,K))),o=Math.floor(Math.random()*a);await new Promise(i=>setTimeout(i,o)),h(this,N,[])},jt=async function(t,e,s){var u,d,S,y,b,R;let[a,o]=await Promise.all([en(this.options.headers),this.options.params?Zr(an(this.options.params)):void 0]);o&&Rr(o);let i=new URL(t);if(o){if(o.table&&O(i,zs,o.table),o.where&&typeof o.where=="string"){let A=ve(o.where,(u=this.options.columnMapper)==null?void 0:u.encode);O(i,Gs,A)}if(o.columns){let A=await Ds((d=this.options.params)==null?void 0:d.columns);if(Array.isArray(A)){let C=A.map(String);this.options.columnMapper&&(C=C.map(this.options.columnMapper.encode));let D=C.map(Qe).join(",");O(i,is,D)}else O(i,is,o.columns)}o.replica&&O(i,Js,o.replica),o.params&&O(i,Xs,o.params);let w=E({},o);delete w.table,delete w.where,delete w.columns,delete w.replica,delete w.params;for(let[A,C]of Object.entries(w))O(i,A,C)}if(s){if(s.whereExpr){let w=nt(s.whereExpr,(S=this.options.columnMapper)==null?void 0:S.encode);O(i,Ce,w),i.searchParams.set(fs,JSON.stringify(s.whereExpr))}else if(s.where&&typeof s.where=="string"){let w=ve(s.where,(y=this.options.columnMapper)==null?void 0:y.encode);O(i,Ce,w)}if(s.params&&i.searchParams.set(tt,Ut(s.params)),s.limit!==void 0&&O(i,Ze,s.limit),s.offset!==void 0&&O(i,et,s.offset),s.orderByExpr){let w=Ht(s.orderByExpr,(b=this.options.columnMapper)==null?void 0:b.encode);O(i,Ae,w),i.searchParams.set(ps,JSON.stringify(s.orderByExpr))}else if(s.orderBy&&typeof s.orderBy=="string"){let w=ve(s.orderBy,(R=this.options.columnMapper)==null?void 0:R.encode);O(i,Ae,w)}}r(this,g).applyUrlParams(i,{isSnapshotRequest:s!==void 0,canLongPoll:!r(this,m,_s)&&!e}),i.searchParams.set(us,r(this,se));let c=Se(i),l=X.getExpiredHandle(c);return l&&i.searchParams.set(Xe,l),i.searchParams.sort(),{fetchUrl:i,requestHeaders:a}},fr=async function(t){var e;if(h(this,k,new AbortController),t){let s=()=>{var a;(a=r(this,k))==null||a.abort(t.reason)};return t.addEventListener("abort",s,{once:!0}),t.aborted&&((e=r(this,k))==null||e.abort(t.reason)),s}},Ms=async function(t){var l,u,d;let{headers:e,status:s}=t,a=e.get(J),o=r(this,F)?Se(r(this,F)):null,i=o?X.getExpiredHandle(o):null;if(r(this,Re)){let{shapeKey:S,staleHandle:y}=r(this,Re);h(this,Re,null),o===S&&a===y&&console.warn(`[Electric] Self-healing retry received the same handle "${y}" that was just marked expired. This means your proxy/CDN is serving a stale cached response and ignoring cache-buster query params. The client will proceed with this stale data to avoid a permanent failure, but it may be out of date until the cache refreshes. Fix: configure your proxy/CDN to include all query parameters (especially 'handle' and 'offset') in its cache key. For more information visit the troubleshooting guide: ${ge}`,new Error("stack trace"))}let c=r(this,g).handleResponseMetadata({status:s,responseHandle:a,responseOffset:e.get(Te),responseCursor:e.get(Ot),responseSchema:hr(e),expiredHandle:i,now:Date.now(),maxStaleCacheRetries:r(this,ae),createCacheBuster:qt});if(h(this,g,c.state),s===204&&h(this,be,null),c.action==="accepted"&&s===204&&h(this,oe,0),c.action==="stale-retry")throw await((l=t.body)==null?void 0:l.cancel()),c.exceededMaxRetries?o&&(X.delete(o),r(this,be)!==o)?(console.warn(`[Electric] Stale cache retries exhausted (${r(this,ae)} attempts). Clearing expired handle entry and attempting self-healing retry without the expired_handle parameter. For more information visit the troubleshooting guide: ${ge}`,new Error("stack trace")),h(this,be,o),a&&h(this,Re,{shapeKey:o,staleHandle:a}),p(this,m,Vt).call(this),new le("Expired handle entry evicted for self-healing retry")):new x(502,void 0,void 0,{},(d=(u=r(this,F))==null?void 0:u.toString())!=null?d:"",`CDN continues serving stale cached responses after ${r(this,ae)} 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: ${ge}`):(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: ${ge} Retrying with a random cache buster to bypass the stale cache (attempt ${r(this,g).staleCacheRetryCount}/${r(this,ae)}).`,new Error("stack trace")),new le(`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 c.action==="ignored"?(console.warn(`[Electric] Response was ignored by state "${r(this,g).kind}". The response body will be skipped. This may indicate a proxy/CDN caching issue or a client state machine bug.`,new Error("stack trace")),!1):!0},Wt=async function(t,e=!1){if(!Array.isArray(t)){console.warn(`[Electric] #onMessages called with non-array argument (${typeof t}). This is a client bug \u2014 please report it.`,new Error("stack trace"));return}if(t.length===0)return;h(this,oe,0);let s=t[t.length-1],a=as(s),o=a?Vs(s):void 0,i=r(this,g).handleMessageBatch({hasMessages:!0,hasUpToDateMessage:a,isSse:e,upToDateOffset:o,now:Date.now(),currentCursor:r(this,g).liveCacheBuster});if(h(this,g,i.state),a){if(i.suppressBatch)return;if(r(this,F)){let l=Se(r(this,F));at.recordUpToDate(l,r(this,g).liveCacheBuster),h(this,be,null)}}let c=t.filter(l=>ze(l)?!r(this,pt).shouldRejectMessage(l):!0);await p(this,m,ks).call(this,c)},pr=async function(t){var s;if(h(this,F,t.fetchUrl),!r(this,g).isUpToDate&&r(this,g).canEnterReplayMode()){let a=Se(t.fetchUrl),o=at.shouldEnterReplayMode(a);o&&h(this,g,r(this,g).enterReplayMode(o))}let e=(s=this.options.liveSse)!=null?s:this.options.experimentalLiveSse;return r(this,g).shouldUseSse({liveSseEnabled:!!e,isRefreshing:r(this,m,_s),resumingFromPause:!!t.resumingFromPause})?(t.fetchUrl.searchParams.set(cs,"true"),t.fetchUrl.searchParams.set(ls,"true"),p(this,m,gr).call(this,t)):p(this,m,mr).call(this,t)},mr=async function(t){var S;let{fetchUrl:e,requestAbortController:s,headers:a}=t,o=await r(this,De).call(this,e.toString(),{signal:s.signal,headers:a});if(h(this,Y,!0),!await p(this,m,Ms).call(this,o))return;let c=r(this,g).schema,u=await o.text()||"[]",d=r(this,ye).parse(u,c);if(!Array.isArray(d)){let y=(S=Ut(d))==null?void 0:S.slice(0,200);throw new x(o.status,`Received non-array response body from shape endpoint. This may indicate a proxy or CDN is returning an unexpected response. Expected a JSON array, got ${typeof d}: ${y}`,void 0,Object.fromEntries(o.headers.entries()),e.toString())}await p(this,m,Wt).call(this,d)},gr=async function(t){let{fetchUrl:e,requestAbortController:s,headers:a}=t,o=r(this,He);h(this,mt,Date.now());let i=_(E({},a),{Accept:"text/event-stream"}),c=!1;try{let l=[];await ys(e.toString(),{headers:i,fetch:o,onopen:async u=>{if(h(this,Y,!0),!await p(this,m,Ms).call(this,u))throw c=!0,new Error("stale response ignored")},onmessage:u=>{if(u.data){let d=r(this,g).schema,S=r(this,ye).parse(u.data,d);l.push(S),as(S)&&(p(this,m,Wt).call(this,l,!0),l=[])}},onerror:u=>{throw u},signal:s.signal})}catch(l){if(c)return;if(s.signal.aborted)throw new j;if(l instanceof x||l instanceof le||l instanceof G)throw l}finally{let l=Date.now()-r(this,mt),u=s.signal.aborted,d=r(this,g).handleSseConnectionClosed({connectionDuration:l,wasAborted:u,minConnectionDuration:r(this,Qt),maxShortConnections:r(this,zt)});if(h(this,g,d.state),d.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.",new Error("stack trace"));else if(d.wasShortConnection){let S=Math.min(r(this,Jt),r(this,Gt)*Math.pow(2,r(this,g).consecutiveShortSseConnections)),y=Math.floor(Math.random()*S);await new Promise(b=>setTimeout(b,y))}}},Sr=async function(){if(r(this,U).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,V)?r(this,V):(h(this,V,new Promise((t,e)=>{h(this,Ie,t),h(this,Fe,e)})),r(this,V).finally(()=>{h(this,V,void 0),h(this,Ie,void 0),h(this,Fe,void 0)}),r(this,V))},ks=async function(t){return h(this,Ne,r(this,Ne).then(()=>Promise.all(Array.from(r(this,te).values()).map(async([e,s])=>{try{await e(t)}catch(a){queueMicrotask(()=>{throw a})}})))),r(this,Ne)},Yt=function(t){r(this,te).forEach(([e,s])=>{s==null||s(t)})},Us=function(){return typeof document=="object"&&typeof document.hidden=="boolean"&&typeof document.addEventListener=="function"},yr=function(){if(p(this,m,Us).call(this)){let t=()=>{document.hidden?r(this,U).acquire("visibility"):r(this,U).release("visibility")};document.addEventListener("visibilitychange",t),h(this,$e,()=>{document.removeEventListener("visibilitychange",t),h(this,$e,void 0)})}},Er=function(){if(p(this,m,Us).call(this)||r(this,ne))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,U).isPaused&&r(this,k)&&(z(this,re)._++,r(this,k).abort(ds),queueMicrotask(()=>{z(this,re)._--}))},t);typeof a=="object"&&"unref"in a&&a.unref(),h(this,ne,()=>{clearInterval(a),h(this,ne,void 0)})},Vt=function(t){h(this,g,r(this,g).markMustRefetch(t)),h(this,Y,!1),r(this,U).releaseAllMatching("snapshot")},Os=async function(t,e,s){var A,C,D;let o=((C=(A=t.method)!=null?A:this.options.subsetMethod)!=null?C:"GET")==="POST",i,c;if(o){let P=await p(this,m,jt).call(this,this.options.url,!0);i=P.fetchUrl,c={method:"POST",headers:_(E({},P.requestHeaders),{"Content-Type":"application/json"}),body:Ut(p(this,m,br).call(this,t))}}else{let P=await p(this,m,jt).call(this,this.options.url,!0,t);i=P.fetchUrl,c={headers:P.requestHeaders}}s&&(i.searchParams.set(ue,s),i.searchParams.sort());let l=r(this,g).handle,u;try{u=await r(this,De).call(this,i.toString(),c)}catch(P){if(P instanceof x&&P.status===409){let Rt=e+1;if(Rt>r(this,St))throw new x(502,void 0,void 0,{},i.toString(),`Snapshot request stuck in 409 retry loop after ${r(this,St)} attempts. This indicates a proxy/CDN misconfiguration. For more information visit the troubleshooting guide: ${ge}`);if(l){let wt=Se(i);X.markExpired(wt,l)}let xe=P.headers[J];xe?h(this,g,r(this,g).withHandle(xe)):console.warn("[Electric] Received 409 response without a shape handle header. This likely indicates a proxy or CDN stripping required headers.",new Error("stack trace"));let Ye=qt();return p(this,m,Os).call(this,t,Rt,Ye)}throw P}if(!u.ok)throw await x.fromResponse(u,i.toString());let d=(D=r(this,g).schema)!=null?D:hr(u.headers,{required:!0,url:i.toString()}),{metadata:S,data:y}=await u.json(),b=r(this,ye).parseSnapshotData(y,d),R=u.headers.get(Te)||null,w=u.headers.get(J);return{metadata:S,data:b,responseOffset:R,responseHandle:w}},br=function(t){var s,a,o,i;let e={};return t.whereExpr?(e.where=nt(t.whereExpr,(s=this.options.columnMapper)==null?void 0:s.encode),e.where_expr=t.whereExpr):t.where&&typeof t.where=="string"&&(e.where=ve(t.where,(a=this.options.columnMapper)==null?void 0:a.encode)),