@electric-sql/client 1.0.10 → 1.0.12

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.
@@ -7,16 +7,29 @@ type Value<Extensions = never> = string | number | boolean | bigint | null | Ext
7
7
  };
8
8
  type Row<Extensions = never> = Record<string, Value<Extensions>>;
9
9
  type GetExtensions<T> = [T] extends [Row<never>] ? never : [T] extends [Row<infer E>] ? E : never;
10
- type Offset = `-1` | `${number}_${number}` | `${bigint}_${number}`;
10
+ type Offset = `-1` | `now` | `${number}_${number}` | `${bigint}_${number}`;
11
+ /** Information about transaction visibility for a snapshot. All fields are encoded as strings, but should be treated as uint64. */
12
+ type PostgresSnapshot = {
13
+ xmin: `${bigint}`;
14
+ xmax: `${bigint}`;
15
+ xip_list: `${bigint}`[];
16
+ };
17
+ type NormalizedPgSnapshot = {
18
+ xmin: bigint;
19
+ xmax: bigint;
20
+ xip_list: bigint[];
21
+ };
11
22
  interface Header {
12
23
  [key: Exclude<string, `operation` | `control`>]: Value;
13
24
  }
14
25
  type Operation = `insert` | `update` | `delete`;
15
26
  type ControlMessage = {
16
- headers: Header & {
27
+ headers: (Header & {
17
28
  control: `up-to-date` | `must-refetch`;
18
29
  global_last_seen_lsn?: string;
19
- };
30
+ }) | (Header & {
31
+ control: `snapshot-end`;
32
+ } & PostgresSnapshot);
20
33
  };
21
34
  type ChangeMessage<T extends Row<unknown> = Row> = {
22
35
  key: string;
@@ -24,6 +37,7 @@ type ChangeMessage<T extends Row<unknown> = Row> = {
24
37
  old_value?: Partial<T>;
25
38
  headers: Header & {
26
39
  operation: Operation;
40
+ txids?: number[];
27
41
  };
28
42
  };
29
43
  type Message<T extends Row<unknown> = Row> = ControlMessage | ChangeMessage<T>;
@@ -78,6 +92,20 @@ type TypedMessages<T extends Row<unknown> = Row> = {
78
92
  schema: ColumnInfo;
79
93
  };
80
94
  type MaybePromise<T> = T | Promise<T>;
95
+ /**
96
+ * Metadata that allows the consumer to know which changes have been incorporated into this snapshot.
97
+ *
98
+ * For any data that has a known transaction ID `xid` (and e.g. a key that's part of the snapshot):
99
+ * - if `xid` < `xmin` - included, change can be skipped
100
+ * - if `xid` < `xmax` AND `xid` not in `xip` - included, change can be skipped
101
+ * - if `xid` < `xmax` AND `xid` in `xip` - parallel, not included, change must be processed
102
+ * - if `xid` >= `xmax` - not included, change must be processed, and we can stop filtering after we see this
103
+ */
104
+ type SnapshotMetadata = {
105
+ /** Random number that's reflected in the `snapshot_mark` header on the snapshot items. */
106
+ snapshot_mark: number;
107
+ database_lsn: string;
108
+ } & PostgresSnapshot;
81
109
 
82
110
  type Token = string;
83
111
  type ParseFunction<Extensions = never> = (value: Token, additionalInfo?: Omit<ColumnInfo, `type` | `dims`>) => Value<Extensions>;
@@ -126,6 +154,7 @@ declare const OFFSET_QUERY_PARAM = "offset";
126
154
  declare const ELECTRIC_PROTOCOL_QUERY_PARAMS: Array<string>;
127
155
 
128
156
  type Replica = `full` | `default`;
157
+ type LogMode = `changes_only` | `full`;
129
158
  /**
130
159
  * PostgreSQL-specific shape parameters that can be provided externally
131
160
  */
@@ -175,7 +204,14 @@ type ExternalParamsRecord<T extends Row<unknown> = Row> = {
175
204
  } & Partial<PostgresParams<T>> & {
176
205
  [K in ReservedParamKeys]?: never;
177
206
  };
178
- type ReservedParamKeys = typeof LIVE_CACHE_BUSTER_QUERY_PARAM | typeof SHAPE_HANDLE_QUERY_PARAM | typeof LIVE_QUERY_PARAM | typeof OFFSET_QUERY_PARAM;
207
+ type SubsetParams = {
208
+ where?: string;
209
+ params?: Record<string, string>;
210
+ limit?: number;
211
+ offset?: number;
212
+ orderBy?: string;
213
+ };
214
+ type ReservedParamKeys = typeof LIVE_CACHE_BUSTER_QUERY_PARAM | typeof SHAPE_HANDLE_QUERY_PARAM | typeof LIVE_QUERY_PARAM | typeof OFFSET_QUERY_PARAM | `subset__${string}`;
179
215
  /**
180
216
  * External headers type - what users provide.
181
217
  * Allows string or function values for any header.
@@ -245,6 +281,10 @@ interface ShapeStreamOptions<T = never> {
245
281
  * Experimental support for Server-Sent Events (SSE) for live updates.
246
282
  */
247
283
  experimentalLiveSse?: boolean;
284
+ /**
285
+ * Initial data loading mode
286
+ */
287
+ log?: LogMode;
248
288
  signal?: AbortSignal;
249
289
  fetchClient?: typeof fetch;
250
290
  backoffOptions?: BackoffOptions;
@@ -273,7 +313,18 @@ interface ShapeStreamInterface<T extends Row<unknown> = Row> {
273
313
  lastOffset: Offset;
274
314
  shapeHandle?: string;
275
315
  error?: unknown;
316
+ mode: LogMode;
276
317
  forceDisconnectAndRefresh(): Promise<void>;
318
+ requestSnapshot(params: {
319
+ where?: string;
320
+ params?: Record<string, string>;
321
+ limit: number;
322
+ offset?: number;
323
+ orderBy: string;
324
+ }): Promise<{
325
+ metadata: SnapshotMetadata;
326
+ data: Array<Message<T>>;
327
+ }>;
277
328
  }
278
329
  /**
279
330
  * Reads updates to a shape from Electric using HTTP requests and long polling or
@@ -326,6 +377,7 @@ declare class ShapeStream<T extends Row<unknown> = Row> implements ShapeStreamIn
326
377
  get error(): unknown;
327
378
  get isUpToDate(): boolean;
328
379
  get lastOffset(): Offset;
380
+ get mode(): LogMode;
329
381
  subscribe(callback: (messages: Message<T>[]) => MaybePromise<void>, onError?: (error: Error) => void): () => void;
330
382
  unsubscribeAll(): void;
331
383
  /** Unix time at which we last synced. Undefined when `isLoading` is true. */
@@ -345,6 +397,24 @@ declare class ShapeStream<T extends Row<unknown> = Row> implements ShapeStreamIn
345
397
  * latest LSN from Postgres at that point in time.
346
398
  */
347
399
  forceDisconnectAndRefresh(): Promise<void>;
400
+ /**
401
+ * Request a snapshot for subset of data.
402
+ *
403
+ * Only available when mode is `changes_only`.
404
+ * Returns the insertion point & the data, but more importantly injects the data
405
+ * into the subscribed data stream. Returned value is unlikely to be useful for the caller,
406
+ * unless the caller has complicated additional logic.
407
+ *
408
+ * Data will be injected in a way that's also tracking further incoming changes, and it'll
409
+ * skip the ones that are already in the snapshot.
410
+ *
411
+ * @param opts - The options for the snapshot request.
412
+ * @returns The metadata and the data for the snapshot.
413
+ */
414
+ requestSnapshot(opts: SubsetParams): Promise<{
415
+ metadata: SnapshotMetadata;
416
+ data: Array<ChangeMessage<T>>;
417
+ }>;
348
418
  }
349
419
 
350
420
  type ShapeData<T extends Row<unknown> = Row> = Map<string, T>;
