@electric-sql/client 1.5.2 → 1.5.4

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