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