@@ -408,6 +478,13 @@ declare class Shape<T extends Row<unknown> = Row> {
408
478
  isLoading(): boolean;
409
479
  /** Indicates if we are connected to the Electric sync service. */
410
480
  isConnected(): boolean;
481
+ /** Current log mode of the underlying stream */
482
+ get mode(): LogMode;
483
+ /**
484
+ * Request a snapshot for subset of data. Only available when mode is changes_only.
485
+ * Returns void; data will be emitted via the stream and processed by this Shape.
486
+ */
487
+ requestSnapshot(params: Parameters<ShapeStreamInterface<T>[`requestSnapshot`]>[0]): Promise<void>;
411
488
  subscribe(callback: ShapeChangedCallback<T>): () => void;
412
489
  unsubscribeAll(): void;
413
490
  get numSubscribers(): number;
@@ -449,5 +526,13 @@ declare function isChangeMessage<T extends Row<unknown> = Row>(message: Message<
449
526
  * ```
450
527
  */
451
528
  declare function isControlMessage<T extends Row<unknown> = Row>(message: Message<T>): message is ControlMessage;
529
+ /**
530
+ * Checks if a transaction is visible in a snapshot.
531
+ *
532
+ * @param txid - the transaction id to check
533
+ * @param snapshot - the information about the snapshot
534
+ * @returns true if the transaction is visible in the snapshot
535
+ */
536
+ declare function isVisibleInSnapshot(txid: number | bigint | `${bigint}`, snapshot: PostgresSnapshot | NormalizedPgSnapshot): boolean;
452
537
 
453
- export { BackoffDefaults, type BackoffOptions, type BitColumn, type BpcharColumn, type ChangeMessage, type ColumnInfo, type CommonColumnProps, type ControlMessage, ELECTRIC_PROTOCOL_QUERY_PARAMS, type ExternalHeadersRecord, type ExternalParamsRecord, FetchError, type GetExtensions, type IntervalColumn, type IntervalColumnWithPrecision, type MaybePromise, type Message, type NumericColumn, type Offset, type Operation, type PostgresParams, type RegularColumn, type Row, type Schema, Shape, type ShapeChangedCallback, type ShapeData, ShapeStream, type ShapeStreamInterface, type ShapeStreamOptions, type TimeColumn, type TypedMessages, type Value, type VarcharColumn, isChangeMessage, isControlMessage, resolveValue };
538
+ export { BackoffDefaults, type BackoffOptions, type BitColumn, type BpcharColumn, type ChangeMessage, type ColumnInfo, type CommonColumnProps, type ControlMessage, ELECTRIC_PROTOCOL_QUERY_PARAMS, type ExternalHeadersRecord, type ExternalParamsRecord, FetchError, type GetExtensions, type IntervalColumn, type IntervalColumnWithPrecision, type LogMode, type MaybePromise, type Message, type NormalizedPgSnapshot, type NumericColumn, type Offset, type Operation, type PostgresParams, type PostgresSnapshot, type RegularColumn, type Row, type Schema, Shape, type ShapeChangedCallback, type ShapeData, ShapeStream, type ShapeStreamInterface, type ShapeStreamOptions, type SnapshotMetadata, type SubsetParams, type TimeColumn, type TypedMessages, type Value, type VarcharColumn, isChangeMessage, isControlMessage, isVisibleInSnapshot, resolveValue };
@@ -1,6 +1,6 @@
1
- var _t=Object.defineProperty,wt=Object.defineProperties;var Tt=Object.getOwnPropertyDescriptors;var ce=Object.getOwnPropertySymbols;var Ye=Object.prototype.hasOwnProperty,Be=Object.prototype.propertyIsEnumerable;var Qe=r=>{throw TypeError(r)};var je=(r,e,t)=>e in r?_t(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,b=(r,e)=>{for(var t in e||(e={}))Ye.call(e,t)&&je(r,t,e[t]);if(ce)for(var t of ce(e))Be.call(e,t)&&je(r,t,e[t]);return r},te=(r,e)=>wt(r,Tt(e));var Ke=(r,e)=>{var t={};for(var s in r)Ye.call(r,s)&&e.indexOf(s)<0&&(t[s]=r[s]);if(r!=null&&ce)for(var s of ce(r))e.indexOf(s)<0&&Be.call(r,s)&&(t[s]=r[s]);return t};var we=(r,e,t)=>e.has(r)||Qe("Cannot "+t);var a=(r,e,t)=>(we(r,e,"read from private field"),t?t.call(r):e.get(r)),m=(r,e,t)=>e.has(r)?Qe("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t),c=(r,e,t,s)=>(we(r,e,"write to private field"),s?s.call(r,t):e.set(r,t),t),d=(r,e,t)=>(we(r,e,"access private method"),t);var E=(r,e,t)=>new Promise((s,n)=>{var o=h=>{try{l(t.next(h))}catch(p){n(p)}},i=h=>{try{l(t.throw(h))}catch(p){n(p)}},l=h=>h.done?s(h.value):Promise.resolve(h.value).then(o,i);l((t=t.apply(r,e)).next())});var P=class r extends Error{constructor(t,s,n,o,i,l){super(l||`HTTP Error ${t} at ${i}: ${s!=null?s:JSON.stringify(n)}`);this.url=i;this.name="FetchError",this.status=t,this.text=s,this.json=n,this.headers=o}static fromResponse(t,s){return E(this,null,function*(){let n=t.status,o=Object.fromEntries([...t.headers.entries()]),i,l,h=t.headers.get("content-type");return t.bodyUsed||(h&&h.includes("application/json")?l=yield t.json():i=yield t.text()),new r(n,i,l,o,s)})}},H=class extends Error{constructor(){super("Fetch with backoff aborted"),this.name="FetchBackoffAbortError"}};var he=class extends Error{constructor(){super("Invalid shape options: missing required url parameter"),this.name="MissingShapeUrlError"}},le=class extends Error{constructor(){super("Invalid signal option. It must be an instance of AbortSignal."),this.name="InvalidSignalError"}},fe=class extends Error{constructor(){super("shapeHandle is required if this isn't an initial fetch (i.e. offset > -1)"),this.name="MissingShapeHandleError"}},ue=class extends Error{constructor(e){super(`Cannot use reserved Electric parameter names in custom params: ${e.join(", ")}`),this.name="ReservedParamError"}},de=class extends Error{constructor(e){super(`Column "${e!=null?e:"unknown"}" does not allow NULL values`),this.name="ParserNullValueError"}};var pe=class extends Error{constructor(e,t){let s=`The response for the shape request to ${e} didn't include the following required headers:
2
- `;t.forEach(n=>{s+=`- ${n}
1
+ var Wt=Object.defineProperty,$t=Object.defineProperties;var Gt=Object.getOwnPropertyDescriptors;var _e=Object.getOwnPropertySymbols;var ft=Object.prototype.hasOwnProperty,ut=Object.prototype.propertyIsEnumerable;var dt=r=>{throw TypeError(r)};var lt=(r,e,t)=>e in r?Wt(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,b=(r,e)=>{for(var t in e||(e={}))ft.call(e,t)&&lt(r,t,e[t]);if(_e)for(var t of _e(e))ut.call(e,t)&&lt(r,t,e[t]);return r},le=(r,e)=>$t(r,Gt(e));var pt=(r,e)=>{var t={};for(var s in r)ft.call(r,s)&&e.indexOf(s)<0&&(t[s]=r[s]);if(r!=null&&_e)for(var s of _e(r))e.indexOf(s)<0&&ut.call(r,s)&&(t[s]=r[s]);return t};var Ve=(r,e,t)=>e.has(r)||dt("Cannot "+t);var n=(r,e,t)=>(Ve(r,e,"read from private field"),t?t.call(r):e.get(r)),p=(r,e,t)=>e.has(r)?dt("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t),h=(r,e,t,s)=>(Ve(r,e,"write to private field"),s?s.call(r,t):e.set(r,t),t),u=(r,e,t)=>(Ve(r,e,"access private method"),t);var je=(r,e,t,s)=>({set _(a){h(r,e,a,t)},get _(){return n(r,e,s)}});var g=(r,e,t)=>new Promise((s,a)=>{var o=f=>{try{c(t.next(f))}catch(d){a(d)}},i=f=>{try{c(t.throw(f))}catch(d){a(d)}},c=f=>f.done?s(f.value):Promise.resolve(f.value).then(o,i);c((t=t.apply(r,e)).next())});var y=class r extends Error{constructor(t,s,a,o,i,c){super(c||`HTTP Error ${t} at ${i}: ${s!=null?s:JSON.stringify(a)}`);this.url=i;this.name="FetchError",this.status=t,this.text=s,this.json=a,this.headers=o}static fromResponse(t,s){return g(this,null,function*(){let a=t.status,o=Object.fromEntries([...t.headers.entries()]),i,c,f=t.headers.get("content-type");return t.bodyUsed||(f&&f.includes("application/json")?c=yield t.json():i=yield t.text()),new r(a,i,c,o,s)})}},I=class extends Error{constructor(){super("Fetch with backoff aborted"),this.name="FetchBackoffAbortError"}};var xe=class extends Error{constructor(){super("Invalid shape options: missing required url parameter"),this.name="MissingShapeUrlError"}},we=class extends Error{constructor(){super("Invalid signal option. It must be an instance of AbortSignal."),this.name="InvalidSignalError"}},Te=class extends Error{constructor(){super("shapeHandle is required if this isn't an initial fetch (i.e. offset > -1)"),this.name="MissingShapeHandleError"}},Me=class extends Error{constructor(e){super(`Cannot use reserved Electric parameter names in custom params: ${e.join(", ")}`),this.name="ReservedParamError"}},ve=class extends Error{constructor(e){super(`Column "${e!=null?e:"unknown"}" does not allow NULL values`),this.name="ParserNullValueError"}};var Ce=class extends Error{constructor(e,t){let s=`The response for the shape request to ${e} didn't include the following required headers:
2
+ `;t.forEach(a=>{s+=`- ${a}
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 me=r=>Number(r),Ct=r=>r==="true"||r==="t",vt=r=>BigInt(r),We=r=>JSON.parse(r),Mt=r=>r,Ut={int2:me,int4:me,int8:vt,bool:Ct,float4:me,float8:me,json:We,jsonb:We};function Ot(r,e){let t=0,s=null,n="",o=!1,i=0,l;function h(u,g,q){let R=u.slice(g,q);return R=R==="NULL"?null:R,e?e(R):R}function p(u){let g=[];for(;t<u.length;t++){if(s=u[t],o)s==="\\"?n+=u[++t]:s==='"'?(g.push(e?e(n):n),n="",o=u[t+1]==='"',i=t+2):n+=s;else if(s==='"')o=!0;else if(s==="{")i=++t,g.push(p(u));else if(s==="}"){o=!1,i<t&&g.push(h(u,i,t)),i=t+1;break}else s===","&&l!=="}"&&l!=='"'&&(g.push(h(u,i,t)),i=t+1);l=s}return i<t&&g.push(g.push(h(u,i,t+1))),g}return p(r)[0]}var Ee=class{constructor(e,t){this.parser=b(b({},Ut),e),this.transformer=t}parse(e,t){return JSON.parse(e,(s,n)=>{if((s==="value"||s==="old_value")&&typeof n=="object"&&n!==null){let o=n;Object.keys(o).forEach(i=>{o[i]=this.parseRow(i,o[i],t)}),this.transformer&&(n=this.transformer(n))}return n})}parseRow(e,t,s){var g;let n=s[e];if(!n)return t;let u=n,{type:o,dims:i}=u,l=Ke(u,["type","dims"]),h=(g=this.parser[o])!=null?g:Mt,p=$e(h,n,e);return i&&i>0?$e((R,_e)=>Ot(R,p),n,e)(t):p(t,l)}};function $e(r,e,t){var n;let s=!((n=e.not_null)!=null&&n);return o=>{if(o===null){if(!s)throw new de(t!=null?t:"unknown");return null}return r(o,e)}}function ge(r){return"key"in r}function Re(r){return!ge(r)}function Te(r){return Re(r)&&r.headers.control==="up-to-date"}function Ge(r){let e=r.headers.global_last_seen_lsn;if(e)return`${e}_0`}var Je="electric-cursor",se="electric-handle",be="electric-offset",ze="electric-schema",Xe="electric-up-to-date",Ze="columns",ye="cursor",Ce="expired_handle",B="handle",w="live",Q="offset",et="table",tt="where",st="replica",rt="params",nt="experimental_live_sse",ve="force-disconnect-and-refresh",Me="pause-stream",Ue=[w,B,Q,ye,Ce];var kt=[429],Ae={initialDelay:100,maxDelay:1e4,multiplier:1.3};function at(r,e=Ae){let{initialDelay:t,maxDelay:s,multiplier:n,debug:o=!1,onFailedAttempt:i}=e;return(...l)=>E(this,null,function*(){var q;let h=l[0],p=l[1],u=t,g=0;for(;;)try{let R=yield r(...l);if(R.ok)return R;throw yield P.fromResponse(R,h.toString())}catch(R){if(i==null||i(),(q=p==null?void 0:p.signal)!=null&&q.aborted)throw new H;if(R instanceof P&&!kt.includes(R.status)&&R.status>=400&&R.status<500)throw R;yield new Promise(_e=>setTimeout(_e,u)),u=Math.min(u*n,s),o&&(g++,console.log(`Retry attempt #${g} after ${u}ms`))}})}var Ht=[201,204,205];function ot(r){return(...e)=>E(this,null,function*(){let t=e[0],s=yield r(...e);try{if(s.status<200||Ht.includes(s.status))return s;let n=yield s.text();return new Response(n,s)}catch(n){throw new P(s.status,void 0,void 0,Object.fromEntries([...s.headers.entries()]),t.toString(),n instanceof Error?n.message:typeof n=="string"?n:"failed to read body")}})}var Lt={maxChunksToPrefetch:2};function it(r,e=Lt){let{maxChunksToPrefetch:t}=e,s;return(...o)=>E(this,null,function*(){let i=o[0].toString(),l=s==null?void 0:s.consume(...o);if(l)return l;s==null||s.abort();let h=yield r(...o),p=ke(i,h);return p&&(s=new Oe({fetchClient:r,maxPrefetchedRequests:t,url:p,requestInit:o[1]})),h})}var Dt=["electric-offset","electric-handle"],Ft=["electric-cursor"],It=["electric-schema"];function ct(r){return(...e)=>E(this,null,function*(){let t=yield r(...e);if(t.ok){let s=t.headers,n=[],o=p=>n.push(...p.filter(u=>!s.has(u)));o(Dt);let l=e[0].toString(),h=new URL(l);if(h.searchParams.get(w)==="true"&&o(Ft),(!h.searchParams.has(w)||h.searchParams.get(w)==="false")&&o(It),n.length>0)throw new pe(l,n)}return t})}var re,ne,T,V,C,K,Pe,Oe=class{constructor(e){m(this,K);m(this,re);m(this,ne);m(this,T,new Map);m(this,V);m(this,C);var t;c(this,re,(t=e.fetchClient)!=null?t:(...s)=>fetch(...s)),c(this,ne,e.maxPrefetchedRequests),c(this,V,e.url.toString()),c(this,C,a(this,V)),d(this,K,Pe).call(this,e.url,e.requestInit)}abort(){a(this,T).forEach(([e,t])=>t.abort())}consume(...e){var n;let t=e[0].toString(),s=(n=a(this,T).get(t))==null?void 0:n[0];if(!(!s||t!==a(this,V)))return a(this,T).delete(t),s.then(o=>{let i=ke(t,o);c(this,V,i),a(this,C)&&!a(this,T).has(a(this,C))&&d(this,K,Pe).call(this,a(this,C),e[1])}).catch(()=>{}),s}};re=new WeakMap,ne=new WeakMap,T=new WeakMap,V=new WeakMap,C=new WeakMap,K=new WeakSet,Pe=function(...e){var n,o;let t=e[0].toString();if(a(this,T).size>=a(this,ne))return;let s=new AbortController;try{let{signal:i,cleanup:l}=Nt(s,(n=e[1])==null?void 0:n.signal),h=a(this,re).call(this,t,te(b({},(o=e[1])!=null?o:{}),{signal:i}));a(this,T).set(t,[h,s]),h.then(p=>{if(!p.ok||s.signal.aborted)return;let u=ke(t,p);if(!u||u===t){c(this,C,void 0);return}return c(this,C,u),d(this,K,Pe).call(this,u,e[1])}).catch(()=>{}).finally(l)}catch(i){}};function ke(r,e){let t=e.headers.get(se),s=e.headers.get(be),n=e.headers.has(Xe);if(!t||!s||n)return;let o=new URL(r);if(!o.searchParams.has(w))return o.searchParams.set(B,t),o.searchParams.set(Q,s),o.searchParams.sort(),o.toString()}function Nt(r,e){let t=qt;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 qt(){}import{fetchEventSource as Vt}from"@microsoft/fetch-event-source";var He=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 n=s.reduce((o,i)=>this.data[i].lastUsed<this.data[o].lastUsed?i:o);delete this.data[n]}this.save()}save(){if(typeof localStorage!="undefined")try{localStorage.setItem(this.storageKey,JSON.stringify(this.data))}catch(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()}},Le=new He;var jt=new Set([ye,B,w,Q]);function lt(r){return E(this,null,function*(){return typeof r=="function"?r():r})}function Yt(r){return E(this,null,function*(){let e=Object.entries(r),t=yield Promise.all(e.map(o=>E(this,[o],function*([s,n]){if(n===void 0)return[s,void 0];let i=yield lt(n);return[s,Array.isArray(i)?i.join(","):i]})));return Object.fromEntries(t.filter(([s,n])=>n!==void 0))})}function Bt(r){return E(this,null,function*(){if(!r)return{};let e=Object.entries(r),t=yield Promise.all(e.map(o=>E(this,[o],function*([s,n]){return[s,yield lt(n)]})));return Object.fromEntries(t)})}function ht(r){let e=new URL(r.origin+r.pathname);for(let[t,s]of r.searchParams)Ue.includes(t)||e.searchParams.set(t,s);return e.searchParams.sort(),e.toString()}var oe,ie,$,G,L,v,A,M,j,D,x,U,S,F,J,_,Y,O,z,X,Z,f,Se,ae,ft,ut,Fe,Ie,dt,pt,mt,Et,gt,Rt,Ne,bt,yt,qe,De=class{constructor(e){m(this,f);m(this,oe,null);m(this,ie);m(this,$);m(this,G);m(this,L,new Map);m(this,v,!1);m(this,A,"active");m(this,M);m(this,j);m(this,D);m(this,x,!1);m(this,U,!1);m(this,S);m(this,F);m(this,J);m(this,_);m(this,Y,!1);m(this,O);m(this,z);m(this,X);m(this,Z,Promise.resolve([]));var o,i,l;this.options=b({subscribe:!0},e),Qt(this.options),c(this,M,(o=this.options.offset)!=null?o:"-1"),c(this,j,""),c(this,S,this.options.handle),c(this,G,new Ee(e.parser,e.transformer)),c(this,J,this.options.onError);let t=(i=e.fetchClient)!=null?i:(...h)=>fetch(...h),s=te(b({},(l=e.backoffOptions)!=null?l:Ae),{onFailedAttempt:()=>{var h,p;c(this,U,!1),(p=(h=e.backoffOptions)==null?void 0:h.onFailedAttempt)==null||p.call(h)}}),n=at(t,s);c(this,$,ct(it(n))),c(this,ie,ot(a(this,$))),d(this,f,yt).call(this)}get shapeHandle(){return a(this,S)}get error(){return a(this,oe)}get isUpToDate(){return a(this,x)}get lastOffset(){return a(this,M)}subscribe(e,t=()=>{}){let s=Math.random();return a(this,L).set(s,[e,t]),a(this,v)||d(this,f,Se).call(this),()=>{a(this,L).delete(s)}}unsubscribeAll(){a(this,L).clear()}lastSyncedAt(){return a(this,D)}lastSynced(){return a(this,D)===void 0?1/0:Date.now()-a(this,D)}isConnected(){return a(this,U)}isLoading(){return!a(this,x)}hasStarted(){return a(this,v)}isPaused(){return a(this,A)==="paused"}forceDisconnectAndRefresh(){return E(this,null,function*(){var e,t;c(this,Y,!0),a(this,x)&&!((e=a(this,_))!=null&&e.signal.aborted)&&((t=a(this,_))==null||t.abort(ve)),yield d(this,f,Rt).call(this),c(this,Y,!1)})}};oe=new WeakMap,ie=new WeakMap,$=new WeakMap,G=new WeakMap,L=new WeakMap,v=new WeakMap,A=new WeakMap,M=new WeakMap,j=new WeakMap,D=new WeakMap,x=new WeakMap,U=new WeakMap,S=new WeakMap,F=new WeakMap,J=new WeakMap,_=new WeakMap,Y=new WeakMap,O=new WeakMap,z=new WeakMap,X=new WeakMap,Z=new WeakMap,f=new WeakSet,Se=function(){return E(this,null,function*(){var e;c(this,v,!0);try{yield d(this,f,ae).call(this)}catch(t){if(c(this,oe,t),a(this,J)){let s=yield a(this,J).call(this,t);typeof s=="object"&&(d(this,f,qe).call(this),"params"in s&&(this.options.params=s.params),"headers"in s&&(this.options.headers=s.headers),c(this,v,!1),d(this,f,Se).call(this));return}throw t}finally{c(this,U,!1),(e=a(this,X))==null||e.call(this)}})},ae=function(){return E(this,null,function*(){var h,p;if(a(this,A)==="pause-requested"){c(this,A,"paused");return}if(!this.options.subscribe&&((h=this.options.signal)!=null&&h.aborted||a(this,x)))return;let e=a(this,A)==="paused";c(this,A,"active");let{url:t,signal:s}=this.options,{fetchUrl:n,requestHeaders:o}=yield d(this,f,ft).call(this,t,e),i=yield d(this,f,ut).call(this,s),l=a(this,_);try{yield d(this,f,dt).call(this,{fetchUrl:n,requestAbortController:l,headers:o,resumingFromPause:e})}catch(u){if((u instanceof P||u instanceof H)&&l.signal.aborted&&l.signal.reason===ve)return d(this,f,ae).call(this);if(u instanceof H){l.signal.aborted&&l.signal.reason===Me&&c(this,A,"paused");return}if(!(u instanceof P))throw u;if(u.status==409){if(a(this,S)){let q=ht(n);Le.markExpired(q,a(this,S))}let g=u.headers[se]||`${a(this,S)}-next`;return d(this,f,qe).call(this,g),yield d(this,f,Ne).call(this,u.json),d(this,f,ae).call(this)}else throw d(this,f,bt).call(this,u),u}finally{i&&s&&s.removeEventListener("abort",i),c(this,_,void 0)}return(p=a(this,z))==null||p.call(this),d(this,f,ae).call(this)})},ft=function(e,t){return E(this,null,function*(){let[s,n]=yield Promise.all([Bt(this.options.headers),this.options.params?Yt(Kt(this.options.params)):void 0]);n&&Pt(n);let o=new URL(e);if(n){n.table&&W(o,et,n.table),n.where&&W(o,tt,n.where),n.columns&&W(o,Ze,n.columns),n.replica&&W(o,st,n.replica),n.params&&W(o,rt,n.params);let h=b({},n);delete h.table,delete h.where,delete h.columns,delete h.replica,delete h.params;for(let[p,u]of Object.entries(h))W(o,p,u)}o.searchParams.set(Q,a(this,M)),a(this,x)&&(!a(this,Y)&&!t&&o.searchParams.set(w,"true"),o.searchParams.set(ye,a(this,j))),a(this,S)&&o.searchParams.set(B,a(this,S));let i=ht(o),l=Le.getExpiredHandle(i);return l&&o.searchParams.set(Ce,l),o.searchParams.sort(),{fetchUrl:o,requestHeaders:s}})},ut=function(e){return E(this,null,function*(){var t;if(c(this,_,new AbortController),e){let s=()=>{var n;(n=a(this,_))==null||n.abort(e.reason)};return e.addEventListener("abort",s,{once:!0}),e.aborted&&((t=a(this,_))==null||t.abort(e.reason)),s}})},Fe=function(e){return E(this,null,function*(){var h;let{headers:t,status:s}=e,n=t.get(se);n&&c(this,S,n);let o=t.get(be);o&&c(this,M,o);let i=t.get(Je);i&&c(this,j,i);let l=()=>{let p=t.get(ze);return p?JSON.parse(p):{}};c(this,F,(h=a(this,F))!=null?h:l()),s===204&&c(this,D,Date.now())})},Ie=function(e,t=!1){return E(this,null,function*(){if(e.length>0){let s=e[e.length-1];if(Te(s)){if(t){let n=Ge(s);n&&c(this,M,n)}c(this,D,Date.now()),c(this,x,!0)}yield d(this,f,Ne).call(this,e)}})},dt=function(e){return E(this,null,function*(){return a(this,x)&&this.options.experimentalLiveSse&&!a(this,Y)&&!e.resumingFromPause?(e.fetchUrl.searchParams.set(nt,"true"),d(this,f,mt).call(this,e)):d(this,f,pt).call(this,e)})},pt=function(e){return E(this,null,function*(){let{fetchUrl:t,requestAbortController:s,headers:n}=e,o=yield a(this,ie).call(this,t.toString(),{signal:s.signal,headers:n});c(this,U,!0),yield d(this,f,Fe).call(this,o);let i=a(this,F),h=(yield o.text())||"[]",p=a(this,G).parse(h,i);yield d(this,f,Ie).call(this,p)})},mt=function(e){return E(this,null,function*(){let{fetchUrl:t,requestAbortController:s,headers:n}=e,o=a(this,$);try{let i=[];yield Vt(t.toString(),{headers:n,fetch:o,onopen:l=>E(this,null,function*(){c(this,U,!0),yield d(this,f,Fe).call(this,l)}),onmessage:l=>{if(l.data){let h=a(this,F),p=a(this,G).parse(l.data,h);i.push(p),Te(p)&&(d(this,f,Ie).call(this,i,!0),i=[])}},onerror:l=>{throw l},signal:s.signal})}catch(i){throw s.signal.aborted?new H:i}})},Et=function(){var e;a(this,v)&&a(this,A)==="active"&&(c(this,A,"pause-requested"),(e=a(this,_))==null||e.abort(Me))},gt=function(){a(this,v)&&a(this,A)==="paused"&&d(this,f,Se).call(this)},Rt=function(){return E(this,null,function*(){return a(this,O)?a(this,O):(c(this,O,new Promise((e,t)=>{c(this,z,e),c(this,X,t)})),a(this,O).finally(()=>{c(this,O,void 0),c(this,z,void 0),c(this,X,void 0)}),a(this,O))})},Ne=function(e){return E(this,null,function*(){return c(this,Z,a(this,Z).then(()=>Promise.all(Array.from(a(this,L).values()).map(n=>E(this,[n],function*([t,s]){try{yield t(e)}catch(o){queueMicrotask(()=>{throw o})}}))))),a(this,Z)})},bt=function(e){a(this,L).forEach(([t,s])=>{s==null||s(e)})},yt=function(){if(typeof document=="object"&&typeof document.hidden=="boolean"&&typeof document.addEventListener=="function"){let e=()=>{document.hidden?d(this,f,Et).call(this):d(this,f,gt).call(this)};document.addEventListener("visibilitychange",e)}},qe=function(e){c(this,M,"-1"),c(this,j,""),c(this,S,e),c(this,x,!1),c(this,U,!1),c(this,F,void 0)},De.Replica={FULL:"full",DEFAULT:"default"};function Pt(r){if(!r)return;let e=Object.keys(r).filter(t=>jt.has(t));if(e.length>0)throw new ue(e)}function Qt(r){if(!r.url)throw new he;if(r.signal&&!(r.signal instanceof AbortSignal))throw new le;if(r.offset!==void 0&&r.offset!=="-1"&&!r.handle)throw new fe;Pt(r.params)}function W(r,e,t){if(!(t===void 0||t==null))if(typeof t=="string")r.searchParams.set(e,t);else if(typeof t=="object")for(let[s,n]of Object.entries(t))r.searchParams.set(`${e}[${s}]`,n);else r.searchParams.set(e,t.toString())}function Kt(r){return Array.isArray(r.params)?te(b({},r),{params:Object.fromEntries(r.params.map((e,t)=>[t+1,e]))}):r}var k,I,ee,N,y,St,xe,xt,Ve,At=class{constructor(e){m(this,y);m(this,k,new Map);m(this,I,new Map);m(this,ee,"syncing");m(this,N,!1);this.stream=e,this.stream.subscribe(d(this,y,St).bind(this),d(this,y,xt).bind(this))}get isUpToDate(){return a(this,ee)==="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:n})=>{s(),a(this,N)&&t(a(this,N)),e(n)})}})}get currentValue(){return a(this,k)}get error(){return a(this,N)}lastSyncedAt(){return this.stream.lastSyncedAt()}lastSynced(){return this.stream.lastSynced()}isLoading(){return this.stream.isLoading()}isConnected(){return this.stream.isConnected()}subscribe(e){let t=Math.random();return a(this,I).set(t,e),()=>{a(this,I).delete(t)}}unsubscribeAll(){a(this,I).clear()}get numSubscribers(){return a(this,I).size}};k=new WeakMap,I=new WeakMap,ee=new WeakMap,N=new WeakMap,y=new WeakSet,St=function(e){let t=!1;e.forEach(s=>{if(ge(s))switch(t=d(this,y,xe).call(this,"syncing"),s.headers.operation){case"insert":a(this,k).set(s.key,s.value);break;case"update":a(this,k).set(s.key,b(b({},a(this,k).get(s.key)),s.value));break;case"delete":a(this,k).delete(s.key);break}if(Re(s))switch(s.headers.control){case"up-to-date":t=d(this,y,xe).call(this,"up-to-date");break;case"must-refetch":a(this,k).clear(),c(this,N,!1),t=d(this,y,xe).call(this,"syncing");break}}),t&&d(this,y,Ve).call(this)},xe=function(e){let t=a(this,ee)!==e;return c(this,ee,e),t&&e==="up-to-date"},xt=function(e){e instanceof P&&(c(this,N,e),d(this,y,Ve).call(this))},Ve=function(){a(this,I).forEach(e=>{e({value:this.currentValue,rows:this.currentRows})})};export{Ae as BackoffDefaults,Ue as ELECTRIC_PROTOCOL_QUERY_PARAMS,P as FetchError,At as Shape,De as ShapeStream,ge as isChangeMessage,Re as isControlMessage,lt as resolveValue};
5
+ For more information visit the troubleshooting guide: /docs/guides/troubleshooting/missing-headers`,super(s)}};var Ue=r=>Number(r),Jt=r=>r==="true"||r==="t",zt=r=>BigInt(r),mt=r=>JSON.parse(r),Xt=r=>r,Zt={int2:Ue,int4:Ue,int8:zt,bool:Jt,float4:Ue,float8:Ue,json:mt,jsonb:mt};function es(r,e){let t=0,s=null,a="",o=!1,i=0,c;function f(m,E,Q){let S=m.slice(E,Q);return S=S==="NULL"?null:S,e?e(S):S}function d(m){let E=[];for(;t<m.length;t++){if(s=m[t],o)s==="\\"?a+=m[++t]:s==='"'?(E.push(e?e(a):a),a="",o=m[t+1]==='"',i=t+2):a+=s;else if(s==='"')o=!0;else if(s==="{")i=++t,E.push(d(m));else if(s==="}"){o=!1,i<t&&E.push(f(m,i,t)),i=t+1;break}else s===","&&c!=="}"&&c!=='"'&&(E.push(f(m,i,t)),i=t+1);c=s}return i<t&&E.push(E.push(f(m,i,t+1))),E}return d(r)[0]}var ke=class{constructor(e,t){this.parser=b(b({},Zt),e),this.transformer=t}parse(e,t){return JSON.parse(e,(s,a)=>{if((s==="value"||s==="old_value")&&typeof a=="object"&&a!==null){let o=a;Object.keys(o).forEach(i=>{o[i]=this.parseRow(i,o[i],t)}),this.transformer&&(a=this.transformer(a))}return a})}parseRow(e,t,s){var E;let a=s[e];if(!a)return t;let m=a,{type:o,dims:i}=m,c=pt(m,["type","dims"]),f=(E=this.parser[o])!=null?E:Xt,d=gt(f,a,e);return i&&i>0?gt((S,Ne)=>es(S,d),a,e)(t):d(t,c)}};function gt(r,e,t){var a;let s=!((a=e.not_null)!=null&&a);return o=>{if(o===null){if(!s)throw new ve(t!=null?t:"unknown");return null}return r(o,e)}}function z(r){return"key"in r}function Oe(r){return!z(r)}function Ye(r){return Oe(r)&&r.headers.control==="up-to-date"}function Et(r){let e=r.headers.global_last_seen_lsn;if(e)return`${e}_0`}function Qe(r,e){let t=BigInt(r),s=BigInt(e.xmin),a=BigInt(e.xmax),o=e.xip_list.map(BigInt);return t<s||t<a&&!o.includes(t)}var Rt="electric-cursor",fe="electric-handle",He="electric-offset",St="electric-schema",bt="electric-up-to-date",yt="columns",Le="cursor",Ke="expired_handle",X="handle",v="live",Z="offset",Pt="table",At="where",_t="replica",xt="params",wt="experimental_live_sse",We="force-disconnect-and-refresh",$e="pause-stream",Ge="log",ue="subset__where",de="subset__limit",pe="subset__offset",me="subset__order_by",ge="subset__params",Je=[v,X,Z,Le,Ke,Ge,ue,de,pe,me,ge];var ts=[429],Ie={initialDelay:100,maxDelay:1e4,multiplier:1.3};function Tt(r,e=Ie){let{initialDelay:t,maxDelay:s,multiplier:a,debug:o=!1,onFailedAttempt:i}=e;return(...c)=>g(this,null,function*(){var Q;let f=c[0],d=c[1],m=t,E=0;for(;;)try{let S=yield r(...c);if(S.ok)return S;throw yield y.fromResponse(S,f.toString())}catch(S){if(i==null||i(),(Q=d==null?void 0:d.signal)!=null&&Q.aborted)throw new I;if(S instanceof y&&!ts.includes(S.status)&&S.status>=400&&S.status<500)throw S;yield new Promise(Ne=>setTimeout(Ne,m)),m=Math.min(m*a,s),o&&(E++,console.log(`Retry attempt #${E} after ${m}ms`))}})}var ss=[201,204,205];function Mt(r){return(...e)=>g(this,null,function*(){let t=e[0],s=yield r(...e);try{if(s.status<200||ss.includes(s.status))return s;let a=yield s.text();return new Response(a,s)}catch(a){throw new y(s.status,void 0,void 0,Object.fromEntries([...s.headers.entries()]),t.toString(),a instanceof Error?a.message:typeof a=="string"?a:"failed to read body")}})}var rs={maxChunksToPrefetch:2};function vt(r,e=rs){let{maxChunksToPrefetch:t}=e,s;return(...o)=>g(this,null,function*(){let i=o[0].toString(),c=s==null?void 0:s.consume(...o);if(c)return c;s==null||s.abort();let f=yield r(...o),d=Xe(i,f);return d&&(s=new ze({fetchClient:r,maxPrefetchedRequests:t,url:d,requestInit:o[1]})),f})}var ns=["electric-offset","electric-handle"],as=["electric-cursor"],is=["electric-schema"];function Ct(r){return(...e)=>g(this,null,function*(){let t=yield r(...e);if(t.ok){let s=t.headers,a=[],o=m=>a.push(...m.filter(E=>!s.has(E))),c=e[0].toString(),f=new URL(c);if([ue,ge,de,pe,me].some(m=>f.searchParams.has(m)))return t;if(o(ns),f.searchParams.get(v)==="true"&&o(as),(!f.searchParams.has(v)||f.searchParams.get(v)==="false")&&o(is),a.length>0)throw new Ce(c,a)}return t})}var Ee,Re,C,K,U,ee,De,ze=class{constructor(e){p(this,ee);p(this,Ee);p(this,Re);p(this,C,new Map);p(this,K);p(this,U);var t;h(this,Ee,(t=e.fetchClient)!=null?t:(...s)=>fetch(...s)),h(this,Re,e.maxPrefetchedRequests),h(this,K,e.url.toString()),h(this,U,n(this,K)),u(this,ee,De).call(this,e.url,e.requestInit)}abort(){n(this,C).forEach(([e,t])=>t.abort())}consume(...e){var a;let t=e[0].toString(),s=(a=n(this,C).get(t))==null?void 0:a[0];if(!(!s||t!==n(this,K)))return n(this,C).delete(t),s.then(o=>{let i=Xe(t,o);h(this,K,i),n(this,U)&&!n(this,C).has(n(this,U))&&u(this,ee,De).call(this,n(this,U),e[1])}).catch(()=>{}),s}};Ee=new WeakMap,Re=new WeakMap,C=new WeakMap,K=new WeakMap,U=new WeakMap,ee=new WeakSet,De=function(...e){var a,o;let t=e[0].toString();if(n(this,C).size>=n(this,Re))return;let s=new AbortController;try{let{signal:i,cleanup:c}=os(s,(a=e[1])==null?void 0:a.signal),f=n(this,Ee).call(this,t,le(b({},(o=e[1])!=null?o:{}),{signal:i}));n(this,C).set(t,[f,s]),f.then(d=>{if(!d.ok||s.signal.aborted)return;let m=Xe(t,d);if(!m||m===t){h(this,U,void 0);return}return h(this,U,m),u(this,ee,De).call(this,m,e[1])}).catch(()=>{}).finally(c)}catch(i){}};function Xe(r,e){let t=e.headers.get(fe),s=e.headers.get(He),a=e.headers.has(bt);if(!t||!s||a)return;let o=new URL(r);if(!o.searchParams.has(v))return o.searchParams.set(X,t),o.searchParams.set(Z,s),o.searchParams.sort(),o.toString()}function os(r,e){let t=hs;if(e)if(e.aborted)r.abort();else{let s=()=>r.abort();e.addEventListener("abort",s,{once:!0,signal:r.signal}),t=()=>e.removeEventListener("abort",s)}return{signal:r.signal,cleanup:t}}function hs(){}import{fetchEventSource as cs}from"@microsoft/fetch-event-source";var Ze=class{constructor(){this.data={};this.max=250;this.storageKey="electric_expired_shapes";this.load()}getExpiredHandle(e){let t=this.data[e];return t?(t.lastUsed=Date.now(),this.save(),t.expiredHandle):null}markExpired(e,t){this.data[e]={expiredHandle:t,lastUsed:Date.now()};let s=Object.keys(this.data);if(s.length>this.max){let a=s.reduce((o,i)=>this.data[i].lastUsed<this.data[o].lastUsed?i:o);delete this.data[a]}this.save()}save(){if(typeof localStorage!="undefined")try{localStorage.setItem(this.storageKey,JSON.stringify(this.data))}catch(e){}}load(){if(typeof localStorage!="undefined")try{let e=localStorage.getItem(this.storageKey);e&&(this.data=JSON.parse(e))}catch(e){this.data={}}}clear(){this.data={},this.save()}},et=new Ze;var Be=class{constructor(){this.activeSnapshots=new Map;this.xmaxSnapshots=new Map;this.snapshotsByDatabaseLsn=new Map}addSnapshot(e,t){var o,i,c,f;this.activeSnapshots.set(e.snapshot_mark,{xmin:BigInt(e.xmin),xmax:BigInt(e.xmax),xip_list:e.xip_list.map(BigInt),keys:t});let s=(i=(o=this.xmaxSnapshots.get(BigInt(e.xmax)))==null?void 0:o.add(e.snapshot_mark))!=null?i:new Set([e.snapshot_mark]);this.xmaxSnapshots.set(BigInt(e.xmax),s);let a=(f=(c=this.snapshotsByDatabaseLsn.get(BigInt(e.database_lsn)))==null?void 0:c.add(e.snapshot_mark))!=null?f:new Set([e.snapshot_mark]);this.snapshotsByDatabaseLsn.set(BigInt(e.database_lsn),a)}removeSnapshot(e){this.activeSnapshots.delete(e)}shouldRejectMessage(e){let t=e.headers.txids||[];if(t.length===0)return!1;let s=Math.max(...t);for(let[a,o]of this.xmaxSnapshots.entries())if(s>=a)for(let i of o)this.removeSnapshot(i);return[...this.activeSnapshots.values()].some(a=>a.keys.has(e.key)&&Qe(s,a))}lastSeenUpdate(e){for(let[t,s]of this.snapshotsByDatabaseLsn.entries())if(t<=e)for(let a of s)this.removeSnapshot(a)}};var ls=new Set([Le,X,v,Z]);function kt(r){return g(this,null,function*(){return typeof r=="function"?r():r})}function fs(r){return g(this,null,function*(){let e=Object.entries(r),t=yield Promise.all(e.map(o=>g(this,[o],function*([s,a]){if(a===void 0)return[s,void 0];let i=yield kt(a);return[s,Array.isArray(i)?i.join(","):i]})));return Object.fromEntries(t.filter(([s,a])=>a!==void 0))})}function us(r){return g(this,null,function*(){if(!r)return{};let e=Object.entries(r),t=yield Promise.all(e.map(o=>g(this,[o],function*([s,a]){return[s,yield kt(a)]})));return Object.fromEntries(t)})}function Ut(r){let e=new URL(r.origin+r.pathname);for(let[t,s]of r.searchParams)Je.includes(t)||e.searchParams.set(t,s);return e.searchParams.sort(),e.toString()}var ye,te,se,W,B,M,A,k,$,F,w,G,O,_,q,H,re,T,J,L,ne,ae,ie,Pe,N,D,oe,l,Se,be,st,Ot,rt,Fe,Ht,Lt,Dt,nt,at,It,Bt,it,Ft,qt,ot,Nt,tt=class{constructor(e){p(this,l);p(this,ye,null);p(this,te);p(this,se);p(this,W);p(this,B,new Map);p(this,M,!1);p(this,A,"active");p(this,k);p(this,$);p(this,F);p(this,w,!1);p(this,G,!0);p(this,O,!1);p(this,_);p(this,q);p(this,H);p(this,re);p(this,T);p(this,J,!1);p(this,L);p(this,ne);p(this,ae);p(this,ie,Promise.resolve([]));p(this,Pe,new Be);p(this,N,0);p(this,D);p(this,oe);var o,i,c,f;this.options=b({subscribe:!0},e),ds(this.options),h(this,k,(o=this.options.offset)!=null?o:"-1"),h(this,$,""),h(this,_,this.options.handle),h(this,W,new ke(e.parser,e.transformer)),h(this,re,this.options.onError),h(this,q,(i=this.options.log)!=null?i:"full");let t=(c=e.fetchClient)!=null?c:(...d)=>fetch(...d),s=le(b({},(f=e.backoffOptions)!=null?f:Ie),{onFailedAttempt:()=>{var d,m;h(this,O,!1),(m=(d=e.backoffOptions)==null?void 0:d.onFailedAttempt)==null||m.call(d)}}),a=Tt(t,s);h(this,se,Ct(vt(a))),h(this,te,Mt(n(this,se))),u(this,l,qt).call(this)}get shapeHandle(){return n(this,_)}get error(){return n(this,ye)}get isUpToDate(){return n(this,w)}get lastOffset(){return n(this,k)}get mode(){return n(this,q)}subscribe(e,t=()=>{}){let s=Math.random();return n(this,B).set(s,[e,t]),n(this,M)||u(this,l,Se).call(this),()=>{n(this,B).delete(s)}}unsubscribeAll(){n(this,B).clear()}lastSyncedAt(){return n(this,F)}lastSynced(){return n(this,F)===void 0?1/0:Date.now()-n(this,F)}isConnected(){return n(this,O)}isLoading(){return!n(this,w)}hasStarted(){return n(this,M)}isPaused(){return n(this,A)==="paused"}forceDisconnectAndRefresh(){return g(this,null,function*(){var e,t;h(this,J,!0),n(this,w)&&!((e=n(this,T))!=null&&e.signal.aborted)&&((t=n(this,T))==null||t.abort(We)),yield u(this,l,It).call(this),h(this,J,!1)})}requestSnapshot(e){return g(this,null,function*(){if(n(this,q)==="full")throw new Error(`Snapshot requests are not supported in ${n(this,q)} mode, as the consumer is guaranteed to observe all data`);n(this,M)||(yield u(this,l,Se).call(this)),yield u(this,l,Bt).call(this),je(this,N)._++;try{n(this,N)===1&&u(this,l,nt).call(this);let{fetchUrl:t,requestHeaders:s}=yield u(this,l,st).call(this,this.options.url,!0,e),{metadata:a,data:o}=yield u(this,l,Nt).call(this,t,s),i=o.concat([{headers:b({control:"snapshot-end"},a)}]);return n(this,Pe).addSnapshot(a,new Set(o.map(c=>c.key))),u(this,l,Fe).call(this,i,!1),{metadata:a,data:o}}finally{je(this,N)._--,n(this,N)===0&&u(this,l,at).call(this)}})}};ye=new WeakMap,te=new WeakMap,se=new WeakMap,W=new WeakMap,B=new WeakMap,M=new WeakMap,A=new WeakMap,k=new WeakMap,$=new WeakMap,F=new WeakMap,w=new WeakMap,G=new WeakMap,O=new WeakMap,_=new WeakMap,q=new WeakMap,H=new WeakMap,re=new WeakMap,T=new WeakMap,J=new WeakMap,L=new WeakMap,ne=new WeakMap,ae=new WeakMap,ie=new WeakMap,Pe=new WeakMap,N=new WeakMap,D=new WeakMap,oe=new WeakMap,l=new WeakSet,Se=function(){return g(this,null,function*(){var e;h(this,M,!0);try{yield u(this,l,be).call(this)}catch(t){if(h(this,ye,t),n(this,re)){let s=yield n(this,re).call(this,t);typeof s=="object"&&(u(this,l,ot).call(this),"params"in s&&(this.options.params=s.params),"headers"in s&&(this.options.headers=s.headers),h(this,M,!1),u(this,l,Se).call(this));return}throw t}finally{h(this,O,!1),(e=n(this,ae))==null||e.call(this)}})},be=function(){return g(this,null,function*(){var f,d;if(n(this,A)==="pause-requested"){h(this,A,"paused");return}if(!this.options.subscribe&&((f=this.options.signal)!=null&&f.aborted||n(this,w)))return;let e=n(this,A)==="paused";h(this,A,"active");let{url:t,signal:s}=this.options,{fetchUrl:a,requestHeaders:o}=yield u(this,l,st).call(this,t,e),i=yield u(this,l,Ot).call(this,s),c=n(this,T);try{yield u(this,l,Ht).call(this,{fetchUrl:a,requestAbortController:c,headers:o,resumingFromPause:e})}catch(m){if((m instanceof y||m instanceof I)&&c.signal.aborted&&c.signal.reason===We)return u(this,l,be).call(this);if(m instanceof I){c.signal.aborted&&c.signal.reason===$e&&h(this,A,"paused");return}if(!(m instanceof y))throw m;if(m.status==409){if(n(this,_)){let Q=Ut(a);et.markExpired(Q,n(this,_))}let E=m.headers[fe]||`${n(this,_)}-next`;return u(this,l,ot).call(this,E),yield u(this,l,it).call(this,m.json),u(this,l,be).call(this)}else throw u(this,l,Ft).call(this,m),m}finally{i&&s&&s.removeEventListener("abort",i),h(this,T,void 0)}return(d=n(this,ne))==null||d.call(this),u(this,l,be).call(this)})},st=function(e,t,s){return g(this,null,function*(){let[a,o]=yield Promise.all([us(this.options.headers),this.options.params?fs(ps(this.options.params)):void 0]);o&&Vt(o);let i=new URL(e);if(o){o.table&&x(i,Pt,o.table),o.where&&x(i,At,o.where),o.columns&&x(i,yt,o.columns),o.replica&&x(i,_t,o.replica),o.params&&x(i,xt,o.params);let d=b({},o);delete d.table,delete d.where,delete d.columns,delete d.replica,delete d.params;for(let[m,E]of Object.entries(d))x(i,m,E)}s&&(s.where&&x(i,ue,s.where),s.params&&x(i,ge,s.params),s.limit&&x(i,de,s.limit),s.offset&&x(i,pe,s.offset),s.orderBy&&x(i,me,s.orderBy)),i.searchParams.set(Z,n(this,k)),i.searchParams.set(Ge,n(this,q)),n(this,w)&&(!n(this,J)&&!t&&i.searchParams.set(v,"true"),i.searchParams.set(Le,n(this,$))),n(this,_)&&i.searchParams.set(X,n(this,_));let c=Ut(i),f=et.getExpiredHandle(c);return f&&i.searchParams.set(Ke,f),i.searchParams.sort(),{fetchUrl:i,requestHeaders:a}})},Ot=function(e){return g(this,null,function*(){var t;if(h(this,T,new AbortController),e){let s=()=>{var a;(a=n(this,T))==null||a.abort(e.reason)};return e.addEventListener("abort",s,{once:!0}),e.aborted&&((t=n(this,T))==null||t.abort(e.reason)),s}})},rt=function(e){return g(this,null,function*(){var f;let{headers:t,status:s}=e,a=t.get(fe);a&&h(this,_,a);let o=t.get(He);o&&h(this,k,o);let i=t.get(Rt);i&&h(this,$,i);let c=()=>{let d=t.get(St);return d?JSON.parse(d):{}};h(this,H,(f=n(this,H))!=null?f:c()),s===204&&h(this,F,Date.now())})},Fe=function(e,t=!1){return g(this,null,function*(){var s;if(e.length>0){h(this,G,!0);let a=e[e.length-1];if(Ye(a)){if(t){let i=Et(a);i&&h(this,k,i)}h(this,F,Date.now()),h(this,w,!0),h(this,G,!1),(s=n(this,oe))==null||s.call(this)}let o=e.filter(i=>z(i)?!n(this,Pe).shouldRejectMessage(i):!0);yield u(this,l,it).call(this,o)}})},Ht=function(e){return g(this,null,function*(){return n(this,w)&&this.options.experimentalLiveSse&&!n(this,J)&&!e.resumingFromPause?(e.fetchUrl.searchParams.set(wt,"true"),u(this,l,Dt).call(this,e)):u(this,l,Lt).call(this,e)})},Lt=function(e){return g(this,null,function*(){let{fetchUrl:t,requestAbortController:s,headers:a}=e,o=yield n(this,te).call(this,t.toString(),{signal:s.signal,headers:a});h(this,O,!0),yield u(this,l,rt).call(this,o);let i=n(this,H),f=(yield o.text())||"[]",d=n(this,W).parse(f,i);yield u(this,l,Fe).call(this,d)})},Dt=function(e){return g(this,null,function*(){let{fetchUrl:t,requestAbortController:s,headers:a}=e,o=n(this,se);try{let i=[];yield cs(t.toString(),{headers:a,fetch:o,onopen:c=>g(this,null,function*(){h(this,O,!0),yield u(this,l,rt).call(this,c)}),onmessage:c=>{if(c.data){let f=n(this,H),d=n(this,W).parse(c.data,f);i.push(d),Ye(d)&&(u(this,l,Fe).call(this,i,!0),i=[])}},onerror:c=>{throw c},signal:s.signal})}catch(i){throw s.signal.aborted?new I:i}})},nt=function(){var e;n(this,M)&&n(this,A)==="active"&&(h(this,A,"pause-requested"),(e=n(this,T))==null||e.abort($e))},at=function(){n(this,M)&&n(this,A)==="paused"&&u(this,l,Se).call(this)},It=function(){return g(this,null,function*(){return n(this,L)?n(this,L):(h(this,L,new Promise((e,t)=>{h(this,ne,e),h(this,ae,t)})),n(this,L).finally(()=>{h(this,L,void 0),h(this,ne,void 0),h(this,ae,void 0)}),n(this,L))})},Bt=function(){return g(this,null,function*(){if(n(this,G))return n(this,D)?n(this,D):(h(this,D,new Promise(e=>{h(this,oe,e)})),n(this,D).finally(()=>{h(this,D,void 0),h(this,oe,void 0)}),n(this,D))})},it=function(e){return g(this,null,function*(){return h(this,ie,n(this,ie).then(()=>Promise.all(Array.from(n(this,B).values()).map(a=>g(this,[a],function*([t,s]){try{yield t(e)}catch(o){queueMicrotask(()=>{throw o})}}))))),n(this,ie)})},Ft=function(e){n(this,B).forEach(([t,s])=>{s==null||s(e)})},qt=function(){if(typeof document=="object"&&typeof document.hidden=="boolean"&&typeof document.addEventListener=="function"){let e=()=>{document.hidden?u(this,l,nt).call(this):u(this,l,at).call(this)};document.addEventListener("visibilitychange",e)}},ot=function(e){h(this,k,"-1"),h(this,$,""),h(this,_,e),h(this,w,!1),h(this,G,!0),h(this,O,!1),h(this,H,void 0),h(this,N,0)},Nt=function(e,t){return g(this,null,function*(){let s=yield n(this,te).call(this,e.toString(),{headers:t});if(!s.ok)throw new y(s.status,void 0,void 0,Object.fromEntries([...s.headers.entries()]),e.toString());let{metadata:a,data:o}=yield s.json(),i=n(this,W).parse(JSON.stringify(o),n(this,H));return{metadata:a,data:i}})},tt.Replica={FULL:"full",DEFAULT:"default"};function Vt(r){if(!r)return;let e=Object.keys(r).filter(t=>ls.has(t));if(e.length>0)throw new Me(e)}function ds(r){if(!r.url)throw new xe;if(r.signal&&!(r.signal instanceof AbortSignal))throw new we;if(r.offset!==void 0&&r.offset!=="-1"&&r.offset!=="now"&&!r.handle)throw new Te;Vt(r.params)}function x(r,e,t){if(!(t===void 0||t==null))if(typeof t=="string")r.searchParams.set(e,t);else if(typeof t=="object")for(let[s,a]of Object.entries(t))r.searchParams.set(`${e}[${s}]`,a);else r.searchParams.set(e,t.toString())}function ps(r){return Array.isArray(r.params)?le(b({},r),{params:Object.fromEntries(r.params.map((e,t)=>[t+1,e]))}):r}var P,V,j,Ae,he,ce,Y,R,Yt,Qt,ht,qe,Kt,ct,jt=class{constructor(e){p(this,R);p(this,P,new Map);p(this,V,new Map);p(this,j,new Set);p(this,Ae,new Set);p(this,he,!1);p(this,ce,"syncing");p(this,Y,!1);this.stream=e,this.stream.subscribe(u(this,R,Yt).bind(this),u(this,R,Kt).bind(this))}get isUpToDate(){return n(this,ce)==="up-to-date"}get lastOffset(){return this.stream.lastOffset}get handle(){return this.stream.shapeHandle}get rows(){return this.value.then(e=>Array.from(e.values()))}get currentRows(){return Array.from(this.currentValue.values())}get value(){return new Promise((e,t)=>{if(this.stream.isUpToDate)e(this.currentValue);else{let s=this.subscribe(({value:a})=>{s(),n(this,Y)&&t(n(this,Y)),e(a)})}})}get currentValue(){return n(this,P)}get error(){return n(this,Y)}lastSyncedAt(){return this.stream.lastSyncedAt()}lastSynced(){return this.stream.lastSynced()}isLoading(){return this.stream.isLoading()}isConnected(){return this.stream.isConnected()}get mode(){return this.stream.mode}requestSnapshot(e){return g(this,null,function*(){let t=JSON.stringify(e);n(this,Ae).add(t),yield u(this,R,ht).call(this),yield this.stream.requestSnapshot(e)})}subscribe(e){let t=Math.random();return n(this,V).set(t,e),()=>{n(this,V).delete(t)}}unsubscribeAll(){n(this,V).clear()}get numSubscribers(){return n(this,V).size}};P=new WeakMap,V=new WeakMap,j=new WeakMap,Ae=new WeakMap,he=new WeakMap,ce=new WeakMap,Y=new WeakMap,R=new WeakSet,Yt=function(e){let t=!1;e.forEach(s=>{if(z(s))if(t=u(this,R,qe).call(this,"syncing"),this.mode==="full")switch(s.headers.operation){case"insert":n(this,P).set(s.key,s.value);break;case"update":n(this,P).set(s.key,b(b({},n(this,P).get(s.key)),s.value));break;case"delete":n(this,P).delete(s.key);break}else switch(s.headers.operation){case"insert":n(this,j).add(s.key),n(this,P).set(s.key,s.value);break;case"update":n(this,j).has(s.key)&&n(this,P).set(s.key,b(b({},n(this,P).get(s.key)),s.value));break;case"delete":n(this,j).has(s.key)&&(n(this,P).delete(s.key),n(this,j).delete(s.key));break}if(Oe(s))switch(s.headers.control){case"up-to-date":t=u(this,R,qe).call(this,"up-to-date"),n(this,he)&&(h(this,he,!1),u(this,R,Qt).call(this));break;case"must-refetch":n(this,P).clear(),n(this,j).clear(),h(this,Y,!1),t=u(this,R,qe).call(this,"syncing"),h(this,he,!0);break}}),t&&u(this,R,ct).call(this)},Qt=function(){return g(this,null,function*(){yield u(this,R,ht).call(this),yield Promise.all(Array.from(n(this,Ae)).map(e=>g(this,null,function*(){try{let t=JSON.parse(e);yield this.stream.requestSnapshot(t)}catch(t){}})))})},ht=function(){return g(this,null,function*(){this.stream.isUpToDate||(yield new Promise(e=>{let t=()=>{this.stream.isUpToDate&&(clearInterval(s),a(),e())},s=setInterval(t,10),a=this.stream.subscribe(()=>t(),()=>t());t()}))})},qe=function(e){let t=n(this,ce)!==e;return h(this,ce,e),t&&e==="up-to-date"},Kt=function(e){e instanceof y&&(h(this,Y,e),u(this,R,ct).call(this))},ct=function(){n(this,V).forEach(e=>{e({value:this.currentValue,rows:this.currentRows})})};export{Ie as BackoffDefaults,Je as ELECTRIC_PROTOCOL_QUERY_PARAMS,y as FetchError,jt as Shape,tt as ShapeStream,z as isChangeMessage,Oe as isControlMessage,Qe as isVisibleInSnapshot,kt as resolveValue};
6
6
  //# sourceMappingURL=index.browser.mjs.map