@electric-sql/client 1.1.2 → 1.1.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.
@@ -135,16 +135,24 @@ interface BackoffOptions {
135
135
  initialDelay: number;
136
136
  /**
137
137
  * Maximum retry delay in milliseconds
138
+ * After reaching this, delay stays constant (e.g., retry every 60s)
138
139
  */
139
140
  maxDelay: number;
140
141
  multiplier: number;
141
142
  onFailedAttempt?: () => void;
142
143
  debug?: boolean;
144
+ /**
145
+ * Maximum number of retry attempts before giving up.
146
+ * Set to Infinity (default) for indefinite retries - needed for offline scenarios
147
+ * where clients may go offline and come back later.
148
+ */
149
+ maxRetries?: number;
143
150
  }
144
151
  declare const BackoffDefaults: {
145
152
  initialDelay: number;
146
153
  maxDelay: number;
147
154
  multiplier: number;
155
+ maxRetries: number;
148
156
  };
149
157
 
150
158
  declare const LIVE_CACHE_BUSTER_QUERY_PARAM = "cursor";
@@ -296,10 +304,51 @@ interface ShapeStreamOptions<T = never> {
296
304
  transformer?: TransformFunction<T>;
297
305
  /**
298
306
  * A function for handling shapestream errors.
299
- * This is optional, when it is not provided any shapestream errors will be thrown.
300
- * If the function returns an object containing parameters and/or headers
301
- * the shapestream will apply those changes and try syncing again.
302
- * If the function returns void the shapestream is stopped.
307
+ *
308
+ * **Automatic retries**: The client automatically retries 5xx server errors, network
309
+ * errors, and 429 rate limits with exponential backoff. The `onError` callback is
310
+ * only invoked after these automatic retries are exhausted, or for non-retryable
311
+ * errors like 4xx client errors.
312
+ *
313
+ * When not provided, non-retryable errors will be thrown and syncing will stop.
314
+ *
315
+ * **Return value behavior**:
316
+ * - Return an **object** (RetryOpts or empty `{}`) to retry syncing:
317
+ * - `{}` - Retry with the same params and headers
318
+ * - `{ params }` - Retry with modified params
319
+ * - `{ headers }` - Retry with modified headers (e.g., refreshed auth token)
320
+ * - `{ params, headers }` - Retry with both modified
321
+ * - Return **void** or **undefined** to stop the stream permanently
322
+ *
323
+ * **Important**: If you want syncing to continue after an error (e.g., to retry
324
+ * on network failures), you MUST return at least an empty object `{}`. Simply
325
+ * logging the error and returning nothing will stop syncing.
326
+ *
327
+ * Supports async functions that return `Promise<void | RetryOpts>`.
328
+ *
329
+ * @example
330
+ * ```typescript
331
+ * // Retry on network errors, stop on others
332
+ * onError: (error) => {
333
+ * console.error('Stream error:', error)
334
+ * if (error instanceof FetchError && error.status >= 500) {
335
+ * return {} // Retry with same params
336
+ * }
337
+ * // Return void to stop on other errors
338
+ * }
339
+ * ```
340
+ *
341
+ * @example
342
+ * ```typescript
343
+ * // Refresh auth token on 401
344
+ * onError: async (error) => {
345
+ * if (error instanceof FetchError && error.status === 401) {
346
+ * const newToken = await refreshAuthToken()
347
+ * return { headers: { Authorization: `Bearer ${newToken}` } }
348
+ * }
349
+ * return {} // Retry other errors
350
+ * }
351
+ * ```
303
352
  */
304
353
  onError?: ShapeStreamErrorHandler;
305
354
  }
