@electric-sql/client 1.0.14 → 1.1.1

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.
@@ -1,6 +1,6 @@
1
- var Wt=Object.defineProperty,$t=Object.defineProperties;var Gt=Object.getOwnPropertyDescriptors;var _e=Object.getOwnPropertySymbols;var ft=Object.prototype.hasOwnProperty,ut=Object.prototype.propertyIsEnumerable;var dt=r=>{throw TypeError(r)};var lt=(r,e,t)=>e in r?Wt(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,b=(r,e)=>{for(var t in e||(e={}))ft.call(e,t)&&lt(r,t,e[t]);if(_e)for(var t of _e(e))ut.call(e,t)&&lt(r,t,e[t]);return r},le=(r,e)=>$t(r,Gt(e));var pt=(r,e)=>{var t={};for(var s in r)ft.call(r,s)&&e.indexOf(s)<0&&(t[s]=r[s]);if(r!=null&&_e)for(var s of _e(r))e.indexOf(s)<0&&ut.call(r,s)&&(t[s]=r[s]);return t};var Ve=(r,e,t)=>e.has(r)||dt("Cannot "+t);var n=(r,e,t)=>(Ve(r,e,"read from private field"),t?t.call(r):e.get(r)),p=(r,e,t)=>e.has(r)?dt("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t),h=(r,e,t,s)=>(Ve(r,e,"write to private field"),s?s.call(r,t):e.set(r,t),t),u=(r,e,t)=>(Ve(r,e,"access private method"),t);var je=(r,e,t,s)=>({set _(a){h(r,e,a,t)},get _(){return n(r,e,s)}});var g=(r,e,t)=>new Promise((s,a)=>{var o=f=>{try{c(t.next(f))}catch(d){a(d)}},i=f=>{try{c(t.throw(f))}catch(d){a(d)}},c=f=>f.done?s(f.value):Promise.resolve(f.value).then(o,i);c((t=t.apply(r,e)).next())});var y=class r extends Error{constructor(t,s,a,o,i,c){super(c||`HTTP Error ${t} at ${i}: ${s!=null?s:JSON.stringify(a)}`);this.url=i;this.name="FetchError",this.status=t,this.text=s,this.json=a,this.headers=o}static fromResponse(t,s){return g(this,null,function*(){let a=t.status,o=Object.fromEntries([...t.headers.entries()]),i,c,f=t.headers.get("content-type");return t.bodyUsed||(f&&f.includes("application/json")?c=yield t.json():i=yield t.text()),new r(a,i,c,o,s)})}},I=class extends Error{constructor(){super("Fetch with backoff aborted"),this.name="FetchBackoffAbortError"}};var xe=class extends Error{constructor(){super("Invalid shape options: missing required url parameter"),this.name="MissingShapeUrlError"}},we=class extends Error{constructor(){super("Invalid signal option. It must be an instance of AbortSignal."),this.name="InvalidSignalError"}},Te=class extends Error{constructor(){super("shapeHandle is required if this isn't an initial fetch (i.e. offset > -1)"),this.name="MissingShapeHandleError"}},Me=class extends Error{constructor(e){super(`Cannot use reserved Electric parameter names in custom params: ${e.join(", ")}`),this.name="ReservedParamError"}},ve=class extends Error{constructor(e){super(`Column "${e!=null?e:"unknown"}" does not allow NULL values`),this.name="ParserNullValueError"}};var Ce=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(a=>{s+=`- ${a}
1
+ var os=Object.defineProperty,cs=Object.defineProperties;var hs=Object.getOwnPropertyDescriptors;var Ue=Object.getOwnPropertySymbols;var At=Object.prototype.hasOwnProperty,Pt=Object.prototype.propertyIsEnumerable;var _t=r=>{throw TypeError(r)};var bt=(r,e,t)=>e in r?os(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,S=(r,e)=>{for(var t in e||(e={}))At.call(e,t)&&bt(r,t,e[t]);if(Ue)for(var t of Ue(e))Pt.call(e,t)&&bt(r,t,e[t]);return r},ge=(r,e)=>cs(r,hs(e));var xt=(r,e)=>{var t={};for(var s in r)At.call(r,s)&&e.indexOf(s)<0&&(t[s]=r[s]);if(r!=null&&Ue)for(var s of Ue(r))e.indexOf(s)<0&&Pt.call(r,s)&&(t[s]=r[s]);return t};var Ge=(r,e,t)=>e.has(r)||_t("Cannot "+t);var n=(r,e,t)=>(Ge(r,e,"read from private field"),t?t.call(r):e.get(r)),p=(r,e,t)=>e.has(r)?_t("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t),c=(r,e,t,s)=>(Ge(r,e,"write to private field"),s?s.call(r,t):e.set(r,t),t),u=(r,e,t)=>(Ge(r,e,"access private method"),t);var Je=(r,e,t,s)=>({set _(i){c(r,e,i,t)},get _(){return n(r,e,s)}});var g=(r,e,t)=>new Promise((s,i)=>{var o=f=>{try{l(t.next(f))}catch(d){i(d)}},a=f=>{try{l(t.throw(f))}catch(d){i(d)}},l=f=>f.done?s(f.value):Promise.resolve(f.value).then(o,a);l((t=t.apply(r,e)).next())});var y=class r extends Error{constructor(t,s,i,o,a,l){super(l||`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 fromResponse(t,s){return g(this,null,function*(){let i=t.status,o=Object.fromEntries([...t.headers.entries()]),a,l,f=t.headers.get("content-type");return t.bodyUsed||(f&&f.includes("application/json")?l=yield t.json():a=yield t.text()),new r(i,a,l,o,s)})}},U=class extends Error{constructor(){super("Fetch with backoff aborted"),this.name="FetchBackoffAbortError"}};var ke=class extends Error{constructor(){super("Invalid shape options: missing required url parameter"),this.name="MissingShapeUrlError"}},Oe=class extends Error{constructor(){super("Invalid signal option. It must be an instance of AbortSignal."),this.name="InvalidSignalError"}},He=class extends Error{constructor(){super("shapeHandle is required if this isn't an initial fetch (i.e. offset > -1)"),this.name="MissingShapeHandleError"}},Le=class extends Error{constructor(e){super(`Cannot use reserved Electric parameter names in custom params: ${e.join(", ")}`),this.name="ReservedParamError"}},De=class extends Error{constructor(e){super(`Column "${e!=null?e:"unknown"}" does not allow NULL values`),this.name="ParserNullValueError"}};var Ie=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}
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)}};var Ue=r=>Number(r),Jt=r=>r==="true"||r==="t",zt=r=>BigInt(r),mt=r=>JSON.parse(r),Xt=r=>r,Zt={int2:Ue,int4:Ue,int8:zt,bool:Jt,float4:Ue,float8:Ue,json:mt,jsonb:mt};function es(r,e){let t=0,s=null,a="",o=!1,i=0,c;function f(m,E,Q){let S=m.slice(E,Q);return S=S==="NULL"?null:S,e?e(S):S}function d(m){let E=[];for(;t<m.length;t++){if(s=m[t],o)s==="\\"?a+=m[++t]:s==='"'?(E.push(e?e(a):a),a="",o=m[t+1]==='"',i=t+2):a+=s;else if(s==='"')o=!0;else if(s==="{")i=++t,E.push(d(m));else if(s==="}"){o=!1,i<t&&E.push(f(m,i,t)),i=t+1;break}else s===","&&c!=="}"&&c!=='"'&&(E.push(f(m,i,t)),i=t+1);c=s}return i<t&&E.push(E.push(f(m,i,t+1))),E}return d(r)[0]}var ke=class{constructor(e,t){this.parser=b(b({},Zt),e),this.transformer=t}parse(e,t){return JSON.parse(e,(s,a)=>{if((s==="value"||s==="old_value")&&typeof a=="object"&&a!==null){let o=a;Object.keys(o).forEach(i=>{o[i]=this.parseRow(i,o[i],t)}),this.transformer&&(a=this.transformer(a))}return a})}parseRow(e,t,s){var E;let a=s[e];if(!a)return t;let m=a,{type:o,dims:i}=m,c=pt(m,["type","dims"]),f=(E=this.parser[o])!=null?E:Xt,d=gt(f,a,e);return i&&i>0?gt((S,Ne)=>es(S,d),a,e)(t):d(t,c)}};function gt(r,e,t){var a;let s=!((a=e.not_null)!=null&&a);return o=>{if(o===null){if(!s)throw new ve(t!=null?t:"unknown");return null}return r(o,e)}}function z(r){return"key"in r}function Oe(r){return!z(r)}function Ye(r){return Oe(r)&&r.headers.control==="up-to-date"}function Et(r){let e=r.headers.global_last_seen_lsn;if(e)return`${e}_0`}function Qe(r,e){let t=BigInt(r),s=BigInt(e.xmin),a=BigInt(e.xmax),o=e.xip_list.map(BigInt);return t<s||t<a&&!o.includes(t)}var Rt="electric-cursor",fe="electric-handle",He="electric-offset",St="electric-schema",bt="electric-up-to-date",yt="columns",Le="cursor",Ke="expired_handle",X="handle",v="live",Z="offset",Pt="table",At="where",_t="replica",xt="params",wt="experimental_live_sse",We="force-disconnect-and-refresh",$e="pause-stream",Ge="log",ue="subset__where",de="subset__limit",pe="subset__offset",me="subset__order_by",ge="subset__params",Je=[v,X,Z,Le,Ke,Ge,ue,de,pe,me,ge];var ts=[429],Ie={initialDelay:100,maxDelay:1e4,multiplier:1.3};function Tt(r,e=Ie){let{initialDelay:t,maxDelay:s,multiplier:a,debug:o=!1,onFailedAttempt:i}=e;return(...c)=>g(this,null,function*(){var Q;let f=c[0],d=c[1],m=t,E=0;for(;;)try{let S=yield r(...c);if(S.ok)return S;throw yield y.fromResponse(S,f.toString())}catch(S){if(i==null||i(),(Q=d==null?void 0:d.signal)!=null&&Q.aborted)throw new I;if(S instanceof y&&!ts.includes(S.status)&&S.status>=400&&S.status<500)throw S;yield new Promise(Ne=>setTimeout(Ne,m)),m=Math.min(m*a,s),o&&(E++,console.log(`Retry attempt #${E} after ${m}ms`))}})}var ss=[201,204,205];function Mt(r){return(...e)=>g(this,null,function*(){let t=e[0],s=yield r(...e);try{if(s.status<200||ss.includes(s.status))return s;let a=yield s.text();return new Response(a,s)}catch(a){throw new y(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 rs={maxChunksToPrefetch:2};function vt(r,e=rs){let{maxChunksToPrefetch:t}=e,s;return(...o)=>g(this,null,function*(){let i=o[0].toString(),c=s==null?void 0:s.consume(...o);if(c)return c;s==null||s.abort();let f=yield r(...o),d=Xe(i,f);return d&&(s=new ze({fetchClient:r,maxPrefetchedRequests:t,url:d,requestInit:o[1]})),f})}var ns=["electric-offset","electric-handle"],as=["electric-cursor"],is=["electric-schema"];function Ct(r){return(...e)=>g(this,null,function*(){let t=yield r(...e);if(t.ok){let s=t.headers,a=[],o=m=>a.push(...m.filter(E=>!s.has(E))),c=e[0].toString(),f=new URL(c);if([ue,ge,de,pe,me].some(m=>f.searchParams.has(m)))return t;if(o(ns),f.searchParams.get(v)==="true"&&o(as),(!f.searchParams.has(v)||f.searchParams.get(v)==="false")&&o(is),a.length>0)throw new Ce(c,a)}return t})}var Ee,Re,C,K,U,ee,De,ze=class{constructor(e){p(this,ee);p(this,Ee);p(this,Re);p(this,C,new Map);p(this,K);p(this,U);var t;h(this,Ee,(t=e.fetchClient)!=null?t:(...s)=>fetch(...s)),h(this,Re,e.maxPrefetchedRequests),h(this,K,e.url.toString()),h(this,U,n(this,K)),u(this,ee,De).call(this,e.url,e.requestInit)}abort(){n(this,C).forEach(([e,t])=>t.abort())}consume(...e){var a;let t=e[0].toString(),s=(a=n(this,C).get(t))==null?void 0:a[0];if(!(!s||t!==n(this,K)))return n(this,C).delete(t),s.then(o=>{let i=Xe(t,o);h(this,K,i),n(this,U)&&!n(this,C).has(n(this,U))&&u(this,ee,De).call(this,n(this,U),e[1])}).catch(()=>{}),s}};Ee=new WeakMap,Re=new WeakMap,C=new WeakMap,K=new WeakMap,U=new WeakMap,ee=new WeakSet,De=function(...e){var a,o;let t=e[0].toString();if(n(this,C).size>=n(this,Re))return;let s=new AbortController;try{let{signal:i,cleanup:c}=os(s,(a=e[1])==null?void 0:a.signal),f=n(this,Ee).call(this,t,le(b({},(o=e[1])!=null?o:{}),{signal:i}));n(this,C).set(t,[f,s]),f.then(d=>{if(!d.ok||s.signal.aborted)return;let m=Xe(t,d);if(!m||m===t){h(this,U,void 0);return}return h(this,U,m),u(this,ee,De).call(this,m,e[1])}).catch(()=>{}).finally(c)}catch(i){}};function Xe(r,e){let t=e.headers.get(fe),s=e.headers.get(He),a=e.headers.has(bt);if(!t||!s||a)return;let o=new URL(r);if(!o.searchParams.has(v))return o.searchParams.set(X,t),o.searchParams.set(Z,s),o.searchParams.sort(),o.toString()}function os(r,e){let t=hs;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 hs(){}import{fetchEventSource as cs}from"@microsoft/fetch-event-source";var Ze=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 a=s.reduce((o,i)=>this.data[i].lastUsed<this.data[o].lastUsed?i:o);delete this.data[a]}this.save()}save(){if(typeof localStorage!="undefined")try{localStorage.setItem(this.storageKey,JSON.stringify(this.data))}catch(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()}},et=new Ze;var Be=class{constructor(){this.activeSnapshots=new Map;this.xmaxSnapshots=new Map;this.snapshotsByDatabaseLsn=new Map}addSnapshot(e,t){var o,i,c,f;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=(i=(o=this.xmaxSnapshots.get(BigInt(e.xmax)))==null?void 0:o.add(e.snapshot_mark))!=null?i:new Set([e.snapshot_mark]);this.xmaxSnapshots.set(BigInt(e.xmax),s);let a=(f=(c=this.snapshotsByDatabaseLsn.get(BigInt(e.database_lsn)))==null?void 0:c.add(e.snapshot_mark))!=null?f:new Set([e.snapshot_mark]);this.snapshotsByDatabaseLsn.set(BigInt(e.database_lsn),a)}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[a,o]of this.xmaxSnapshots.entries())if(s>=a)for(let i of o)this.removeSnapshot(i);return[...this.activeSnapshots.values()].some(a=>a.keys.has(e.key)&&Qe(s,a))}lastSeenUpdate(e){for(let[t,s]of this.snapshotsByDatabaseLsn.entries())if(t<=e)for(let a of s)this.removeSnapshot(a)}};var ls=new Set([Le,X,v,Z]);function kt(r){return g(this,null,function*(){return typeof r=="function"?r():r})}function fs(r){return g(this,null,function*(){let e=Object.entries(r),t=yield Promise.all(e.map(o=>g(this,[o],function*([s,a]){if(a===void 0)return[s,void 0];let i=yield kt(a);return[s,Array.isArray(i)?i.join(","):i]})));return Object.fromEntries(t.filter(([s,a])=>a!==void 0))})}function us(r){return g(this,null,function*(){if(!r)return{};let e=Object.entries(r),t=yield Promise.all(e.map(o=>g(this,[o],function*([s,a]){return[s,yield kt(a)]})));return Object.fromEntries(t)})}function Ut(r){let e=new URL(r.origin+r.pathname);for(let[t,s]of r.searchParams)Je.includes(t)||e.searchParams.set(t,s);return e.searchParams.sort(),e.toString()}var ye,te,se,W,B,M,A,k,$,F,w,G,O,_,q,H,re,T,J,L,ne,ae,ie,Pe,N,D,oe,l,Se,be,st,Ot,rt,Fe,Ht,Lt,Dt,nt,at,It,Bt,it,Ft,qt,ot,Nt,tt=class{constructor(e){p(this,l);p(this,ye,null);p(this,te);p(this,se);p(this,W);p(this,B,new Map);p(this,M,!1);p(this,A,"active");p(this,k);p(this,$);p(this,F);p(this,w,!1);p(this,G,!0);p(this,O,!1);p(this,_);p(this,q);p(this,H);p(this,re);p(this,T);p(this,J,!1);p(this,L);p(this,ne);p(this,ae);p(this,ie,Promise.resolve([]));p(this,Pe,new Be);p(this,N,0);p(this,D);p(this,oe);var o,i,c,f;this.options=b({subscribe:!0},e),ds(this.options),h(this,k,(o=this.options.offset)!=null?o:"-1"),h(this,$,""),h(this,_,this.options.handle),h(this,W,new ke(e.parser,e.transformer)),h(this,re,this.options.onError),h(this,q,(i=this.options.log)!=null?i:"full");let t=(c=e.fetchClient)!=null?c:(...d)=>fetch(...d),s=le(b({},(f=e.backoffOptions)!=null?f:Ie),{onFailedAttempt:()=>{var d,m;h(this,O,!1),(m=(d=e.backoffOptions)==null?void 0:d.onFailedAttempt)==null||m.call(d)}}),a=Tt(t,s);h(this,se,Ct(vt(a))),h(this,te,Mt(n(this,se))),u(this,l,qt).call(this)}get shapeHandle(){return n(this,_)}get error(){return n(this,ye)}get isUpToDate(){return n(this,w)}get lastOffset(){return n(this,k)}get mode(){return n(this,q)}subscribe(e,t=()=>{}){let s=Math.random();return n(this,B).set(s,[e,t]),n(this,M)||u(this,l,Se).call(this),()=>{n(this,B).delete(s)}}unsubscribeAll(){n(this,B).clear()}lastSyncedAt(){return n(this,F)}lastSynced(){return n(this,F)===void 0?1/0:Date.now()-n(this,F)}isConnected(){return n(this,O)}isLoading(){return!n(this,w)}hasStarted(){return n(this,M)}isPaused(){return n(this,A)==="paused"}forceDisconnectAndRefresh(){return g(this,null,function*(){var e,t;h(this,J,!0),n(this,w)&&!((e=n(this,T))!=null&&e.signal.aborted)&&((t=n(this,T))==null||t.abort(We)),yield u(this,l,It).call(this),h(this,J,!1)})}requestSnapshot(e){return g(this,null,function*(){if(n(this,q)==="full")throw new Error(`Snapshot requests are not supported in ${n(this,q)} mode, as the consumer is guaranteed to observe all data`);n(this,M)||(yield u(this,l,Se).call(this)),yield u(this,l,Bt).call(this),je(this,N)._++;try{n(this,N)===1&&u(this,l,nt).call(this);let{fetchUrl:t,requestHeaders:s}=yield u(this,l,st).call(this,this.options.url,!0,e),{metadata:a,data:o}=yield u(this,l,Nt).call(this,t,s),i=o.concat([{headers:b({control:"snapshot-end"},a)}]);return n(this,Pe).addSnapshot(a,new Set(o.map(c=>c.key))),u(this,l,Fe).call(this,i,!1),{metadata:a,data:o}}finally{je(this,N)._--,n(this,N)===0&&u(this,l,at).call(this)}})}};ye=new WeakMap,te=new WeakMap,se=new WeakMap,W=new WeakMap,B=new WeakMap,M=new WeakMap,A=new WeakMap,k=new WeakMap,$=new WeakMap,F=new WeakMap,w=new WeakMap,G=new WeakMap,O=new WeakMap,_=new WeakMap,q=new WeakMap,H=new WeakMap,re=new WeakMap,T=new WeakMap,J=new WeakMap,L=new WeakMap,ne=new WeakMap,ae=new WeakMap,ie=new WeakMap,Pe=new WeakMap,N=new WeakMap,D=new WeakMap,oe=new WeakMap,l=new WeakSet,Se=function(){return g(this,null,function*(){var e;h(this,M,!0);try{yield u(this,l,be).call(this)}catch(t){if(h(this,ye,t),n(this,re)){let s=yield n(this,re).call(this,t);typeof s=="object"&&(u(this,l,ot).call(this),"params"in s&&(this.options.params=s.params),"headers"in s&&(this.options.headers=s.headers),h(this,M,!1),u(this,l,Se).call(this));return}throw t}finally{h(this,O,!1),(e=n(this,ae))==null||e.call(this)}})},be=function(){return g(this,null,function*(){var f,d;if(n(this,A)==="pause-requested"){h(this,A,"paused");return}if(!this.options.subscribe&&((f=this.options.signal)!=null&&f.aborted||n(this,w)))return;let e=n(this,A)==="paused";h(this,A,"active");let{url:t,signal:s}=this.options,{fetchUrl:a,requestHeaders:o}=yield u(this,l,st).call(this,t,e),i=yield u(this,l,Ot).call(this,s),c=n(this,T);try{yield u(this,l,Ht).call(this,{fetchUrl:a,requestAbortController:c,headers:o,resumingFromPause:e})}catch(m){if((m instanceof y||m instanceof I)&&c.signal.aborted&&c.signal.reason===We)return u(this,l,be).call(this);if(m instanceof I){c.signal.aborted&&c.signal.reason===$e&&h(this,A,"paused");return}if(!(m instanceof y))throw m;if(m.status==409){if(n(this,_)){let Q=Ut(a);et.markExpired(Q,n(this,_))}let E=m.headers[fe]||`${n(this,_)}-next`;return u(this,l,ot).call(this,E),yield u(this,l,it).call(this,m.json),u(this,l,be).call(this)}else throw u(this,l,Ft).call(this,m),m}finally{i&&s&&s.removeEventListener("abort",i),h(this,T,void 0)}return(d=n(this,ne))==null||d.call(this),u(this,l,be).call(this)})},st=function(e,t,s){return g(this,null,function*(){let[a,o]=yield Promise.all([us(this.options.headers),this.options.params?fs(ps(this.options.params)):void 0]);o&&Vt(o);let i=new URL(e);if(o){o.table&&x(i,Pt,o.table),o.where&&x(i,At,o.where),o.columns&&x(i,yt,o.columns),o.replica&&x(i,_t,o.replica),o.params&&x(i,xt,o.params);let d=b({},o);delete d.table,delete d.where,delete d.columns,delete d.replica,delete d.params;for(let[m,E]of Object.entries(d))x(i,m,E)}s&&(s.where&&x(i,ue,s.where),s.params&&x(i,ge,s.params),s.limit&&x(i,de,s.limit),s.offset&&x(i,pe,s.offset),s.orderBy&&x(i,me,s.orderBy)),i.searchParams.set(Z,n(this,k)),i.searchParams.set(Ge,n(this,q)),n(this,w)&&(!n(this,J)&&!t&&i.searchParams.set(v,"true"),i.searchParams.set(Le,n(this,$))),n(this,_)&&i.searchParams.set(X,n(this,_));let c=Ut(i),f=et.getExpiredHandle(c);return f&&i.searchParams.set(Ke,f),i.searchParams.sort(),{fetchUrl:i,requestHeaders:a}})},Ot=function(e){return g(this,null,function*(){var t;if(h(this,T,new AbortController),e){let s=()=>{var a;(a=n(this,T))==null||a.abort(e.reason)};return e.addEventListener("abort",s,{once:!0}),e.aborted&&((t=n(this,T))==null||t.abort(e.reason)),s}})},rt=function(e){return g(this,null,function*(){var f;let{headers:t,status:s}=e,a=t.get(fe);a&&h(this,_,a);let o=t.get(He);o&&h(this,k,o);let i=t.get(Rt);i&&h(this,$,i);let c=()=>{let d=t.get(St);return d?JSON.parse(d):{}};h(this,H,(f=n(this,H))!=null?f:c()),s===204&&h(this,F,Date.now())})},Fe=function(e,t=!1){return g(this,null,function*(){var s;if(e.length>0){h(this,G,!0);let a=e[e.length-1];if(Ye(a)){if(t){let i=Et(a);i&&h(this,k,i)}h(this,F,Date.now()),h(this,w,!0),h(this,G,!1),(s=n(this,oe))==null||s.call(this)}let o=e.filter(i=>z(i)?!n(this,Pe).shouldRejectMessage(i):!0);yield u(this,l,it).call(this,o)}})},Ht=function(e){return g(this,null,function*(){return n(this,w)&&this.options.experimentalLiveSse&&!n(this,J)&&!e.resumingFromPause?(e.fetchUrl.searchParams.set(wt,"true"),u(this,l,Dt).call(this,e)):u(this,l,Lt).call(this,e)})},Lt=function(e){return g(this,null,function*(){let{fetchUrl:t,requestAbortController:s,headers:a}=e,o=yield n(this,te).call(this,t.toString(),{signal:s.signal,headers:a});h(this,O,!0),yield u(this,l,rt).call(this,o);let i=n(this,H),f=(yield o.text())||"[]",d=n(this,W).parse(f,i);yield u(this,l,Fe).call(this,d)})},Dt=function(e){return g(this,null,function*(){let{fetchUrl:t,requestAbortController:s,headers:a}=e,o=n(this,se);try{let i=[];yield cs(t.toString(),{headers:a,fetch:o,onopen:c=>g(this,null,function*(){h(this,O,!0),yield u(this,l,rt).call(this,c)}),onmessage:c=>{if(c.data){let f=n(this,H),d=n(this,W).parse(c.data,f);i.push(d),Ye(d)&&(u(this,l,Fe).call(this,i,!0),i=[])}},onerror:c=>{throw c},signal:s.signal})}catch(i){throw s.signal.aborted?new I:i}})},nt=function(){var e;n(this,M)&&n(this,A)==="active"&&(h(this,A,"pause-requested"),(e=n(this,T))==null||e.abort($e))},at=function(){n(this,M)&&n(this,A)==="paused"&&u(this,l,Se).call(this)},It=function(){return g(this,null,function*(){return n(this,L)?n(this,L):(h(this,L,new Promise((e,t)=>{h(this,ne,e),h(this,ae,t)})),n(this,L).finally(()=>{h(this,L,void 0),h(this,ne,void 0),h(this,ae,void 0)}),n(this,L))})},Bt=function(){return g(this,null,function*(){if(n(this,G))return n(this,D)?n(this,D):(h(this,D,new Promise(e=>{h(this,oe,e)})),n(this,D).finally(()=>{h(this,D,void 0),h(this,oe,void 0)}),n(this,D))})},it=function(e){return g(this,null,function*(){return h(this,ie,n(this,ie).then(()=>Promise.all(Array.from(n(this,B).values()).map(a=>g(this,[a],function*([t,s]){try{yield t(e)}catch(o){queueMicrotask(()=>{throw o})}}))))),n(this,ie)})},Ft=function(e){n(this,B).forEach(([t,s])=>{s==null||s(e)})},qt=function(){if(typeof document=="object"&&typeof document.hidden=="boolean"&&typeof document.addEventListener=="function"){let e=()=>{document.hidden?u(this,l,nt).call(this):u(this,l,at).call(this)};document.addEventListener("visibilitychange",e)}},ot=function(e){h(this,k,"-1"),h(this,$,""),h(this,_,e),h(this,w,!1),h(this,G,!0),h(this,O,!1),h(this,H,void 0),h(this,N,0)},Nt=function(e,t){return g(this,null,function*(){let s=yield n(this,te).call(this,e.toString(),{headers:t});if(!s.ok)throw new y(s.status,void 0,void 0,Object.fromEntries([...s.headers.entries()]),e.toString());let{metadata:a,data:o}=yield s.json(),i=n(this,W).parse(JSON.stringify(o),n(this,H));return{metadata:a,data:i}})},tt.Replica={FULL:"full",DEFAULT:"default"};function Vt(r){if(!r)return;let e=Object.keys(r).filter(t=>ls.has(t));if(e.length>0)throw new Me(e)}function ds(r){if(!r.url)throw new xe;if(r.signal&&!(r.signal instanceof AbortSignal))throw new we;if(r.offset!==void 0&&r.offset!=="-1"&&r.offset!=="now"&&!r.handle)throw new Te;Vt(r.params)}function x(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,a]of Object.entries(t))r.searchParams.set(`${e}[${s}]`,a);else r.searchParams.set(e,t.toString())}function ps(r){return Array.isArray(r.params)?le(b({},r),{params:Object.fromEntries(r.params.map((e,t)=>[t+1,e]))}):r}var P,V,j,Ae,he,ce,Y,R,Yt,Qt,ht,qe,Kt,ct,jt=class{constructor(e){p(this,R);p(this,P,new Map);p(this,V,new Map);p(this,j,new Set);p(this,Ae,new Set);p(this,he,!1);p(this,ce,"syncing");p(this,Y,!1);this.stream=e,this.stream.subscribe(u(this,R,Yt).bind(this),u(this,R,Kt).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:a})=>{s(),n(this,Y)&&t(n(this,Y)),e(a)})}})}get currentValue(){return n(this,P)}get error(){return n(this,Y)}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}requestSnapshot(e){return g(this,null,function*(){let t=JSON.stringify(e);n(this,Ae).add(t),yield u(this,R,ht).call(this),yield this.stream.requestSnapshot(e)})}subscribe(e){let t=Math.random();return n(this,V).set(t,e),()=>{n(this,V).delete(t)}}unsubscribeAll(){n(this,V).clear()}get numSubscribers(){return n(this,V).size}};P=new WeakMap,V=new WeakMap,j=new WeakMap,Ae=new WeakMap,he=new WeakMap,ce=new WeakMap,Y=new WeakMap,R=new WeakSet,Yt=function(e){let t=!1;e.forEach(s=>{if(z(s))if(t=u(this,R,qe).call(this,"syncing"),this.mode==="full")switch(s.headers.operation){case"insert":n(this,P).set(s.key,s.value);break;case"update":n(this,P).set(s.key,b(b({},n(this,P).get(s.key)),s.value));break;case"delete":n(this,P).delete(s.key);break}else switch(s.headers.operation){case"insert":n(this,j).add(s.key),n(this,P).set(s.key,s.value);break;case"update":n(this,j).has(s.key)&&n(this,P).set(s.key,b(b({},n(this,P).get(s.key)),s.value));break;case"delete":n(this,j).has(s.key)&&(n(this,P).delete(s.key),n(this,j).delete(s.key));break}if(Oe(s))switch(s.headers.control){case"up-to-date":t=u(this,R,qe).call(this,"up-to-date"),n(this,he)&&(h(this,he,!1),u(this,R,Qt).call(this));break;case"must-refetch":n(this,P).clear(),n(this,j).clear(),h(this,Y,!1),t=u(this,R,qe).call(this,"syncing"),h(this,he,!0);break}}),t&&u(this,R,ct).call(this)},Qt=function(){return g(this,null,function*(){yield u(this,R,ht).call(this),yield Promise.all(Array.from(n(this,Ae)).map(e=>g(this,null,function*(){try{let t=JSON.parse(e);yield this.stream.requestSnapshot(t)}catch(t){}})))})},ht=function(){return g(this,null,function*(){this.stream.isUpToDate||(yield new Promise(e=>{let t=()=>{this.stream.isUpToDate&&(clearInterval(s),a(),e())},s=setInterval(t,10),a=this.stream.subscribe(()=>t(),()=>t());t()}))})},qe=function(e){let t=n(this,ce)!==e;return h(this,ce,e),t&&e==="up-to-date"},Kt=function(e){e instanceof y&&(h(this,Y,e),u(this,R,ct).call(this))},ct=function(){n(this,V).forEach(e=>{e({value:this.currentValue,rows:this.currentRows})})};export{Ie as BackoffDefaults,Je as ELECTRIC_PROTOCOL_QUERY_PARAMS,y as FetchError,jt as Shape,tt as ShapeStream,z as isChangeMessage,Oe as isControlMessage,Qe as isVisibleInSnapshot,kt as resolveValue};
5
+ For more information visit the troubleshooting guide: /docs/guides/troubleshooting/missing-headers`,super(s)}};var Be=r=>Number(r),ls=r=>r==="true"||r==="t",fs=r=>BigInt(r),wt=r=>JSON.parse(r),us=r=>r,ds={int2:Be,int4:Be,int8:fs,bool:ls,float4:Be,float8:Be,json:wt,jsonb:wt};function ps(r,e){let t=0,s=null,i="",o=!1,a=0,l;function f(m,E,Z){let b=m.slice(E,Z);return b=b==="NULL"?null:b,e?e(b):b}function d(m){let E=[];for(;t<m.length;t++){if(s=m[t],o)s==="\\"?i+=m[++t]:s==='"'?(E.push(e?e(i):i),i="",o=m[t+1]==='"',a=t+2):i+=s;else if(s==='"')o=!0;else if(s==="{")a=++t,E.push(d(m));else if(s==="}"){o=!1,a<t&&E.push(f(m,a,t)),a=t+1;break}else s===","&&l!=="}"&&l!=='"'&&(E.push(f(m,a,t)),a=t+1);l=s}return a<t&&E.push(E.push(f(m,a,t+1))),E}return d(r)[0]}var Fe=class{constructor(e,t){this.parser=S(S({},ds),e),this.transformer=t}parse(e,t){return JSON.parse(e,(s,i)=>{if((s==="value"||s==="old_value")&&typeof i=="object"&&i!==null){let o=i;Object.keys(o).forEach(a=>{o[a]=this.parseRow(a,o[a],t)}),this.transformer&&(i=this.transformer(i))}return i})}parseRow(e,t,s){var E;let i=s[e];if(!i)return t;let m=i,{type:o,dims:a}=m,l=xt(m,["type","dims"]),f=(E=this.parser[o])!=null?E:us,d=Tt(f,i,e);return a&&a>0?Tt((b,pe)=>ps(b,d),i,e)(t):d(t,l)}};function Tt(r,e,t){var i;let s=!((i=e.not_null)!=null&&i);return o=>{if(o===null){if(!s)throw new De(t!=null?t:"unknown");return null}return r(o,e)}}function te(r){return"key"in r}function Ne(r){return!te(r)}function ze(r){return Ne(r)&&r.headers.control==="up-to-date"}function Mt(r){let e=r.headers.global_last_seen_lsn;if(e)return`${e}_0`}function Xe(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 vt="electric-cursor",Ee="electric-handle",qe="electric-offset",Ct="electric-schema",Ut="electric-up-to-date",kt="columns",Ve="cursor",Ze="expired_handle",se="handle",k="live",re="offset",Ot="table",Ht="where",Lt="replica",Dt="params",It="experimental_live_sse",Bt="live_sse",et="force-disconnect-and-refresh",tt="pause-stream",st="log",Re="subset__where",Se="subset__limit",ye="subset__offset",be="subset__order_by",Ae="subset__params",rt=[k,se,re,Ve,Ze,st,Re,Se,ye,be,Ae];var ms=[429],Ye={initialDelay:100,maxDelay:6e4,multiplier:1.3,maxRetries:1/0,retryBudgetPercent:.1};function Ft(r,e=Ye){let{initialDelay:t,maxDelay:s,multiplier:i,debug:o=!1,onFailedAttempt:a,maxRetries:l=1/0,retryBudgetPercent:f=.1}=e,d=0,m=0,E=Date.now()+6e4;function Z(b){let pe=Date.now();if(pe>E&&(d=0,m=0,E=pe+6e4),d++,d<10)return!0;let K=m/d<b;return K&&m++,K}return(...b)=>g(this,null,function*(){var Et;let pe=b[0],Ce=b[1],K=t,me=0;for(;;)try{let A=yield r(...b);if(A.ok)return K=t,A;throw yield y.fromResponse(A,pe.toString())}catch(A){if(a==null||a(),(Et=Ce==null?void 0:Ce.signal)!=null&&Et.aborted)throw new U;if(A instanceof y&&!ms.includes(A.status)&&A.status>=400&&A.status<500)throw A;{if(me++,me>=l)throw o&&console.log(`Max retries reached (${me}/${l}), giving up`),A;if(!Z(f)){o&&console.log(`Retry budget exhausted (attempt ${me}), backing off`),yield new Promise(C=>setTimeout(C,s));continue}let ee=0;if(A instanceof y&&A.headers){let C=A.headers["retry-after"];if(C){let We=Number(C);if(Number.isFinite(We)&&We>0)ee=We*1e3;else{let yt=Date.parse(C);if(!isNaN(yt)){let as=yt-Date.now();ee=Math.max(0,Math.min(as,36e5))}}}}let is=Math.random()*K,Rt=Math.min(is,s),St=Math.max(ee,Rt);if(o){let C=ee>0?"server+client":"client";console.log(`Retry attempt #${me} after ${St}ms (${C}, serverMin=${ee}ms, clientBackoff=${Rt}ms)`)}yield new Promise(C=>setTimeout(C,St)),K=Math.min(K*i,s)}}})}var gs=[201,204,205];function Nt(r){return(...e)=>g(this,null,function*(){var i,o;let t=e[0],s=yield r(...e);try{if(s.status<200||gs.includes(s.status))return s;let a=yield s.text();return new Response(a,s)}catch(a){throw(o=(i=e[1])==null?void 0:i.signal)!=null&&o.aborted?new U:new y(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 Es={maxChunksToPrefetch:2};function qt(r,e=Es){let{maxChunksToPrefetch:t}=e,s;return(...o)=>g(this,null,function*(){let a=o[0].toString(),l=s==null?void 0:s.consume(...o);if(l)return l;s==null||s.abort();let f=yield r(...o),d=it(a,f);return d&&(s=new nt({fetchClient:r,maxPrefetchedRequests:t,url:d,requestInit:o[1]})),f})}var Rs=["electric-offset","electric-handle"],Ss=["electric-cursor"],ys=["electric-schema"];function Vt(r){return(...e)=>g(this,null,function*(){let t=yield r(...e);if(t.ok){let s=t.headers,i=[],o=m=>i.push(...m.filter(E=>!s.has(E))),l=e[0].toString(),f=new URL(l);if([Re,Ae,Se,ye,be].some(m=>f.searchParams.has(m)))return t;if(o(Rs),f.searchParams.get(k)==="true"&&o(Ss),(!f.searchParams.has(k)||f.searchParams.get(k)==="false")&&o(ys),i.length>0)throw new Ie(l,i)}return t})}var Pe,_e,O,W,H,ne,je,nt=class{constructor(e){p(this,ne);p(this,Pe);p(this,_e);p(this,O,new Map);p(this,W);p(this,H);var t;c(this,Pe,(t=e.fetchClient)!=null?t:(...s)=>fetch(...s)),c(this,_e,e.maxPrefetchedRequests),c(this,W,e.url.toString()),c(this,H,n(this,W)),u(this,ne,je).call(this,e.url,e.requestInit)}abort(){n(this,O).forEach(([e,t])=>t.abort())}consume(...e){var i;let t=e[0].toString(),s=(i=n(this,O).get(t))==null?void 0:i[0];if(!(!s||t!==n(this,W)))return n(this,O).delete(t),s.then(o=>{let a=it(t,o);c(this,W,a),n(this,H)&&!n(this,O).has(n(this,H))&&u(this,ne,je).call(this,n(this,H),e[1])}).catch(()=>{}),s}};Pe=new WeakMap,_e=new WeakMap,O=new WeakMap,W=new WeakMap,H=new WeakMap,ne=new WeakSet,je=function(...e){var i,o;let t=e[0].toString();if(n(this,O).size>=n(this,_e))return;let s=new AbortController;try{let{signal:a,cleanup:l}=bs(s,(i=e[1])==null?void 0:i.signal),f=n(this,Pe).call(this,t,ge(S({},(o=e[1])!=null?o:{}),{signal:a}));n(this,O).set(t,[f,s]),f.then(d=>{if(!d.ok||s.signal.aborted)return;let m=it(t,d);if(!m||m===t){c(this,H,void 0);return}return c(this,H,m),u(this,ne,je).call(this,m,e[1])}).catch(()=>{}).finally(l)}catch(a){}};function it(r,e){let t=e.headers.get(Ee),s=e.headers.get(qe),i=e.headers.has(Ut);if(!t||!s||i)return;let o=new URL(r);if(!o.searchParams.has(k))return o.searchParams.set(se,t),o.searchParams.set(re,s),o.searchParams.sort(),o.toString()}function bs(r,e){let t=As;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 As(){}import{fetchEventSource as Ps}from"@microsoft/fetch-event-source";var at=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()}},ot=new at;var Qe=class{constructor(){this.activeSnapshots=new Map;this.xmaxSnapshots=new Map;this.snapshotsByDatabaseLsn=new Map}addSnapshot(e,t){var o,a,l,f;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=(f=(l=this.snapshotsByDatabaseLsn.get(BigInt(e.database_lsn)))==null?void 0:l.add(e.snapshot_mark))!=null?f: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)&&Xe(s,i))}lastSeenUpdate(e){for(let[t,s]of this.snapshotsByDatabaseLsn.entries())if(t<=e)for(let i of s)this.removeSnapshot(i)}};var _s=new Set([Ve,se,k,re]);function Yt(r){return g(this,null,function*(){return typeof r=="function"?r():r})}function xs(r){return g(this,null,function*(){let e=Object.entries(r),t=yield Promise.all(e.map(o=>g(this,[o],function*([s,i]){if(i===void 0)return[s,void 0];let a=yield Yt(i);return[s,Array.isArray(a)?a.join(","):a]})));return Object.fromEntries(t.filter(([s,i])=>i!==void 0))})}function ws(r){return g(this,null,function*(){if(!r)return{};let e=Object.entries(r),t=yield Promise.all(e.map(o=>g(this,[o],function*([s,i]){return[s,yield Yt(i)]})));return Object.fromEntries(t)})}function jt(r){let e=new URL(r.origin+r.pathname);for(let[t,s]of r.searchParams)rt.includes(t)||e.searchParams.set(t,s);return e.searchParams.sort(),e.toString()}var Te,ie,ae,G,N,v,_,L,J,q,T,z,D,x,V,I,oe,M,X,B,ce,he,le,Me,j,F,fe,h,xe,we,ht,Qt,lt,$e,$t,Kt,Wt,ft,ut,Gt,Jt,dt,zt,Xt,pt,Zt,ct=class{constructor(e){p(this,h);p(this,Te,null);p(this,ie);p(this,ae);p(this,G);p(this,N,new Map);p(this,v,!1);p(this,_,"active");p(this,L);p(this,J);p(this,q);p(this,T,!1);p(this,z,!0);p(this,D,!1);p(this,x);p(this,V);p(this,I);p(this,oe);p(this,M);p(this,X,!1);p(this,B);p(this,ce);p(this,he);p(this,le,Promise.resolve([]));p(this,Me,new Qe);p(this,j,0);p(this,F);p(this,fe);var o,a,l,f;this.options=S({subscribe:!0},e),Ts(this.options),c(this,L,(o=this.options.offset)!=null?o:"-1"),c(this,J,""),c(this,x,this.options.handle),c(this,G,new Fe(e.parser,e.transformer)),c(this,oe,this.options.onError),c(this,V,(a=this.options.log)!=null?a:"full");let t=(l=e.fetchClient)!=null?l:(...d)=>fetch(...d),s=ge(S({},(f=e.backoffOptions)!=null?f:Ye),{onFailedAttempt:()=>{var d,m;c(this,D,!1),(m=(d=e.backoffOptions)==null?void 0:d.onFailedAttempt)==null||m.call(d)}}),i=Ft(t,s);c(this,ae,Vt(qt(i))),c(this,ie,Nt(n(this,ae))),u(this,h,Xt).call(this)}get shapeHandle(){return n(this,x)}get error(){return n(this,Te)}get isUpToDate(){return n(this,T)}get lastOffset(){return n(this,L)}get mode(){return n(this,V)}subscribe(e,t=()=>{}){let s=Math.random();return n(this,N).set(s,[e,t]),n(this,v)||u(this,h,xe).call(this),()=>{n(this,N).delete(s)}}unsubscribeAll(){n(this,N).clear()}lastSyncedAt(){return n(this,q)}lastSynced(){return n(this,q)===void 0?1/0:Date.now()-n(this,q)}isConnected(){return n(this,D)}isLoading(){return!n(this,T)}hasStarted(){return n(this,v)}isPaused(){return n(this,_)==="paused"}forceDisconnectAndRefresh(){return g(this,null,function*(){var e,t;c(this,X,!0),n(this,T)&&!((e=n(this,M))!=null&&e.signal.aborted)&&((t=n(this,M))==null||t.abort(et)),yield u(this,h,Gt).call(this),c(this,X,!1)})}requestSnapshot(e){return g(this,null,function*(){if(n(this,V)==="full")throw new Error(`Snapshot requests are not supported in ${n(this,V)} mode, as the consumer is guaranteed to observe all data`);n(this,v)||(yield u(this,h,xe).call(this)),yield u(this,h,Jt).call(this),Je(this,j)._++;try{n(this,j)===1&&u(this,h,ft).call(this);let{fetchUrl:t,requestHeaders:s}=yield u(this,h,ht).call(this,this.options.url,!0,e),{metadata:i,data:o}=yield u(this,h,Zt).call(this,t,s),a=o.concat([{headers:S({control:"snapshot-end"},i)}]);return n(this,Me).addSnapshot(i,new Set(o.map(l=>l.key))),u(this,h,$e).call(this,a,!1),{metadata:i,data:o}}finally{Je(this,j)._--,n(this,j)===0&&u(this,h,ut).call(this)}})}};Te=new WeakMap,ie=new WeakMap,ae=new WeakMap,G=new WeakMap,N=new WeakMap,v=new WeakMap,_=new WeakMap,L=new WeakMap,J=new WeakMap,q=new WeakMap,T=new WeakMap,z=new WeakMap,D=new WeakMap,x=new WeakMap,V=new WeakMap,I=new WeakMap,oe=new WeakMap,M=new WeakMap,X=new WeakMap,B=new WeakMap,ce=new WeakMap,he=new WeakMap,le=new WeakMap,Me=new WeakMap,j=new WeakMap,F=new WeakMap,fe=new WeakMap,h=new WeakSet,xe=function(){return g(this,null,function*(){var e;c(this,v,!0);try{yield u(this,h,we).call(this)}catch(t){if(c(this,Te,t),n(this,oe)){let s=yield n(this,oe).call(this,t);typeof s=="object"&&(u(this,h,pt).call(this),"params"in s&&(this.options.params=s.params),"headers"in s&&(this.options.headers=s.headers),c(this,v,!1),u(this,h,xe).call(this));return}throw t}finally{c(this,D,!1),(e=n(this,he))==null||e.call(this)}})},we=function(){return g(this,null,function*(){var f,d;if(n(this,_)==="pause-requested"){c(this,_,"paused");return}if(!this.options.subscribe&&((f=this.options.signal)!=null&&f.aborted||n(this,T)))return;let e=n(this,_)==="paused";c(this,_,"active");let{url:t,signal:s}=this.options,{fetchUrl:i,requestHeaders:o}=yield u(this,h,ht).call(this,t,e),a=yield u(this,h,Qt).call(this,s),l=n(this,M);try{yield u(this,h,$t).call(this,{fetchUrl:i,requestAbortController:l,headers:o,resumingFromPause:e})}catch(m){if((m instanceof y||m instanceof U)&&l.signal.aborted&&l.signal.reason===et)return u(this,h,we).call(this);if(m instanceof U){l.signal.aborted&&l.signal.reason===tt&&c(this,_,"paused");return}if(!(m instanceof y))throw m;if(m.status==409){if(n(this,x)){let Z=jt(i);ot.markExpired(Z,n(this,x))}let E=m.headers[Ee]||`${n(this,x)}-next`;return u(this,h,pt).call(this,E),yield u(this,h,dt).call(this,Array.isArray(m.json)?m.json:[m.json]),u(this,h,we).call(this)}else throw u(this,h,zt).call(this,m),m}finally{a&&s&&s.removeEventListener("abort",a),c(this,M,void 0)}return(d=n(this,ce))==null||d.call(this),u(this,h,we).call(this)})},ht=function(e,t,s){return g(this,null,function*(){let[i,o]=yield Promise.all([ws(this.options.headers),this.options.params?xs(Ms(this.options.params)):void 0]);o&&es(o);let a=new URL(e);if(o){o.table&&w(a,Ot,o.table),o.where&&w(a,Ht,o.where),o.columns&&w(a,kt,o.columns),o.replica&&w(a,Lt,o.replica),o.params&&w(a,Dt,o.params);let d=S({},o);delete d.table,delete d.where,delete d.columns,delete d.replica,delete d.params;for(let[m,E]of Object.entries(d))w(a,m,E)}s&&(s.where&&w(a,Re,s.where),s.params&&w(a,Ae,s.params),s.limit&&w(a,Se,s.limit),s.offset&&w(a,ye,s.offset),s.orderBy&&w(a,be,s.orderBy)),a.searchParams.set(re,n(this,L)),a.searchParams.set(st,n(this,V)),n(this,T)&&(!n(this,X)&&!t&&a.searchParams.set(k,"true"),a.searchParams.set(Ve,n(this,J))),n(this,x)&&a.searchParams.set(se,n(this,x));let l=jt(a),f=ot.getExpiredHandle(l);return f&&a.searchParams.set(Ze,f),a.searchParams.sort(),{fetchUrl:a,requestHeaders:i}})},Qt=function(e){return g(this,null,function*(){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}})},lt=function(e){return g(this,null,function*(){var f;let{headers:t,status:s}=e,i=t.get(Ee);i&&c(this,x,i);let o=t.get(qe);o&&c(this,L,o);let a=t.get(vt);a&&c(this,J,a);let l=()=>{let d=t.get(Ct);return d?JSON.parse(d):{}};c(this,I,(f=n(this,I))!=null?f:l()),s===204&&c(this,q,Date.now())})},$e=function(e,t=!1){return g(this,null,function*(){var s;if(e.length>0){c(this,z,!0);let i=e[e.length-1];if(ze(i)){if(t){let a=Mt(i);a&&c(this,L,a)}c(this,q,Date.now()),c(this,T,!0),c(this,z,!1),(s=n(this,fe))==null||s.call(this)}let o=e.filter(a=>te(a)?!n(this,Me).shouldRejectMessage(a):!0);yield u(this,h,dt).call(this,o)}})},$t=function(e){return g(this,null,function*(){var s;let t=(s=this.options.liveSse)!=null?s:this.options.experimentalLiveSse;return n(this,T)&&t&&!n(this,X)&&!e.resumingFromPause?(e.fetchUrl.searchParams.set(It,"true"),e.fetchUrl.searchParams.set(Bt,"true"),u(this,h,Wt).call(this,e)):u(this,h,Kt).call(this,e)})},Kt=function(e){return g(this,null,function*(){let{fetchUrl:t,requestAbortController:s,headers:i}=e,o=yield n(this,ie).call(this,t.toString(),{signal:s.signal,headers:i});c(this,D,!0),yield u(this,h,lt).call(this,o);let a=n(this,I),f=(yield o.text())||"[]",d=n(this,G).parse(f,a);yield u(this,h,$e).call(this,d)})},Wt=function(e){return g(this,null,function*(){let{fetchUrl:t,requestAbortController:s,headers:i}=e,o=n(this,ae);try{let a=[];yield Ps(t.toString(),{headers:i,fetch:o,onopen:l=>g(this,null,function*(){c(this,D,!0),yield u(this,h,lt).call(this,l)}),onmessage:l=>{if(l.data){let f=n(this,I),d=n(this,G).parse(l.data,f);a.push(d),ze(d)&&(u(this,h,$e).call(this,a,!0),a=[])}},onerror:l=>{throw l},signal:s.signal})}catch(a){throw s.signal.aborted?new U:a}})},ft=function(){var e;n(this,v)&&n(this,_)==="active"&&(c(this,_,"pause-requested"),(e=n(this,M))==null||e.abort(tt))},ut=function(){n(this,v)&&n(this,_)==="paused"&&u(this,h,xe).call(this)},Gt=function(){return g(this,null,function*(){return n(this,B)?n(this,B):(c(this,B,new Promise((e,t)=>{c(this,ce,e),c(this,he,t)})),n(this,B).finally(()=>{c(this,B,void 0),c(this,ce,void 0),c(this,he,void 0)}),n(this,B))})},Jt=function(){return g(this,null,function*(){if(n(this,z))return n(this,F)?n(this,F):(c(this,F,new Promise(e=>{c(this,fe,e)})),n(this,F).finally(()=>{c(this,F,void 0),c(this,fe,void 0)}),n(this,F))})},dt=function(e){return g(this,null,function*(){return c(this,le,n(this,le).then(()=>Promise.all(Array.from(n(this,N).values()).map(i=>g(this,[i],function*([t,s]){try{yield t(e)}catch(o){queueMicrotask(()=>{throw o})}}))))),n(this,le)})},zt=function(e){n(this,N).forEach(([t,s])=>{s==null||s(e)})},Xt=function(){if(typeof document=="object"&&typeof document.hidden=="boolean"&&typeof document.addEventListener=="function"){let e=()=>{document.hidden?u(this,h,ft).call(this):u(this,h,ut).call(this)};document.addEventListener("visibilitychange",e)}},pt=function(e){c(this,L,"-1"),c(this,J,""),c(this,x,e),c(this,T,!1),c(this,z,!0),c(this,D,!1),c(this,I,void 0),c(this,j,0)},Zt=function(e,t){return g(this,null,function*(){let s=yield n(this,ie).call(this,e.toString(),{headers:t});if(!s.ok)throw new y(s.status,void 0,void 0,Object.fromEntries([...s.headers.entries()]),e.toString());let{metadata:i,data:o}=yield s.json(),a=n(this,G).parse(JSON.stringify(o),n(this,I));return{metadata:i,data:a}})},ct.Replica={FULL:"full",DEFAULT:"default"};function es(r){if(!r)return;let e=Object.keys(r).filter(t=>_s.has(t));if(e.length>0)throw new Le(e)}function Ts(r){if(!r.url)throw new ke;if(r.signal&&!(r.signal instanceof AbortSignal))throw new Oe;if(r.offset!==void 0&&r.offset!=="-1"&&r.offset!=="now"&&!r.handle)throw new He;es(r.params)}function w(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 Ms(r){return Array.isArray(r.params)?ge(S({},r),{params:Object.fromEntries(r.params.map((e,t)=>[t+1,e]))}):r}var P,Y,Q,ve,ue,de,$,R,ss,rs,mt,Ke,ns,gt,ts=class{constructor(e){p(this,R);p(this,P,new Map);p(this,Y,new Map);p(this,Q,new Set);p(this,ve,new Set);p(this,ue,!1);p(this,de,"syncing");p(this,$,!1);this.stream=e,this.stream.subscribe(u(this,R,ss).bind(this),u(this,R,ns).bind(this))}get isUpToDate(){return n(this,de)==="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,$)&&t(n(this,$)),e(i)})}})}get currentValue(){return n(this,P)}get error(){return n(this,$)}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}requestSnapshot(e){return g(this,null,function*(){let t=JSON.stringify(e);n(this,ve).add(t),yield u(this,R,mt).call(this),yield this.stream.requestSnapshot(e)})}subscribe(e){let t=Math.random();return n(this,Y).set(t,e),()=>{n(this,Y).delete(t)}}unsubscribeAll(){n(this,Y).clear()}get numSubscribers(){return n(this,Y).size}};P=new WeakMap,Y=new WeakMap,Q=new WeakMap,ve=new WeakMap,ue=new WeakMap,de=new WeakMap,$=new WeakMap,R=new WeakSet,ss=function(e){let t=!1;e.forEach(s=>{if(te(s))if(t=u(this,R,Ke).call(this,"syncing"),this.mode==="full")switch(s.headers.operation){case"insert":n(this,P).set(s.key,s.value);break;case"update":n(this,P).set(s.key,S(S({},n(this,P).get(s.key)),s.value));break;case"delete":n(this,P).delete(s.key);break}else switch(s.headers.operation){case"insert":n(this,Q).add(s.key),n(this,P).set(s.key,s.value);break;case"update":n(this,Q).has(s.key)&&n(this,P).set(s.key,S(S({},n(this,P).get(s.key)),s.value));break;case"delete":n(this,Q).has(s.key)&&(n(this,P).delete(s.key),n(this,Q).delete(s.key));break}if(Ne(s))switch(s.headers.control){case"up-to-date":t=u(this,R,Ke).call(this,"up-to-date"),n(this,ue)&&(c(this,ue,!1),u(this,R,rs).call(this));break;case"must-refetch":n(this,P).clear(),n(this,Q).clear(),c(this,$,!1),t=u(this,R,Ke).call(this,"syncing"),c(this,ue,!0);break}}),t&&u(this,R,gt).call(this)},rs=function(){return g(this,null,function*(){yield u(this,R,mt).call(this),yield Promise.all(Array.from(n(this,ve)).map(e=>g(this,null,function*(){try{let t=JSON.parse(e);yield this.stream.requestSnapshot(t)}catch(t){}})))})},mt=function(){return g(this,null,function*(){this.stream.isUpToDate||(yield new Promise(e=>{let t=()=>{this.stream.isUpToDate&&(clearInterval(s),i(),e())},s=setInterval(t,10),i=this.stream.subscribe(()=>t(),()=>t());t()}))})},Ke=function(e){let t=n(this,de)!==e;return c(this,de,e),t&&e==="up-to-date"},ns=function(e){e instanceof y&&(c(this,$,e),u(this,R,gt).call(this))},gt=function(){n(this,Y).forEach(e=>{e({value:this.currentValue,rows:this.currentRows})})};export{Ye as BackoffDefaults,rt as ELECTRIC_PROTOCOL_QUERY_PARAMS,y as FetchError,ts as Shape,ct as ShapeStream,te as isChangeMessage,Ne as isControlMessage,Xe as isVisibleInSnapshot,Yt as resolveValue};
6
6
  //# sourceMappingURL=index.browser.mjs.map