UNPKG

@electric-sql/client

Version:

Postgres everywhere - your data, in sync, wherever you need it.

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