@@ -1,6 +1,6 @@
1
- var ts=Object.defineProperty,ss=Object.defineProperties;var rs=Object.getOwnPropertyDescriptors;var Me=Object.getOwnPropertySymbols;var St=Object.prototype.hasOwnProperty,Rt=Object.prototype.propertyIsEnumerable;var bt=n=>{throw TypeError(n)};var Et=(n,e,t)=>e in n?ts(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,S=(n,e)=>{for(var t in e||(e={}))St.call(e,t)&&Et(n,t,e[t]);if(Me)for(var t of Me(e))Rt.call(e,t)&&Et(n,t,e[t]);return n},de=(n,e)=>ss(n,rs(e));var yt=(n,e)=>{var t={};for(var s in n)St.call(n,s)&&e.indexOf(s)<0&&(t[s]=n[s]);if(n!=null&&Me)for(var s of Me(n))e.indexOf(s)<0&&Rt.call(n,s)&&(t[s]=n[s]);return t};var Je=(n,e,t)=>e.has(n)||bt("Cannot "+t);var r=(n,e,t)=>(Je(n,e,"read from private field"),t?t.call(n):e.get(n)),l=(n,e,t)=>e.has(n)?bt("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(n):e.set(n,t),h=(n,e,t,s)=>(Je(n,e,"write to private field"),s?s.call(n,t):e.set(n,t),t),d=(n,e,t)=>(Je(n,e,"access private method"),t);var ve=(n,e,t,s)=>({set _(a){h(n,e,a,t)},get _(){return r(n,e,s)}});var g=(n,e,t)=>new Promise((s,a)=>{var o=u=>{try{c(t.next(u))}catch(p){a(p)}},i=u=>{try{c(t.throw(u))}catch(p){a(p)}},c=u=>u.done?s(u.value):Promise.resolve(u.value).then(o,i);c((t=t.apply(n,e)).next())});var y=class n 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,u=t.headers.get("content-type");return t.bodyUsed||(u&&u.includes("application/json")?c=yield t.json():i=yield t.text()),new n(a,i,c,o,s)})}},C=class extends Error{constructor(){super("Fetch with backoff aborted"),this.name="FetchBackoffAbortError"}};var Ce=class extends Error{constructor(){super("Invalid shape options: missing required url parameter"),this.name="MissingShapeUrlError"}},Ue=class extends Error{constructor(){super("Invalid signal option. It must be an instance of AbortSignal."),this.name="InvalidSignalError"}},ke=class extends Error{constructor(){super("shapeHandle is required if this isn't an initial fetch (i.e. offset > -1)"),this.name="MissingShapeHandleError"}},Oe=class extends Error{constructor(e){super(`Cannot use reserved Electric parameter names in custom params: ${e.join(", ")}`),this.name="ReservedParamError"}},He=class extends Error{constructor(e){super(`Column "${e!=null?e:"unknown"}" does not allow NULL values`),this.name="ParserNullValueError"}};var Le=class extends Error{constructor(e,t){let s=`The response for the shape request to ${e} didn't include the following required headers:
1
+ var os=Object.defineProperty,cs=Object.defineProperties;var hs=Object.getOwnPropertyDescriptors;var ke=Object.getOwnPropertySymbols;var _t=Object.prototype.hasOwnProperty,xt=Object.prototype.propertyIsEnumerable;var wt=n=>{throw TypeError(n)};var Pt=(n,e,t)=>e in n?os(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,S=(n,e)=>{for(var t in e||(e={}))_t.call(e,t)&&Pt(n,t,e[t]);if(ke)for(var t of ke(e))xt.call(e,t)&&Pt(n,t,e[t]);return n},pe=(n,e)=>cs(n,hs(e));var Tt=(n,e)=>{var t={};for(var s in n)_t.call(n,s)&&e.indexOf(s)<0&&(t[s]=n[s]);if(n!=null&&ke)for(var s of ke(n))e.indexOf(s)<0&&xt.call(n,s)&&(t[s]=n[s]);return t};var Ze=(n,e,t)=>e.has(n)||wt("Cannot "+t);var r=(n,e,t)=>(Ze(n,e,"read from private field"),t?t.call(n):e.get(n)),l=(n,e,t)=>e.has(n)?wt("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(n):e.set(n,t),c=(n,e,t,s)=>(Ze(n,e,"write to private field"),s?s.call(n,t):e.set(n,t),t),d=(n,e,t)=>(Ze(n,e,"access private method"),t);var Ue=(n,e,t,s)=>({set _(a){c(n,e,a,t)},get _(){return r(n,e,s)}});var g=(n,e,t)=>new Promise((s,a)=>{var o=f=>{try{h(t.next(f))}catch(p){a(p)}},i=f=>{try{h(t.throw(f))}catch(p){a(p)}},h=f=>f.done?s(f.value):Promise.resolve(f.value).then(o,i);h((t=t.apply(n,e)).next())});var A=class n extends Error{constructor(t,s,a,o,i,h){super(h||`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,h,f=t.headers.get("content-type");return t.bodyUsed||(f&&f.includes("application/json")?h=yield t.json():i=yield t.text()),new n(a,i,h,o,s)})}},U=class extends Error{constructor(){super("Fetch with backoff aborted"),this.name="FetchBackoffAbortError"}};var Oe=class extends Error{constructor(){super("Invalid shape options: missing required url parameter"),this.name="MissingShapeUrlError"}},He=class extends Error{constructor(){super("Invalid signal option. It must be an instance of AbortSignal."),this.name="InvalidSignalError"}},Le=class extends Error{constructor(){super("shapeHandle is required if this isn't an initial fetch (i.e. offset > -1)"),this.name="MissingShapeHandleError"}},De=class extends Error{constructor(e){super(`Cannot use reserved Electric parameter names in custom params: ${e.join(", ")}`),this.name="ReservedParamError"}},Ie=class extends Error{constructor(e){super(`Column "${e!=null?e:"unknown"}" does not allow NULL values`),this.name="ParserNullValueError"}};var Be=class extends Error{constructor(e,t){let s=`The response for the shape request to ${e} didn't include the following required headers:
2
2
  `;t.forEach(a=>{s+=`- ${a}
3
3
  `}),s+=`
4
4
  This is often due to a proxy not setting CORS correctly so that all Electric headers can be read by the client.`,s+=`
5
- For more information visit the troubleshooting guide: /docs/guides/troubleshooting/missing-headers`,super(s)}};var De=n=>Number(n),ns=n=>n==="true"||n==="t",is=n=>BigInt(n),At=n=>JSON.parse(n),as=n=>n,os={int2:De,int4:De,int8:is,bool:ns,float4:De,float8:De,json:At,jsonb:At};function hs(n,e){let t=0,s=null,a="",o=!1,i=0,c;function u(m,E,W){let b=m.slice(E,W);return b=b==="NULL"?null:b,e?e(b):b}function p(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(p(m));else if(s==="}"){o=!1,i<t&&E.push(u(m,i,t)),i=t+1;break}else s===","&&c!=="}"&&c!=='"'&&(E.push(u(m,i,t)),i=t+1);c=s}return i<t&&E.push(E.push(u(m,i,t+1))),E}return p(n)[0]}var Ie=class{constructor(e,t){this.parser=S(S({},os),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=yt(m,["type","dims"]),u=(E=this.parser[o])!=null?E:as,p=Pt(u,a,e);return i&&i>0?Pt((b,Ge)=>hs(b,p),a,e)(t):p(t,c)}};function Pt(n,e,t){var a;let s=!((a=e.not_null)!=null&&a);return o=>{if(o===null){if(!s)throw new He(t!=null?t:"unknown");return null}return n(o,e)}}function Z(n){return"key"in n}function Be(n){return!Z(n)}function ze(n){return Be(n)&&n.headers.control==="up-to-date"}function _t(n){let e=n.headers.global_last_seen_lsn;if(e)return`${e}_0`}function Xe(n,e){let t=BigInt(n),s=BigInt(e.xmin),a=BigInt(e.xmax),o=e.xip_list.map(BigInt);return t<s||t<a&&!o.includes(t)}var xt="electric-cursor",pe="electric-handle",Fe="electric-offset",wt="electric-schema",Tt="electric-up-to-date",Mt="columns",qe="cursor",Ze="expired_handle",ee="handle",U="live",te="offset",vt="table",Ct="where",Ut="replica",kt="params",Ot="experimental_live_sse",Ht="live_sse",et="force-disconnect-and-refresh",tt="pause-stream",st="log",me="subset__where",ge="subset__limit",Ee="subset__offset",Se="subset__order_by",Re="subset__params",rt=[U,ee,te,qe,Ze,st,me,ge,Ee,Se,Re];var cs=[429],Ve={initialDelay:100,maxDelay:1e4,multiplier:1.3};function Lt(n,e=Ve){let{initialDelay:t,maxDelay:s,multiplier:a,debug:o=!1,onFailedAttempt:i}=e;return(...c)=>g(this,null,function*(){var W;let u=c[0],p=c[1],m=t,E=0;for(;;)try{let b=yield n(...c);if(b.ok)return b;throw yield y.fromResponse(b,u.toString())}catch(b){if(i==null||i(),(W=p==null?void 0:p.signal)!=null&&W.aborted)throw new C;if(b instanceof y&&!cs.includes(b.status)&&b.status>=400&&b.status<500)throw b;yield new Promise(Ge=>setTimeout(Ge,m)),m=Math.min(m*a,s),o&&(E++,console.log(`Retry attempt #${E} after ${m}ms`))}})}var ls=[201,204,205];function Dt(n){return(...e)=>g(this,null,function*(){var a,o;let t=e[0],s=yield n(...e);try{if(s.status<200||ls.includes(s.status))return s;let i=yield s.text();return new Response(i,s)}catch(i){throw(o=(a=e[1])==null?void 0:a.signal)!=null&&o.aborted?new C:new y(s.status,void 0,void 0,Object.fromEntries([...s.headers.entries()]),t.toString(),i instanceof Error?i.message:typeof i=="string"?i:"failed to read body")}})}var fs={maxChunksToPrefetch:2};function It(n,e=fs){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 u=yield n(...o),p=it(i,u);return p&&(s=new nt({fetchClient:n,maxPrefetchedRequests:t,url:p,requestInit:o[1]})),u})}var us=["electric-offset","electric-handle"],ds=["electric-cursor"],ps=["electric-schema"];function Bt(n){return(...e)=>g(this,null,function*(){let t=yield n(...e);if(t.ok){let s=t.headers,a=[],o=m=>a.push(...m.filter(E=>!s.has(E))),c=e[0].toString(),u=new URL(c);if([me,Re,ge,Ee,Se].some(m=>u.searchParams.has(m)))return t;if(o(us),u.searchParams.get(U)==="true"&&o(ds),(!u.searchParams.has(U)||u.searchParams.get(U)==="false")&&o(ps),a.length>0)throw new Le(c,a)}return t})}var be,ye,k,$,O,se,Ne,nt=class{constructor(e){l(this,se);l(this,be);l(this,ye);l(this,k,new Map);l(this,$);l(this,O);var t;h(this,be,(t=e.fetchClient)!=null?t:(...s)=>fetch(...s)),h(this,ye,e.maxPrefetchedRequests),h(this,$,e.url.toString()),h(this,O,r(this,$)),d(this,se,Ne).call(this,e.url,e.requestInit)}abort(){r(this,k).forEach(([e,t])=>t.abort())}consume(...e){var a;let t=e[0].toString(),s=(a=r(this,k).get(t))==null?void 0:a[0];if(!(!s||t!==r(this,$)))return r(this,k).delete(t),s.then(o=>{let i=it(t,o);h(this,$,i),r(this,O)&&!r(this,k).has(r(this,O))&&d(this,se,Ne).call(this,r(this,O),e[1])}).catch(()=>{}),s}};be=new WeakMap,ye=new WeakMap,k=new WeakMap,$=new WeakMap,O=new WeakMap,se=new WeakSet,Ne=function(...e){var a,o;let t=e[0].toString();if(r(this,k).size>=r(this,ye))return;let s=new AbortController;try{let{signal:i,cleanup:c}=ms(s,(a=e[1])==null?void 0:a.signal),u=r(this,be).call(this,t,de(S({},(o=e[1])!=null?o:{}),{signal:i}));r(this,k).set(t,[u,s]),u.then(p=>{if(!p.ok||s.signal.aborted)return;let m=it(t,p);if(!m||m===t){h(this,O,void 0);return}return h(this,O,m),d(this,se,Ne).call(this,m,e[1])}).catch(()=>{}).finally(c)}catch(i){}};function it(n,e){let t=e.headers.get(pe),s=e.headers.get(Fe),a=e.headers.has(Tt);if(!t||!s||a)return;let o=new URL(n);if(!o.searchParams.has(U))return o.searchParams.set(ee,t),o.searchParams.set(te,s),o.searchParams.sort(),o.toString()}function ms(n,e){let t=gs;if(e)if(e.aborted)n.abort();else{let s=()=>n.abort();e.addEventListener("abort",s,{once:!0,signal:n.signal}),t=()=>e.removeEventListener("abort",s)}return{signal:n.signal,cleanup:t}}function gs(){}import{fetchEventSource as Es}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 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()}},ot=new at;var Ye=class{constructor(){this.activeSnapshots=new Map;this.xmaxSnapshots=new Map;this.snapshotsByDatabaseLsn=new Map}addSnapshot(e,t){var o,i,c,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=(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=(u=(c=this.snapshotsByDatabaseLsn.get(BigInt(e.database_lsn)))==null?void 0:c.add(e.snapshot_mark))!=null?u: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)&&Xe(s,a))}lastSeenUpdate(e){for(let[t,s]of this.snapshotsByDatabaseLsn.entries())if(t<=e)for(let a of s)this.removeSnapshot(a)}};var Ss=new Set([qe,ee,U,te]);function qt(n){return g(this,null,function*(){return typeof n=="function"?n():n})}function Rs(n){return g(this,null,function*(){let e=Object.entries(n),t=yield Promise.all(e.map(o=>g(this,[o],function*([s,a]){if(a===void 0)return[s,void 0];let i=yield qt(a);return[s,Array.isArray(i)?i.join(","):i]})));return Object.fromEntries(t.filter(([s,a])=>a!==void 0))})}function bs(n){return g(this,null,function*(){if(!n)return{};let e=Object.entries(n),t=yield Promise.all(e.map(o=>g(this,[o],function*([s,a]){return[s,yield qt(a)]})));return Object.fromEntries(t)})}function Ft(n){let e=new URL(n.origin+n.pathname);for(let[t,s]of n.searchParams)rt.includes(t)||e.searchParams.set(t,s);return e.searchParams.sort(),e.toString()}var re,ne,ie,G,B,v,P,H,J,F,w,z,T,_,q,L,ae,M,X,D,oe,N,he,_e,V,I,ce,xe,we,Y,Qe,le,Ke,We,f,Ae,Pe,ct,Nt,lt,je,Vt,Yt,jt,ft,ut,Qt,Kt,dt,pt,Wt,$t,Gt,ht=class{constructor(e){l(this,f);l(this,re,null);l(this,ne);l(this,ie);l(this,G);l(this,B,new Map);l(this,v,!1);l(this,P,"active");l(this,H);l(this,J);l(this,F);l(this,w,!1);l(this,z,!0);l(this,T,!1);l(this,_);l(this,q);l(this,L);l(this,ae);l(this,M);l(this,X,!1);l(this,D);l(this,oe);l(this,N);l(this,he,Promise.resolve([]));l(this,_e,new Ye);l(this,V,0);l(this,I);l(this,ce);l(this,xe);l(this,we,1e3);l(this,Y,0);l(this,Qe,3);l(this,le,!1);l(this,Ke,100);l(this,We,5e3);var o,i,c,u;this.options=S({subscribe:!0},e),ys(this.options),h(this,H,(o=this.options.offset)!=null?o:"-1"),h(this,J,""),h(this,_,this.options.handle),h(this,G,new Ie(e.parser,e.transformer)),h(this,ae,this.options.onError),h(this,q,(i=this.options.log)!=null?i:"full");let t=(c=e.fetchClient)!=null?c:(...p)=>fetch(...p),s=de(S({},(u=e.backoffOptions)!=null?u:Ve),{onFailedAttempt:()=>{var p,m;h(this,T,!1),(m=(p=e.backoffOptions)==null?void 0:p.onFailedAttempt)==null||m.call(p)}}),a=Lt(t,s);h(this,ie,Bt(It(a))),h(this,ne,Dt(r(this,ie))),d(this,f,Wt).call(this)}get shapeHandle(){return r(this,_)}get error(){return r(this,re)}get isUpToDate(){return r(this,w)}get lastOffset(){return r(this,H)}get mode(){return r(this,q)}subscribe(e,t=()=>{}){let s=Math.random();return r(this,B).set(s,[e,t]),r(this,v)||d(this,f,Ae).call(this),()=>{r(this,B).delete(s)}}unsubscribeAll(){r(this,B).clear()}lastSyncedAt(){return r(this,F)}lastSynced(){return r(this,F)===void 0?1/0:Date.now()-r(this,F)}isConnected(){return r(this,T)}isLoading(){return!r(this,w)}hasStarted(){return r(this,v)}isPaused(){return r(this,P)==="paused"}forceDisconnectAndRefresh(){return g(this,null,function*(){var e,t;h(this,X,!0),r(this,w)&&!((e=r(this,M))!=null&&e.signal.aborted)&&((t=r(this,M))==null||t.abort(et)),yield d(this,f,Qt).call(this),h(this,X,!1)})}requestSnapshot(e){return g(this,null,function*(){if(r(this,q)==="full")throw new Error(`Snapshot requests are not supported in ${r(this,q)} mode, as the consumer is guaranteed to observe all data`);r(this,v)||(yield d(this,f,Ae).call(this)),yield d(this,f,Kt).call(this),ve(this,V)._++;try{r(this,V)===1&&d(this,f,ft).call(this);let{fetchUrl:t,requestHeaders:s}=yield d(this,f,ct).call(this,this.options.url,!0,e),{metadata:a,data:o}=yield d(this,f,Gt).call(this,t,s),i=o.concat([{headers:S({control:"snapshot-end"},a)}]);return r(this,_e).addSnapshot(a,new Set(o.map(c=>c.key))),d(this,f,je).call(this,i,!1),{metadata:a,data:o}}finally{ve(this,V)._--,r(this,V)===0&&d(this,f,ut).call(this)}})}};re=new WeakMap,ne=new WeakMap,ie=new WeakMap,G=new WeakMap,B=new WeakMap,v=new WeakMap,P=new WeakMap,H=new WeakMap,J=new WeakMap,F=new WeakMap,w=new WeakMap,z=new WeakMap,T=new WeakMap,_=new WeakMap,q=new WeakMap,L=new WeakMap,ae=new WeakMap,M=new WeakMap,X=new WeakMap,D=new WeakMap,oe=new WeakMap,N=new WeakMap,he=new WeakMap,_e=new WeakMap,V=new WeakMap,I=new WeakMap,ce=new WeakMap,xe=new WeakMap,we=new WeakMap,Y=new WeakMap,Qe=new WeakMap,le=new WeakMap,Ke=new WeakMap,We=new WeakMap,f=new WeakSet,Ae=function(){return g(this,null,function*(){var e,t,s,a,o;h(this,v,!0);try{yield d(this,f,Pe).call(this)}catch(i){if(h(this,re,i),r(this,ae)){let c=yield r(this,ae).call(this,i);if(c&&typeof c=="object"){c.params&&(this.options.params=S(S({},(e=this.options.params)!=null?e:{}),c.params)),c.headers&&(this.options.headers=S(S({},(t=this.options.headers)!=null?t:{}),c.headers)),h(this,re,null),h(this,v,!1),yield d(this,f,Ae).call(this);return}i instanceof Error&&d(this,f,pt).call(this,i),h(this,T,!1),(s=r(this,N))==null||s.call(this);return}throw i instanceof Error&&d(this,f,pt).call(this,i),h(this,T,!1),(a=r(this,N))==null||a.call(this),i}h(this,T,!1),(o=r(this,N))==null||o.call(this)})},Pe=function(){return g(this,null,function*(){var u,p;if(r(this,P)==="pause-requested"){h(this,P,"paused");return}if(!this.options.subscribe&&((u=this.options.signal)!=null&&u.aborted||r(this,w)))return;let e=r(this,P)==="paused";h(this,P,"active");let{url:t,signal:s}=this.options,{fetchUrl:a,requestHeaders:o}=yield d(this,f,ct).call(this,t,e),i=yield d(this,f,Nt).call(this,s),c=r(this,M);try{yield d(this,f,Vt).call(this,{fetchUrl:a,requestAbortController:c,headers:o,resumingFromPause:e})}catch(m){if((m instanceof y||m instanceof C)&&c.signal.aborted&&c.signal.reason===et)return d(this,f,Pe).call(this);if(m instanceof C){c.signal.aborted&&c.signal.reason===tt&&h(this,P,"paused");return}if(!(m instanceof y))throw m;if(m.status==409){if(r(this,_)){let W=Ft(a);ot.markExpired(W,r(this,_))}let E=m.headers[pe]||`${r(this,_)}-next`;return d(this,f,$t).call(this,E),yield d(this,f,dt).call(this,Array.isArray(m.json)?m.json:[m.json]),d(this,f,Pe).call(this)}else throw m}finally{i&&s&&s.removeEventListener("abort",i),h(this,M,void 0)}return(p=r(this,oe))==null||p.call(this),d(this,f,Pe).call(this)})},ct=function(e,t,s){return g(this,null,function*(){let[a,o]=yield Promise.all([bs(this.options.headers),this.options.params?Rs(As(this.options.params)):void 0]);o&&Jt(o);let i=new URL(e);if(o){o.table&&x(i,vt,o.table),o.where&&x(i,Ct,o.where),o.columns&&x(i,Mt,o.columns),o.replica&&x(i,Ut,o.replica),o.params&&x(i,kt,o.params);let p=S({},o);delete p.table,delete p.where,delete p.columns,delete p.replica,delete p.params;for(let[m,E]of Object.entries(p))x(i,m,E)}s&&(s.where&&x(i,me,s.where),s.params&&x(i,Re,s.params),s.limit&&x(i,ge,s.limit),s.offset&&x(i,Ee,s.offset),s.orderBy&&x(i,Se,s.orderBy)),i.searchParams.set(te,r(this,H)),i.searchParams.set(st,r(this,q)),r(this,w)&&(!r(this,X)&&!t&&i.searchParams.set(U,"true"),i.searchParams.set(qe,r(this,J))),r(this,_)&&i.searchParams.set(ee,r(this,_));let c=Ft(i),u=ot.getExpiredHandle(c);return u&&i.searchParams.set(Ze,u),i.searchParams.sort(),{fetchUrl:i,requestHeaders:a}})},Nt=function(e){return g(this,null,function*(){var t;if(h(this,M,new AbortController),e){let s=()=>{var a;(a=r(this,M))==null||a.abort(e.reason)};return e.addEventListener("abort",s,{once:!0}),e.aborted&&((t=r(this,M))==null||t.abort(e.reason)),s}})},lt=function(e){return g(this,null,function*(){var u;let{headers:t,status:s}=e,a=t.get(pe);a&&h(this,_,a);let o=t.get(Fe);o&&h(this,H,o);let i=t.get(xt);i&&h(this,J,i);let c=()=>{let p=t.get(wt);return p?JSON.parse(p):{}};h(this,L,(u=r(this,L))!=null?u:c()),s===204&&h(this,F,Date.now())})},je=function(e,t=!1){return g(this,null,function*(){var s;if(e.length>0){h(this,z,!0);let a=e[e.length-1];if(ze(a)){if(t){let i=_t(a);i&&h(this,H,i)}h(this,F,Date.now()),h(this,w,!0),h(this,z,!1),(s=r(this,ce))==null||s.call(this)}let o=e.filter(i=>Z(i)?!r(this,_e).shouldRejectMessage(i):!0);yield d(this,f,dt).call(this,o)}})},Vt=function(e){return g(this,null,function*(){var s;let t=(s=this.options.liveSse)!=null?s:this.options.experimentalLiveSse;return r(this,w)&&t&&!r(this,X)&&!e.resumingFromPause&&!r(this,le)?(e.fetchUrl.searchParams.set(Ot,"true"),e.fetchUrl.searchParams.set(Ht,"true"),d(this,f,jt).call(this,e)):d(this,f,Yt).call(this,e)})},Yt=function(e){return g(this,null,function*(){let{fetchUrl:t,requestAbortController:s,headers:a}=e,o=yield r(this,ne).call(this,t.toString(),{signal:s.signal,headers:a});h(this,T,!0),yield d(this,f,lt).call(this,o);let i=r(this,L),u=(yield o.text())||"[]",p=r(this,G).parse(u,i);yield d(this,f,je).call(this,p)})},jt=function(e){return g(this,null,function*(){let{fetchUrl:t,requestAbortController:s,headers:a}=e,o=r(this,ie);h(this,xe,Date.now());try{let i=[];yield Es(t.toString(),{headers:a,fetch:o,onopen:c=>g(this,null,function*(){h(this,T,!0),yield d(this,f,lt).call(this,c)}),onmessage:c=>{if(c.data){let u=r(this,L),p=r(this,G).parse(c.data,u);i.push(p),ze(p)&&(d(this,f,je).call(this,i,!0),i=[])}},onerror:c=>{throw c},signal:s.signal})}catch(i){throw s.signal.aborted?new C:i}finally{let i=Date.now()-r(this,xe),c=s.signal.aborted;if(i<r(this,we)&&!c)if(ve(this,Y)._++,r(this,Y)>=r(this,Qe))h(this,le,!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 u=Math.min(r(this,We),r(this,Ke)*Math.pow(2,r(this,Y))),p=Math.floor(Math.random()*u);yield new Promise(m=>setTimeout(m,p))}else i>=r(this,we)&&h(this,Y,0)}})},ft=function(){var e;r(this,v)&&r(this,P)==="active"&&(h(this,P,"pause-requested"),(e=r(this,M))==null||e.abort(tt))},ut=function(){r(this,v)&&r(this,P)==="paused"&&d(this,f,Ae).call(this)},Qt=function(){return g(this,null,function*(){return r(this,D)?r(this,D):(h(this,D,new Promise((e,t)=>{h(this,oe,e),h(this,N,t)})),r(this,D).finally(()=>{h(this,D,void 0),h(this,oe,void 0),h(this,N,void 0)}),r(this,D))})},Kt=function(){return g(this,null,function*(){if(r(this,z))return r(this,I)?r(this,I):(h(this,I,new Promise(e=>{h(this,ce,e)})),r(this,I).finally(()=>{h(this,I,void 0),h(this,ce,void 0)}),r(this,I))})},dt=function(e){return g(this,null,function*(){return h(this,he,r(this,he).then(()=>Promise.all(Array.from(r(this,B).values()).map(a=>g(this,[a],function*([t,s]){try{yield t(e)}catch(o){queueMicrotask(()=>{throw o})}}))))),r(this,he)})},pt=function(e){r(this,B).forEach(([t,s])=>{s==null||s(e)})},Wt=function(){if(typeof document=="object"&&typeof document.hidden=="boolean"&&typeof document.addEventListener=="function"){let e=()=>{document.hidden?d(this,f,ft).call(this):d(this,f,ut).call(this)};document.addEventListener("visibilitychange",e)}},$t=function(e){h(this,H,"-1"),h(this,J,""),h(this,_,e),h(this,w,!1),h(this,z,!0),h(this,T,!1),h(this,L,void 0),h(this,V,0),h(this,Y,0),h(this,le,!1)},Gt=function(e,t){return g(this,null,function*(){let s=yield r(this,ne).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=r(this,G).parse(JSON.stringify(o),r(this,L));return{metadata:a,data:i}})},ht.Replica={FULL:"full",DEFAULT:"default"};function Jt(n){if(!n)return;let e=Object.keys(n).filter(t=>Ss.has(t));if(e.length>0)throw new Oe(e)}function ys(n){if(!n.url)throw new Ce;if(n.signal&&!(n.signal instanceof AbortSignal))throw new Ue;if(n.offset!==void 0&&n.offset!=="-1"&&n.offset!=="now"&&!n.handle)throw new ke;Jt(n.params)}function x(n,e,t){if(!(t===void 0||t==null))if(typeof t=="string")n.searchParams.set(e,t);else if(typeof t=="object")for(let[s,a]of Object.entries(t))n.searchParams.set(`${e}[${s}]`,a);else n.searchParams.set(e,t.toString())}function As(n){return Array.isArray(n.params)?de(S({},n),{params:Object.fromEntries(n.params.map((e,t)=>[t+1,e]))}):n}var A,j,Q,Te,fe,ue,K,R,Xt,Zt,mt,$e,es,gt,zt=class{constructor(e){l(this,R);l(this,A,new Map);l(this,j,new Map);l(this,Q,new Set);l(this,Te,new Set);l(this,fe,!1);l(this,ue,"syncing");l(this,K,!1);this.stream=e,this.stream.subscribe(d(this,R,Xt).bind(this),d(this,R,es).bind(this))}get isUpToDate(){return r(this,ue)==="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(),r(this,K)&&t(r(this,K)),e(a)})}})}get currentValue(){return r(this,A)}get error(){return r(this,K)}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);r(this,Te).add(t),yield d(this,R,mt).call(this),yield this.stream.requestSnapshot(e)})}subscribe(e){let t=Math.random();return r(this,j).set(t,e),()=>{r(this,j).delete(t)}}unsubscribeAll(){r(this,j).clear()}get numSubscribers(){return r(this,j).size}};A=new WeakMap,j=new WeakMap,Q=new WeakMap,Te=new WeakMap,fe=new WeakMap,ue=new WeakMap,K=new WeakMap,R=new WeakSet,Xt=function(e){let t=!1;e.forEach(s=>{if(Z(s))if(t=d(this,R,$e).call(this,"syncing"),this.mode==="full")switch(s.headers.operation){case"insert":r(this,A).set(s.key,s.value);break;case"update":r(this,A).set(s.key,S(S({},r(this,A).get(s.key)),s.value));break;case"delete":r(this,A).delete(s.key);break}else switch(s.headers.operation){case"insert":r(this,Q).add(s.key),r(this,A).set(s.key,s.value);break;case"update":r(this,Q).has(s.key)&&r(this,A).set(s.key,S(S({},r(this,A).get(s.key)),s.value));break;case"delete":r(this,Q).has(s.key)&&(r(this,A).delete(s.key),r(this,Q).delete(s.key));break}if(Be(s))switch(s.headers.control){case"up-to-date":t=d(this,R,$e).call(this,"up-to-date"),r(this,fe)&&(h(this,fe,!1),d(this,R,Zt).call(this));break;case"must-refetch":r(this,A).clear(),r(this,Q).clear(),h(this,K,!1),t=d(this,R,$e).call(this,"syncing"),h(this,fe,!0);break}}),t&&d(this,R,gt).call(this)},Zt=function(){return g(this,null,function*(){yield d(this,R,mt).call(this),yield Promise.all(Array.from(r(this,Te)).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),a(),e())},s=setInterval(t,10),a=this.stream.subscribe(()=>t(),()=>t());t()}))})},$e=function(e){let t=r(this,ue)!==e;return h(this,ue,e),t&&e==="up-to-date"},es=function(e){e instanceof y&&(h(this,K,e),d(this,R,gt).call(this))},gt=function(){r(this,j).forEach(e=>{e({value:this.currentValue,rows:this.currentRows})})};export{Ve as BackoffDefaults,rt as ELECTRIC_PROTOCOL_QUERY_PARAMS,y as FetchError,zt as Shape,ht as ShapeStream,Z as isChangeMessage,Be as isControlMessage,Xe as isVisibleInSnapshot,qt as resolveValue};
5
+ For more information visit the troubleshooting guide: /docs/guides/troubleshooting/missing-headers`,super(s)}};var Fe=n=>Number(n),ls=n=>n==="true"||n==="t",fs=n=>BigInt(n),Mt=n=>JSON.parse(n),us=n=>n,ds={int2:Fe,int4:Fe,int8:fs,bool:ls,float4:Fe,float8:Fe,json:Mt,jsonb:Mt};function ps(n,e){let t=0,s=null,a="",o=!1,i=0,h;function f(m,E,k){let v=m.slice(E,k);return v=v==="NULL"?null:v,e?e(v):v}function p(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(p(m));else if(s==="}"){o=!1,i<t&&E.push(f(m,i,t)),i=t+1;break}else s===","&&h!=="}"&&h!=='"'&&(E.push(f(m,i,t)),i=t+1);h=s}return i<t&&E.push(E.push(f(m,i,t+1))),E}return p(n)[0]}var qe=class{constructor(e,t){this.parser=S(S({},ds),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,h=Tt(m,["type","dims"]),f=(E=this.parser[o])!=null?E:us,p=vt(f,a,e);return i&&i>0?vt((v,y)=>ps(v,p),a,e)(t):p(t,h)}};function vt(n,e,t){var a;let s=!((a=e.not_null)!=null&&a);return o=>{if(o===null){if(!s)throw new Ie(t!=null?t:"unknown");return null}return n(o,e)}}function ee(n){return"key"in n}function Ne(n){return!ee(n)}function et(n){return Ne(n)&&n.headers.control==="up-to-date"}function Ct(n){let e=n.headers.global_last_seen_lsn;if(e)return`${e}_0`}function tt(n,e){let t=BigInt(n),s=BigInt(e.xmin),a=BigInt(e.xmax),o=e.xip_list.map(BigInt);return t<s||t<a&&!o.includes(t)}var kt="electric-cursor",me="electric-handle",Ve="electric-offset",Ut="electric-schema",Ot="electric-up-to-date",Ht="columns",je="cursor",st="expired_handle",te="handle",O="live",se="offset",Lt="table",Dt="where",It="replica",Bt="params",Ft="experimental_live_sse",rt="live_sse",nt="force-disconnect-and-refresh",it="pause-stream",at="log",ge="subset__where",Ee="subset__limit",Se="subset__offset",Re="subset__order_by",be="subset__params",ot=[O,rt,te,se,je,st,at,ge,Ee,Se,Re,be];var ms=[429],Qe={initialDelay:100,maxDelay:6e4,multiplier:1.3,maxRetries:1/0};function gs(n){if(!n)return 0;let e=Number(n);if(Number.isFinite(e)&&e>0)return e*1e3;let t=Date.parse(n);if(!isNaN(t)){let s=t-Date.now();return Math.max(0,Math.min(s,36e5))}return 0}function qt(n,e=Qe){let{initialDelay:t,maxDelay:s,multiplier:a,debug:o=!1,onFailedAttempt:i,maxRetries:h=1/0}=e;return(...f)=>g(this,null,function*(){var v;let p=f[0],m=f[1],E=t,k=0;for(;;)try{let y=yield n(...f);if(y.ok)return y;throw yield A.fromResponse(y,p.toString())}catch(y){if(i==null||i(),(v=m==null?void 0:m.signal)!=null&&v.aborted)throw new U;if(y instanceof A&&!ms.includes(y.status)&&y.status>=400&&y.status<500)throw y;{if(k++,k>h)throw o&&console.log(`Max retries reached (${k}/${h}), giving up`),y;let Ce=y instanceof A&&y.headers?gs(y.headers["retry-after"]):0,as=Math.random()*E,yt=Math.min(as,s),At=Math.max(Ce,yt);if(o){let Xe=Ce>0?"server+client":"client";console.log(`Retry attempt #${k} after ${At}ms (${Xe}, serverMin=${Ce}ms, clientBackoff=${yt}ms)`)}yield new Promise(Xe=>setTimeout(Xe,At)),E=Math.min(E*a,s)}}})}var Es=[201,204,205];function Nt(n){return(...e)=>g(this,null,function*(){var a,o;let t=e[0],s=yield n(...e);try{if(s.status<200||Es.includes(s.status))return s;let i=yield s.text();return new Response(i,s)}catch(i){throw(o=(a=e[1])==null?void 0:a.signal)!=null&&o.aborted?new U:new A(s.status,void 0,void 0,Object.fromEntries([...s.headers.entries()]),t.toString(),i instanceof Error?i.message:typeof i=="string"?i:"failed to read body")}})}var Ss={maxChunksToPrefetch:2};function Vt(n,e=Ss){let{maxChunksToPrefetch:t}=e,s;return(...o)=>g(this,null,function*(){let i=o[0].toString(),h=s==null?void 0:s.consume(...o);if(h)return h;s==null||s.abort();let f=yield n(...o),p=ht(i,f);return p&&(s=new ct({fetchClient:n,maxPrefetchedRequests:t,url:p,requestInit:o[1]})),f})}var Rs=["electric-offset","electric-handle"],bs=["electric-cursor"],ys=["electric-schema"];function jt(n){return(...e)=>g(this,null,function*(){let t=yield n(...e);if(t.ok){let s=t.headers,a=[],o=m=>a.push(...m.filter(E=>!s.has(E))),h=e[0].toString(),f=new URL(h);if([ge,be,Ee,Se,Re].some(m=>f.searchParams.has(m)))return t;if(o(Rs),f.searchParams.get(O)==="true"&&o(bs),(!f.searchParams.has(O)||f.searchParams.get(O)==="false")&&o(ys),a.length>0)throw new Be(h,a)}return t})}var ye,Ae,H,G,L,re,Ye,ct=class{constructor(e){l(this,re);l(this,ye);l(this,Ae);l(this,H,new Map);l(this,G);l(this,L);var t;c(this,ye,(t=e.fetchClient)!=null?t:(...s)=>fetch(...s)),c(this,Ae,e.maxPrefetchedRequests),c(this,G,e.url.toString()),c(this,L,r(this,G)),d(this,re,Ye).call(this,e.url,e.requestInit)}abort(){r(this,H).forEach(([e,t])=>t.abort())}consume(...e){var a;let t=e[0].toString(),s=(a=r(this,H).get(t))==null?void 0:a[0];if(!(!s||t!==r(this,G)))return r(this,H).delete(t),s.then(o=>{let i=ht(t,o);c(this,G,i),r(this,L)&&!r(this,H).has(r(this,L))&&d(this,re,Ye).call(this,r(this,L),e[1])}).catch(()=>{}),s}};ye=new WeakMap,Ae=new WeakMap,H=new WeakMap,G=new WeakMap,L=new WeakMap,re=new WeakSet,Ye=function(...e){var a,o;let t=e[0].toString();if(r(this,H).size>=r(this,Ae))return;let s=new AbortController;try{let{signal:i,cleanup:h}=As(s,(a=e[1])==null?void 0:a.signal),f=r(this,ye).call(this,t,pe(S({},(o=e[1])!=null?o:{}),{signal:i}));r(this,H).set(t,[f,s]),f.then(p=>{if(!p.ok||s.signal.aborted)return;let m=ht(t,p);if(!m||m===t){c(this,L,void 0);return}return c(this,L,m),d(this,re,Ye).call(this,m,e[1])}).catch(()=>{}).finally(h)}catch(i){}};function ht(n,e){let t=e.headers.get(me),s=e.headers.get(Ve),a=e.headers.has(Ot);if(!t||!s||a)return;let o=new URL(n);if(!o.searchParams.has(O))return o.searchParams.set(te,t),o.searchParams.set(se,s),o.searchParams.sort(),o.toString()}function As(n,e){let t=Ps;if(e)if(e.aborted)n.abort();else{let s=()=>n.abort();e.addEventListener("abort",s,{once:!0,signal:n.signal}),t=()=>e.removeEventListener("abort",s)}return{signal:n.signal,cleanup:t}}function Ps(){}import{fetchEventSource as _s}from"@microsoft/fetch-event-source";var lt=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()}},ft=new lt;var Ke=class{constructor(){this.activeSnapshots=new Map;this.xmaxSnapshots=new Map;this.snapshotsByDatabaseLsn=new Map}addSnapshot(e,t){var o,i,h,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=(h=this.snapshotsByDatabaseLsn.get(BigInt(e.database_lsn)))==null?void 0:h.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)&&tt(s,a))}lastSeenUpdate(e){for(let[t,s]of this.snapshotsByDatabaseLsn.entries())if(t<=e)for(let a of s)this.removeSnapshot(a)}};var xs=new Set([je,te,O,se]);function Qt(n){return g(this,null,function*(){return typeof n=="function"?n():n})}function ws(n){return g(this,null,function*(){let e=Object.entries(n),t=yield Promise.all(e.map(o=>g(this,[o],function*([s,a]){if(a===void 0)return[s,void 0];let i=yield Qt(a);return[s,Array.isArray(i)?i.join(","):i]})));return Object.fromEntries(t.filter(([s,a])=>a!==void 0))})}function Ts(n){return g(this,null,function*(){if(!n)return{};let e=Object.entries(n),t=yield Promise.all(e.map(o=>g(this,[o],function*([s,a]){return[s,yield Qt(a)]})));return Object.fromEntries(t)})}function Yt(n){let e=new URL(n.origin+n.pathname);for(let[t,s]of n.searchParams)ot.includes(t)||e.searchParams.set(t,s);return e.searchParams.sort(),e.toString()}var ne,ie,ae,J,q,C,b,D,z,N,w,X,T,_,V,I,oe,M,Z,B,ce,j,he,xe,Y,F,le,we,Te,Q,We,fe,Ge,Je,Me,u,Pe,_e,dt,Kt,pt,$e,$t,Wt,Gt,mt,gt,Jt,zt,Et,St,Xt,Zt,es,ut=class{constructor(e){l(this,u);l(this,ne,null);l(this,ie);l(this,ae);l(this,J);l(this,q,new Map);l(this,C,!1);l(this,b,"active");l(this,D);l(this,z);l(this,N);l(this,w,!1);l(this,X,!0);l(this,T,!1);l(this,_);l(this,V);l(this,I);l(this,oe);l(this,M);l(this,Z,!1);l(this,B);l(this,ce);l(this,j);l(this,he,Promise.resolve([]));l(this,xe,new Ke);l(this,Y,0);l(this,F);l(this,le);l(this,we);l(this,Te,1e3);l(this,Q,0);l(this,We,3);l(this,fe,!1);l(this,Ge,100);l(this,Je,5e3);l(this,Me);var o,i,h,f;this.options=S({subscribe:!0},e),Ms(this.options),c(this,D,(o=this.options.offset)!=null?o:"-1"),c(this,z,""),c(this,_,this.options.handle),c(this,J,new qe(e.parser,e.transformer)),c(this,oe,this.options.onError),c(this,V,(i=this.options.log)!=null?i:"full");let t=(h=e.fetchClient)!=null?h:(...p)=>fetch(...p),s=pe(S({},(f=e.backoffOptions)!=null?f:Qe),{onFailedAttempt:()=>{var p,m;c(this,T,!1),(m=(p=e.backoffOptions)==null?void 0:p.onFailedAttempt)==null||m.call(p)}}),a=qt(t,s);c(this,ae,jt(Vt(a))),c(this,ie,Nt(r(this,ae))),d(this,u,Xt).call(this)}get shapeHandle(){return r(this,_)}get error(){return r(this,ne)}get isUpToDate(){return r(this,w)}get lastOffset(){return r(this,D)}get mode(){return r(this,V)}subscribe(e,t=()=>{}){let s=Math.random();return r(this,q).set(s,[e,t]),r(this,C)||d(this,u,Pe).call(this),()=>{r(this,q).delete(s)}}unsubscribeAll(){var e;r(this,q).clear(),(e=r(this,Me))==null||e.call(this)}lastSyncedAt(){return r(this,N)}lastSynced(){return r(this,N)===void 0?1/0:Date.now()-r(this,N)}isConnected(){return r(this,T)}isLoading(){return!r(this,w)}hasStarted(){return r(this,C)}isPaused(){return r(this,b)==="paused"}forceDisconnectAndRefresh(){return g(this,null,function*(){var e,t;c(this,Z,!0),r(this,w)&&!((e=r(this,M))!=null&&e.signal.aborted)&&((t=r(this,M))==null||t.abort(nt)),yield d(this,u,Jt).call(this),c(this,Z,!1)})}requestSnapshot(e){return g(this,null,function*(){if(r(this,V)==="full")throw new Error(`Snapshot requests are not supported in ${r(this,V)} mode, as the consumer is guaranteed to observe all data`);r(this,C)||(yield d(this,u,Pe).call(this)),yield d(this,u,zt).call(this),Ue(this,Y)._++;try{r(this,Y)===1&&d(this,u,mt).call(this);let{fetchUrl:t,requestHeaders:s}=yield d(this,u,dt).call(this,this.options.url,!0,e),{metadata:a,data:o}=yield d(this,u,es).call(this,t,s),i=o.concat([{headers:S({control:"snapshot-end"},a)}]);return r(this,xe).addSnapshot(a,new Set(o.map(h=>h.key))),d(this,u,$e).call(this,i,!1),{metadata:a,data:o}}finally{Ue(this,Y)._--,r(this,Y)===0&&d(this,u,gt).call(this)}})}};ne=new WeakMap,ie=new WeakMap,ae=new WeakMap,J=new WeakMap,q=new WeakMap,C=new WeakMap,b=new WeakMap,D=new WeakMap,z=new WeakMap,N=new WeakMap,w=new WeakMap,X=new WeakMap,T=new WeakMap,_=new WeakMap,V=new WeakMap,I=new WeakMap,oe=new WeakMap,M=new WeakMap,Z=new WeakMap,B=new WeakMap,ce=new WeakMap,j=new WeakMap,he=new WeakMap,xe=new WeakMap,Y=new WeakMap,F=new WeakMap,le=new WeakMap,we=new WeakMap,Te=new WeakMap,Q=new WeakMap,We=new WeakMap,fe=new WeakMap,Ge=new WeakMap,Je=new WeakMap,Me=new WeakMap,u=new WeakSet,Pe=function(){return g(this,null,function*(){var e,t,s,a,o;c(this,C,!0);try{yield d(this,u,_e).call(this)}catch(i){if(c(this,ne,i),r(this,oe)){let h=yield r(this,oe).call(this,i);if(h&&typeof h=="object"){h.params&&(this.options.params=S(S({},(e=this.options.params)!=null?e:{}),h.params)),h.headers&&(this.options.headers=S(S({},(t=this.options.headers)!=null?t:{}),h.headers)),c(this,ne,null),c(this,C,!1),yield d(this,u,Pe).call(this);return}i instanceof Error&&d(this,u,St).call(this,i),c(this,T,!1),(s=r(this,j))==null||s.call(this);return}throw i instanceof Error&&d(this,u,St).call(this,i),c(this,T,!1),(a=r(this,j))==null||a.call(this),i}c(this,T,!1),(o=r(this,j))==null||o.call(this)})},_e=function(){return g(this,null,function*(){var f,p;if(r(this,b)==="pause-requested"){c(this,b,"paused");return}if(!this.options.subscribe&&((f=this.options.signal)!=null&&f.aborted||r(this,w)))return;let e=r(this,b)==="paused";c(this,b,"active");let{url:t,signal:s}=this.options,{fetchUrl:a,requestHeaders:o}=yield d(this,u,dt).call(this,t,e),i=yield d(this,u,Kt).call(this,s),h=r(this,M);try{yield d(this,u,$t).call(this,{fetchUrl:a,requestAbortController:h,headers:o,resumingFromPause:e})}catch(m){if((m instanceof A||m instanceof U)&&h.signal.aborted&&h.signal.reason===nt)return d(this,u,_e).call(this);if(m instanceof U){let E=r(this,b);h.signal.aborted&&h.signal.reason===it&&E==="pause-requested"&&c(this,b,"paused");return}if(!(m instanceof A))throw m;if(m.status==409){if(r(this,_)){let k=Yt(a);ft.markExpired(k,r(this,_))}let E=m.headers[me]||`${r(this,_)}-next`;return d(this,u,Zt).call(this,E),yield d(this,u,Et).call(this,Array.isArray(m.json)?m.json:[m.json]),d(this,u,_e).call(this)}else throw m}finally{i&&s&&s.removeEventListener("abort",i),c(this,M,void 0)}return(p=r(this,ce))==null||p.call(this),d(this,u,_e).call(this)})},dt=function(e,t,s){return g(this,null,function*(){let[a,o]=yield Promise.all([Ts(this.options.headers),this.options.params?ws(vs(this.options.params)):void 0]);o&&ts(o);let i=new URL(e);if(o){o.table&&x(i,Lt,o.table),o.where&&x(i,Dt,o.where),o.columns&&x(i,Ht,o.columns),o.replica&&x(i,It,o.replica),o.params&&x(i,Bt,o.params);let p=S({},o);delete p.table,delete p.where,delete p.columns,delete p.replica,delete p.params;for(let[m,E]of Object.entries(p))x(i,m,E)}s&&(s.where&&x(i,ge,s.where),s.params&&x(i,be,s.params),s.limit&&x(i,Ee,s.limit),s.offset&&x(i,Se,s.offset),s.orderBy&&x(i,Re,s.orderBy)),i.searchParams.set(se,r(this,D)),i.searchParams.set(at,r(this,V)),r(this,w)&&(!r(this,Z)&&!t&&i.searchParams.set(O,"true"),i.searchParams.set(je,r(this,z))),r(this,_)&&i.searchParams.set(te,r(this,_));let h=Yt(i),f=ft.getExpiredHandle(h);return f&&i.searchParams.set(st,f),i.searchParams.sort(),{fetchUrl:i,requestHeaders:a}})},Kt=function(e){return g(this,null,function*(){var t;if(c(this,M,new AbortController),e){let s=()=>{var a;(a=r(this,M))==null||a.abort(e.reason)};return e.addEventListener("abort",s,{once:!0}),e.aborted&&((t=r(this,M))==null||t.abort(e.reason)),s}})},pt=function(e){return g(this,null,function*(){var f;let{headers:t,status:s}=e,a=t.get(me);a&&c(this,_,a);let o=t.get(Ve);o&&c(this,D,o);let i=t.get(kt);i&&c(this,z,i);let h=()=>{let p=t.get(Ut);return p?JSON.parse(p):{}};c(this,I,(f=r(this,I))!=null?f:h()),s===204&&c(this,N,Date.now())})},$e=function(e,t=!1){return g(this,null,function*(){var s;if(e.length>0){c(this,X,!0);let a=e[e.length-1];if(et(a)){if(t){let i=Ct(a);i&&c(this,D,i)}c(this,N,Date.now()),c(this,w,!0),c(this,X,!1),(s=r(this,le))==null||s.call(this)}let o=e.filter(i=>ee(i)?!r(this,xe).shouldRejectMessage(i):!0);yield d(this,u,Et).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 r(this,w)&&t&&!r(this,Z)&&!e.resumingFromPause&&!r(this,fe)?(e.fetchUrl.searchParams.set(Ft,"true"),e.fetchUrl.searchParams.set(rt,"true"),d(this,u,Gt).call(this,e)):d(this,u,Wt).call(this,e)})},Wt=function(e){return g(this,null,function*(){let{fetchUrl:t,requestAbortController:s,headers:a}=e,o=yield r(this,ie).call(this,t.toString(),{signal:s.signal,headers:a});c(this,T,!0),yield d(this,u,pt).call(this,o);let i=r(this,I),f=(yield o.text())||"[]",p=r(this,J).parse(f,i);yield d(this,u,$e).call(this,p)})},Gt=function(e){return g(this,null,function*(){let{fetchUrl:t,requestAbortController:s,headers:a}=e,o=r(this,ae);c(this,we,Date.now());try{let i=[];yield _s(t.toString(),{headers:a,fetch:o,onopen:h=>g(this,null,function*(){c(this,T,!0),yield d(this,u,pt).call(this,h)}),onmessage:h=>{if(h.data){let f=r(this,I),p=r(this,J).parse(h.data,f);i.push(p),et(p)&&(d(this,u,$e).call(this,i,!0),i=[])}},onerror:h=>{throw h},signal:s.signal})}catch(i){throw s.signal.aborted?new U:i}finally{let i=Date.now()-r(this,we),h=s.signal.aborted;if(i<r(this,Te)&&!h)if(Ue(this,Q)._++,r(this,Q)>=r(this,We))c(this,fe,!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 f=Math.min(r(this,Je),r(this,Ge)*Math.pow(2,r(this,Q))),p=Math.floor(Math.random()*f);yield new Promise(m=>setTimeout(m,p))}else i>=r(this,Te)&&c(this,Q,0)}})},mt=function(){var e;r(this,C)&&r(this,b)==="active"&&(c(this,b,"pause-requested"),(e=r(this,M))==null||e.abort(it))},gt=function(){r(this,C)&&(r(this,b)==="paused"||r(this,b)==="pause-requested")&&(r(this,b)==="pause-requested"&&c(this,b,"active"),d(this,u,Pe).call(this))},Jt=function(){return g(this,null,function*(){return r(this,B)?r(this,B):(c(this,B,new Promise((e,t)=>{c(this,ce,e),c(this,j,t)})),r(this,B).finally(()=>{c(this,B,void 0),c(this,ce,void 0),c(this,j,void 0)}),r(this,B))})},zt=function(){return g(this,null,function*(){if(r(this,X))return r(this,F)?r(this,F):(c(this,F,new Promise(e=>{c(this,le,e)})),r(this,F).finally(()=>{c(this,F,void 0),c(this,le,void 0)}),r(this,F))})},Et=function(e){return g(this,null,function*(){return c(this,he,r(this,he).then(()=>Promise.all(Array.from(r(this,q).values()).map(a=>g(this,[a],function*([t,s]){try{yield t(e)}catch(o){queueMicrotask(()=>{throw o})}}))))),r(this,he)})},St=function(e){r(this,q).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?d(this,u,mt).call(this):d(this,u,gt).call(this)};document.addEventListener("visibilitychange",e),c(this,Me,()=>{document.removeEventListener("visibilitychange",e)})}},Zt=function(e){c(this,D,"-1"),c(this,z,""),c(this,_,e),c(this,w,!1),c(this,X,!0),c(this,T,!1),c(this,I,void 0),c(this,Y,0),c(this,Q,0),c(this,fe,!1)},es=function(e,t){return g(this,null,function*(){let s=yield r(this,ie).call(this,e.toString(),{headers:t});if(!s.ok)throw new A(s.status,void 0,void 0,Object.fromEntries([...s.headers.entries()]),e.toString());let{metadata:a,data:o}=yield s.json(),i=r(this,J).parse(JSON.stringify(o),r(this,I));return{metadata:a,data:i}})},ut.Replica={FULL:"full",DEFAULT:"default"};function ts(n){if(!n)return;let e=Object.keys(n).filter(t=>xs.has(t));if(e.length>0)throw new De(e)}function Ms(n){if(!n.url)throw new Oe;if(n.signal&&!(n.signal instanceof AbortSignal))throw new He;if(n.offset!==void 0&&n.offset!=="-1"&&n.offset!=="now"&&!n.handle)throw new Le;ts(n.params)}function x(n,e,t){if(!(t===void 0||t==null))if(typeof t=="string")n.searchParams.set(e,t);else if(typeof t=="object")for(let[s,a]of Object.entries(t))n.searchParams.set(`${e}[${s}]`,a);else n.searchParams.set(e,t.toString())}function vs(n){return Array.isArray(n.params)?pe(S({},n),{params:Object.fromEntries(n.params.map((e,t)=>[t+1,e]))}):n}var P,K,$,ve,ue,de,W,R,rs,ns,Rt,ze,is,bt,ss=class{constructor(e){l(this,R);l(this,P,new Map);l(this,K,new Map);l(this,$,new Set);l(this,ve,new Set);l(this,ue,!1);l(this,de,"syncing");l(this,W,!1);this.stream=e,this.stream.subscribe(d(this,R,rs).bind(this),d(this,R,is).bind(this))}get isUpToDate(){return r(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:a})=>{s(),r(this,W)&&t(r(this,W)),e(a)})}})}get currentValue(){return r(this,P)}get error(){return r(this,W)}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);r(this,ve).add(t),yield d(this,R,Rt).call(this),yield this.stream.requestSnapshot(e)})}subscribe(e){let t=Math.random();return r(this,K).set(t,e),()=>{r(this,K).delete(t)}}unsubscribeAll(){r(this,K).clear()}get numSubscribers(){return r(this,K).size}};P=new WeakMap,K=new WeakMap,$=new WeakMap,ve=new WeakMap,ue=new WeakMap,de=new WeakMap,W=new WeakMap,R=new WeakSet,rs=function(e){let t=!1;e.forEach(s=>{if(ee(s))if(t=d(this,R,ze).call(this,"syncing"),this.mode==="full")switch(s.headers.operation){case"insert":r(this,P).set(s.key,s.value);break;case"update":r(this,P).set(s.key,S(S({},r(this,P).get(s.key)),s.value));break;case"delete":r(this,P).delete(s.key);break}else switch(s.headers.operation){case"insert":r(this,$).add(s.key),r(this,P).set(s.key,s.value);break;case"update":r(this,$).has(s.key)&&r(this,P).set(s.key,S(S({},r(this,P).get(s.key)),s.value));break;case"delete":r(this,$).has(s.key)&&(r(this,P).delete(s.key),r(this,$).delete(s.key));break}if(Ne(s))switch(s.headers.control){case"up-to-date":t=d(this,R,ze).call(this,"up-to-date"),r(this,ue)&&(c(this,ue,!1),d(this,R,ns).call(this));break;case"must-refetch":r(this,P).clear(),r(this,$).clear(),c(this,W,!1),t=d(this,R,ze).call(this,"syncing"),c(this,ue,!0);break}}),t&&d(this,R,bt).call(this)},ns=function(){return g(this,null,function*(){yield d(this,R,Rt).call(this),yield Promise.all(Array.from(r(this,ve)).map(e=>g(this,null,function*(){try{let t=JSON.parse(e);yield this.stream.requestSnapshot(t)}catch(t){}})))})},Rt=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()}))})},ze=function(e){let t=r(this,de)!==e;return c(this,de,e),t&&e==="up-to-date"},is=function(e){e instanceof A&&(c(this,W,e),d(this,R,bt).call(this))},bt=function(){r(this,K).forEach(e=>{e({value:this.currentValue,rows:this.currentRows})})};export{Qe as BackoffDefaults,ot as ELECTRIC_PROTOCOL_QUERY_PARAMS,A as FetchError,ss as Shape,ut as ShapeStream,ee as isChangeMessage,Ne as isControlMessage,tt as isVisibleInSnapshot,Qt as resolveValue};
6
6
  //# sourceMappingURL=index.browser.mjs.map