@electric-sql/client 1.1.4 → 1.2.0

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.
@@ -118,6 +118,140 @@ type Parser<Extensions = never> = {
118
118
  };
119
119
  type TransformFunction<Extensions = never> = (message: Row<Extensions>) => Row<Extensions>;
120
120
 
121
+ type DbColumnName = string;
122
+ type AppColumnName = string;
123
+ /**
124
+ * A bidirectional column mapper that handles transforming column **names**
125
+ * between database format (e.g., snake_case) and application format (e.g., camelCase).
126
+ *
127
+ * **Important**: ColumnMapper only transforms column names, not column values or types.
128
+ * For type conversions (e.g., string → Date), use the `parser` option.
129
+ * For value transformations (e.g., encryption), use the `transformer` option.
130
+ *
131
+ * @example
132
+ * ```typescript
133
+ * const mapper = snakeCamelMapper()
134
+ * mapper.decode('user_id') // 'userId'
135
+ * mapper.encode('userId') // 'user_id'
136
+ * ```
137
+ */
138
+ interface ColumnMapper {
139
+ /**
140
+ * Transform a column name from database format to application format.
141
+ * Applied to column names in query results.
142
+ */
143
+ decode: (dbColumnName: DbColumnName) => AppColumnName;
144
+ /**
145
+ * Transform a column name from application format to database format.
146
+ * Applied to column names in WHERE clauses and other query parameters.
147
+ */
148
+ encode: (appColumnName: AppColumnName) => DbColumnName;
149
+ }
150
+ /**
151
+ * Converts a snake_case string to camelCase.
152
+ *
153
+ * Handles edge cases:
154
+ * - Preserves leading underscores: `_user_id` → `_userId`
155
+ * - Preserves trailing underscores: `user_id_` → `userId_`
156
+ * - Collapses multiple underscores: `user__id` → `userId`
157
+ * - Normalizes to lowercase first: `user_Column` → `userColumn`
158
+ *
159
+ * @example
160
+ * snakeToCamel('user_id') // 'userId'
161
+ * snakeToCamel('project_id') // 'projectId'
162
+ * snakeToCamel('created_at') // 'createdAt'
163
+ * snakeToCamel('_private') // '_private'
164
+ * snakeToCamel('user__id') // 'userId'
165
+ * snakeToCamel('user_id_') // 'userId_'
166
+ */
167
+ declare function snakeToCamel(str: string): string;
168
+ /**
169
+ * Converts a camelCase string to snake_case.
170
+ *
171
+ * Handles consecutive capitals (acronyms) properly:
172
+ * - `userID` → `user_id`
173
+ * - `userHTTPSURL` → `user_https_url`
174
+ *
175
+ * @example
176
+ * camelToSnake('userId') // 'user_id'
177
+ * camelToSnake('projectId') // 'project_id'
178
+ * camelToSnake('createdAt') // 'created_at'
179
+ * camelToSnake('userID') // 'user_id'
180
+ * camelToSnake('parseHTMLString') // 'parse_html_string'
181
+ */
182
+ declare function camelToSnake(str: string): string;
183
+ /**
184
+ * Creates a column mapper from an explicit mapping of database columns to application columns.
185
+ *
186
+ * @param mapping - Object mapping database column names (keys) to application column names (values)
187
+ * @returns A ColumnMapper that can encode and decode column names bidirectionally
188
+ *
189
+ * @example
190
+ * const mapper = createColumnMapper({
191
+ * user_id: 'userId',
192
+ * project_id: 'projectId',
193
+ * created_at: 'createdAt'
194
+ * })
195
+ *
196
+ * // Use with ShapeStream
197
+ * const stream = new ShapeStream({
198
+ * url: 'http://localhost:3000/v1/shape',
199
+ * params: { table: 'todos' },
200
+ * columnMapper: mapper
201
+ * })
202
+ */
203
+ declare function createColumnMapper(mapping: Record<string, string>): ColumnMapper;
204
+ /**
205
+ * Creates a column mapper that automatically converts between snake_case and camelCase.
206
+ * This is the most common use case for column mapping.
207
+ *
208
+ * When a schema is provided, it will only map columns that exist in the schema.
209
+ * Otherwise, it will map any column name it encounters.
210
+ *
211
+ * **⚠️ Limitations and Edge Cases:**
212
+ * - **WHERE clause encoding**: Uses regex-based parsing which may not handle all complex
213
+ * SQL expressions. Test thoroughly with your queries, especially those with:
214
+ * - Complex nested expressions
215
+ * - Custom operators or functions
216
+ * - Column names that conflict with SQL keywords
217
+ * - Quoted identifiers (e.g., `"$price"`, `"user-id"`) - not supported
218
+ * - Column names with special characters (non-alphanumeric except underscore)
219
+ * - **Acronym ambiguity**: `userID` → `user_id` → `userId` (ID becomes Id after roundtrip)
220
+ * Use `createColumnMapper()` with explicit mapping if you need exact control
221
+ * - **Type conversion**: This only renames columns, not values. Use `parser` for type conversion
222
+ *
223
+ * **When to use explicit mapping instead:**
224
+ * - You have column names that don't follow snake_case/camelCase patterns
225
+ * - You need exact control over mappings (e.g., `id` → `identifier`)
226
+ * - Your WHERE clauses are complex and automatic encoding fails
227
+ * - You have quoted identifiers or column names with special characters
228
+ *
229
+ * @param schema - Optional database schema to constrain mapping to known columns
230
+ * @returns A ColumnMapper for snake_case ↔ camelCase conversion
231
+ *
232
+ * @example
233
+ * // Basic usage
234
+ * const mapper = snakeCamelMapper()
235
+ *
236
+ * // With schema - only maps columns in schema (recommended)
237
+ * const mapper = snakeCamelMapper(schema)
238
+ *
239
+ * // Use with ShapeStream
240
+ * const stream = new ShapeStream({
241
+ * url: 'http://localhost:3000/v1/shape',
242
+ * params: { table: 'todos' },
243
+ * columnMapper: snakeCamelMapper()
244
+ * })
245
+ *
246
+ * @example
247
+ * // If automatic encoding fails, fall back to manual column names in WHERE clauses:
248
+ * stream.requestSnapshot({
249
+ * where: "user_id = $1", // Use database column names directly if needed
250
+ * params: { "1": "123" }
251
+ * })
252
+ */
253
+ declare function snakeCamelMapper(schema?: Schema): ColumnMapper;
254
+
121
255
  declare class FetchError extends Error {
122
256
  url: string;
123
257
  status: number;
@@ -301,7 +435,84 @@ interface ShapeStreamOptions<T = never> {
301
435
  fetchClient?: typeof fetch;
302
436
  backoffOptions?: BackoffOptions;
303
437
  parser?: Parser<T>;
438
+ /**
439
+ * Function to transform rows after parsing (e.g., for encryption, type coercion).
440
+ * Applied to data received from Electric.
441
+ *
442
+ * **Note**: If you're using `transformer` solely for column name transformation
443
+ * (e.g., snake_case → camelCase), consider using `columnMapper` instead, which
444
+ * provides bidirectional transformation and automatically encodes WHERE clauses.
445
+ *
446
+ * **Execution order** when both are provided:
447
+ * 1. `columnMapper.decode` runs first (renames columns)
448
+ * 2. `transformer` runs second (transforms values)
449
+ *
450
+ * @example
451
+ * ```typescript
452
+ * // For column renaming only - use columnMapper
453
+ * import { snakeCamelMapper } from '@electric-sql/client'
454
+ * const stream = new ShapeStream({ columnMapper: snakeCamelMapper() })
455
+ * ```
456
+ *
457
+ * @example
458
+ * ```typescript
459
+ * // For value transformation (encryption, etc.) - use transformer
460
+ * const stream = new ShapeStream({
461
+ * transformer: (row) => ({
462
+ * ...row,
463
+ * encrypted_field: decrypt(row.encrypted_field)
464
+ * })
465
+ * })
466
+ * ```
467
+ *
468
+ * @example
469
+ * ```typescript
470
+ * // Use both together
471
+ * const stream = new ShapeStream({
472
+ * columnMapper: snakeCamelMapper(), // Runs first: renames columns
473
+ * transformer: (row) => ({ // Runs second: transforms values
474
+ * ...row,
475
+ * encryptedData: decrypt(row.encryptedData)
476
+ * })
477
+ * })
478
+ * ```
479
+ */
304
480
  transformer?: TransformFunction<T>;
481
+ /**
482
+ * Bidirectional column name mapper for transforming between database column names
483
+ * (e.g., snake_case) and application column names (e.g., camelCase).
484
+ *
485
+ * The mapper handles both:
486
+ * - **Decoding**: Database → Application (applied to query results)
487
+ * - **Encoding**: Application → Database (applied to WHERE clauses)
488
+ *
489
+ * @example
490
+ * ```typescript
491
+ * // Most common case: snake_case ↔ camelCase
492
+ * import { snakeCamelMapper } from '@electric-sql/client'
493
+ *
494
+ * const stream = new ShapeStream({
495
+ * url: 'http://localhost:3000/v1/shape',
496
+ * params: { table: 'todos' },
497
+ * columnMapper: snakeCamelMapper()
498
+ * })
499
+ * ```
500
+ *
501
+ * @example
502
+ * ```typescript
503
+ * // Custom mapping
504
+ * import { createColumnMapper } from '@electric-sql/client'
505
+ *
506
+ * const stream = new ShapeStream({
507
+ * columnMapper: createColumnMapper({
508
+ * user_id: 'userId',
509
+ * project_id: 'projectId',
510
+ * created_at: 'createdAt'
511
+ * })
512
+ * })
513
+ * ```
514
+ */
515
+ columnMapper?: ColumnMapper;
305
516
  /**
306
517
  * A function for handling shapestream errors.
307
518
  *
@@ -368,16 +579,14 @@ interface ShapeStreamInterface<T extends Row<unknown> = Row> {
368
579
  error?: unknown;
369
580
  mode: LogMode;
370
581
  forceDisconnectAndRefresh(): Promise<void>;
371
- requestSnapshot(params: {
372
- where?: string;
373
- params?: Record<string, string>;
374
- limit: number;
375
- offset?: number;
376
- orderBy: string;
377
- }): Promise<{
582
+ requestSnapshot(params: SubsetParams): Promise<{
378
583
  metadata: SnapshotMetadata;
379
584
  data: Array<Message<T>>;
380
585
  }>;
586
+ fetchSnapshot(opts: SubsetParams): Promise<{
587
+ metadata: SnapshotMetadata;
588
+ data: Array<ChangeMessage<T>>;
589
+ }>;
381
590
  }
382
591
  /**
383
592
  * Reads updates to a shape from Electric using HTTP requests and long polling or
@@ -451,7 +660,7 @@ declare class ShapeStream<T extends Row<unknown> = Row> implements ShapeStreamIn
451
660
  */
452
661
  forceDisconnectAndRefresh(): Promise<void>;
453
662
  /**
454
- * Request a snapshot for subset of data.
663
+ * Request a snapshot for subset of data and inject it into the subscribed data stream.
455
664
  *
456
665
  * Only available when mode is `changes_only`.
457
666
  * Returns the insertion point & the data, but more importantly injects the data
@@ -468,6 +677,17 @@ declare class ShapeStream<T extends Row<unknown> = Row> implements ShapeStreamIn
468
677
  metadata: SnapshotMetadata;
469
678
  data: Array<ChangeMessage<T>>;
470
679
  }>;
680
+ /**
681
+ * Fetch a snapshot for subset of data.
682
+ * Returns the metadata and the data, but does not inject it into the subscribed data stream.
683
+ *
684
+ * @param opts - The options for the snapshot request.
685
+ * @returns The metadata and the data for the snapshot.
686
+ */
687
+ fetchSnapshot(opts: SubsetParams): Promise<{
688
+ metadata: SnapshotMetadata;
689
+ data: Array<ChangeMessage<T>>;
690
+ }>;
471
691
  }
472
692
 
473
693
  type ShapeData<T extends Row<unknown> = Row> = Map<string, T>;
@@ -588,4 +808,4 @@ declare function isControlMessage<T extends Row<unknown> = Row>(message: Message
588
808
  */
589
809
  declare function isVisibleInSnapshot(txid: number | bigint | `${bigint}`, snapshot: PostgresSnapshot | NormalizedPgSnapshot): boolean;
590
810
 
591
- 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 };
811
+ export { BackoffDefaults, type BackoffOptions, type BitColumn, type BpcharColumn, type ChangeMessage, type ColumnInfo, type ColumnMapper, 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, camelToSnake, createColumnMapper, isChangeMessage, isControlMessage, isVisibleInSnapshot, resolveValue, snakeCamelMapper, snakeToCamel };
@@ -1,6 +1,6 @@
1
- var os=Object.defineProperty,cs=Object.defineProperties;var hs=Object.getOwnPropertyDescriptors;var ke=Object.getOwnPropertySymbols;var _t=Object.prototype.hasOwnProperty,xt=Object.prototype.propertyIsEnumerable;var wt=n=>{throw TypeError(n)};var Pt=(n,e,t)=>e in n?os(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,S=(n,e)=>{for(var t in e||(e={}))_t.call(e,t)&&Pt(n,t,e[t]);if(ke)for(var t of ke(e))xt.call(e,t)&&Pt(n,t,e[t]);return n},pe=(n,e)=>cs(n,hs(e));var Tt=(n,e)=>{var t={};for(var s in n)_t.call(n,s)&&e.indexOf(s)<0&&(t[s]=n[s]);if(n!=null&&ke)for(var s of ke(n))e.indexOf(s)<0&&xt.call(n,s)&&(t[s]=n[s]);return t};var Ze=(n,e,t)=>e.has(n)||wt("Cannot "+t);var r=(n,e,t)=>(Ze(n,e,"read from private field"),t?t.call(n):e.get(n)),l=(n,e,t)=>e.has(n)?wt("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(n):e.set(n,t),c=(n,e,t,s)=>(Ze(n,e,"write to private field"),s?s.call(n,t):e.set(n,t),t),d=(n,e,t)=>(Ze(n,e,"access private method"),t);var Ue=(n,e,t,s)=>({set _(a){c(n,e,a,t)},get _(){return r(n,e,s)}});var g=(n,e,t)=>new Promise((s,a)=>{var o=f=>{try{h(t.next(f))}catch(p){a(p)}},i=f=>{try{h(t.throw(f))}catch(p){a(p)}},h=f=>f.done?s(f.value):Promise.resolve(f.value).then(o,i);h((t=t.apply(n,e)).next())});var A=class n extends Error{constructor(t,s,a,o,i,h){super(h||`HTTP Error ${t} at ${i}: ${s!=null?s:JSON.stringify(a)}`);this.url=i;this.name="FetchError",this.status=t,this.text=s,this.json=a,this.headers=o}static fromResponse(t,s){return g(this,null,function*(){let a=t.status,o=Object.fromEntries([...t.headers.entries()]),i,h,f=t.headers.get("content-type");return t.bodyUsed||(f&&f.includes("application/json")?h=yield t.json():i=yield t.text()),new n(a,i,h,o,s)})}},U=class extends Error{constructor(){super("Fetch with backoff aborted"),this.name="FetchBackoffAbortError"}};var Oe=class extends Error{constructor(){super("Invalid shape options: missing required url parameter"),this.name="MissingShapeUrlError"}},He=class extends Error{constructor(){super("Invalid signal option. It must be an instance of AbortSignal."),this.name="InvalidSignalError"}},Le=class extends Error{constructor(){super("shapeHandle is required if this isn't an initial fetch (i.e. offset > -1)"),this.name="MissingShapeHandleError"}},De=class extends Error{constructor(e){super(`Cannot use reserved Electric parameter names in custom params: ${e.join(", ")}`),this.name="ReservedParamError"}},Ie=class extends Error{constructor(e){super(`Column "${e!=null?e:"unknown"}" does not allow NULL values`),this.name="ParserNullValueError"}};var Be=class extends Error{constructor(e,t){let s=`The response for the shape request to ${e} didn't include the following required headers:
1
+ var gs=Object.defineProperty,Es=Object.defineProperties;var Ss=Object.getOwnPropertyDescriptors;var Le=Object.getOwnPropertySymbols;var Ot=Object.prototype.hasOwnProperty,Lt=Object.prototype.propertyIsEnumerable;var Dt=r=>{throw TypeError(r)};var Ut=(r,e,t)=>e in r?gs(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,R=(r,e)=>{for(var t in e||(e={}))Ot.call(e,t)&&Ut(r,t,e[t]);if(Le)for(var t of Le(e))Lt.call(e,t)&&Ut(r,t,e[t]);return r},Se=(r,e)=>Es(r,Ss(e));var Ht=(r,e)=>{var t={};for(var s in r)Ot.call(r,s)&&e.indexOf(s)<0&&(t[s]=r[s]);if(r!=null&&Le)for(var s of Le(r))e.indexOf(s)<0&&Lt.call(r,s)&&(t[s]=r[s]);return t};var rt=(r,e,t)=>e.has(r)||Dt("Cannot "+t);var n=(r,e,t)=>(rt(r,e,"read from private field"),t?t.call(r):e.get(r)),d=(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),c=(r,e,t,s)=>(rt(r,e,"write to private field"),s?s.call(r,t):e.set(r,t),t),p=(r,e,t)=>(rt(r,e,"access private method"),t);var De=(r,e,t,s)=>({set _(a){c(r,e,a,t)},get _(){return n(r,e,s)}});var g=(r,e,t)=>new Promise((s,a)=>{var o=l=>{try{h(t.next(l))}catch(m){a(m)}},i=l=>{try{h(t.throw(l))}catch(m){a(m)}},h=l=>l.done?s(l.value):Promise.resolve(l.value).then(o,i);h((t=t.apply(r,e)).next())});var x=class r extends Error{constructor(t,s,a,o,i,h){super(h||`HTTP Error ${t} at ${i}: ${s!=null?s:JSON.stringify(a)}`);this.url=i;this.name="FetchError",this.status=t,this.text=s,this.json=a,this.headers=o}static fromResponse(t,s){return g(this,null,function*(){let a=t.status,o=Object.fromEntries([...t.headers.entries()]),i,h,l=t.headers.get("content-type");return t.bodyUsed||(l&&l.includes("application/json")?h=yield t.json():i=yield t.text()),new r(a,i,h,o,s)})}},U=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"}},Ie=class extends Error{constructor(){super("Invalid signal option. It must be an instance of AbortSignal."),this.name="InvalidSignalError"}},Ne=class extends Error{constructor(){super("shapeHandle is required if this isn't an initial fetch (i.e. offset > -1)"),this.name="MissingShapeHandleError"}},Be=class extends Error{constructor(e){super(`Cannot use reserved Electric parameter names in custom params: ${e.join(", ")}`),this.name="ReservedParamError"}},Fe=class extends Error{constructor(e){super(`Column "${e!=null?e:"unknown"}" does not allow NULL values`),this.name="ParserNullValueError"}};var se=class extends Error{constructor(e,t){let s=`The response for the shape request to ${e} didn't include the following required headers:
2
2
  `;t.forEach(a=>{s+=`- ${a}
3
3
  `}),s+=`
4
4
  This is often due to a proxy not setting CORS correctly so that all Electric headers can be read by the client.`,s+=`
5
- For more information visit the troubleshooting guide: /docs/guides/troubleshooting/missing-headers`,super(s)}};var Fe=n=>Number(n),ls=n=>n==="true"||n==="t",fs=n=>BigInt(n),Mt=n=>JSON.parse(n),us=n=>n,ds={int2:Fe,int4:Fe,int8:fs,bool:ls,float4:Fe,float8:Fe,json:Mt,jsonb:Mt};function ps(n,e){let t=0,s=null,a="",o=!1,i=0,h;function f(m,E,k){let v=m.slice(E,k);return v=v==="NULL"?null:v,e?e(v):v}function p(m){let E=[];for(;t<m.length;t++){if(s=m[t],o)s==="\\"?a+=m[++t]:s==='"'?(E.push(e?e(a):a),a="",o=m[t+1]==='"',i=t+2):a+=s;else if(s==='"')o=!0;else if(s==="{")i=++t,E.push(p(m));else if(s==="}"){o=!1,i<t&&E.push(f(m,i,t)),i=t+1;break}else s===","&&h!=="}"&&h!=='"'&&(E.push(f(m,i,t)),i=t+1);h=s}return i<t&&E.push(E.push(f(m,i,t+1))),E}return p(n)[0]}var qe=class{constructor(e,t){this.parser=S(S({},ds),e),this.transformer=t}parse(e,t){return JSON.parse(e,(s,a)=>{if((s==="value"||s==="old_value")&&typeof a=="object"&&a!==null){let o=a;Object.keys(o).forEach(i=>{o[i]=this.parseRow(i,o[i],t)}),this.transformer&&(a=this.transformer(a))}return a})}parseRow(e,t,s){var E;let a=s[e];if(!a)return t;let m=a,{type:o,dims:i}=m,h=Tt(m,["type","dims"]),f=(E=this.parser[o])!=null?E:us,p=vt(f,a,e);return i&&i>0?vt((v,y)=>ps(v,p),a,e)(t):p(t,h)}};function vt(n,e,t){var a;let s=!((a=e.not_null)!=null&&a);return o=>{if(o===null){if(!s)throw new Ie(t!=null?t:"unknown");return null}return n(o,e)}}function ee(n){return"key"in n}function Ne(n){return!ee(n)}function et(n){return Ne(n)&&n.headers.control==="up-to-date"}function Ct(n){let e=n.headers.global_last_seen_lsn;if(e)return`${e}_0`}function tt(n,e){let t=BigInt(n),s=BigInt(e.xmin),a=BigInt(e.xmax),o=e.xip_list.map(BigInt);return t<s||t<a&&!o.includes(t)}var kt="electric-cursor",me="electric-handle",Ve="electric-offset",Ut="electric-schema",Ot="electric-up-to-date",Ht="columns",je="cursor",st="expired_handle",te="handle",O="live",se="offset",Lt="table",Dt="where",It="replica",Bt="params",Ft="experimental_live_sse",rt="live_sse",nt="force-disconnect-and-refresh",it="pause-stream",at="log",ge="subset__where",Ee="subset__limit",Se="subset__offset",Re="subset__order_by",be="subset__params",ot=[O,rt,te,se,je,st,at,ge,Ee,Se,Re,be];var ms=[429],Qe={initialDelay:100,maxDelay:6e4,multiplier:1.3,maxRetries:1/0};function gs(n){if(!n)return 0;let e=Number(n);if(Number.isFinite(e)&&e>0)return e*1e3;let t=Date.parse(n);if(!isNaN(t)){let s=t-Date.now();return Math.max(0,Math.min(s,36e5))}return 0}function qt(n,e=Qe){let{initialDelay:t,maxDelay:s,multiplier:a,debug:o=!1,onFailedAttempt:i,maxRetries:h=1/0}=e;return(...f)=>g(this,null,function*(){var v;let p=f[0],m=f[1],E=t,k=0;for(;;)try{let y=yield n(...f);if(y.ok)return y;throw yield A.fromResponse(y,p.toString())}catch(y){if(i==null||i(),(v=m==null?void 0:m.signal)!=null&&v.aborted)throw new U;if(y instanceof A&&!ms.includes(y.status)&&y.status>=400&&y.status<500)throw y;{if(k++,k>h)throw o&&console.log(`Max retries reached (${k}/${h}), giving up`),y;let Ce=y instanceof A&&y.headers?gs(y.headers["retry-after"]):0,as=Math.random()*E,yt=Math.min(as,s),At=Math.max(Ce,yt);if(o){let Xe=Ce>0?"server+client":"client";console.log(`Retry attempt #${k} after ${At}ms (${Xe}, serverMin=${Ce}ms, clientBackoff=${yt}ms)`)}yield new Promise(Xe=>setTimeout(Xe,At)),E=Math.min(E*a,s)}}})}var Es=[201,204,205];function Nt(n){return(...e)=>g(this,null,function*(){var a,o;let t=e[0],s=yield n(...e);try{if(s.status<200||Es.includes(s.status))return s;let i=yield s.text();return new Response(i,s)}catch(i){throw(o=(a=e[1])==null?void 0:a.signal)!=null&&o.aborted?new U:new A(s.status,void 0,void 0,Object.fromEntries([...s.headers.entries()]),t.toString(),i instanceof Error?i.message:typeof i=="string"?i:"failed to read body")}})}var Ss={maxChunksToPrefetch:2};function Vt(n,e=Ss){let{maxChunksToPrefetch:t}=e,s;return(...o)=>g(this,null,function*(){let i=o[0].toString(),h=s==null?void 0:s.consume(...o);if(h)return h;s==null||s.abort();let f=yield n(...o),p=ht(i,f);return p&&(s=new ct({fetchClient:n,maxPrefetchedRequests:t,url:p,requestInit:o[1]})),f})}var Rs=["electric-offset","electric-handle"],bs=["electric-cursor"],ys=["electric-schema"];function jt(n){return(...e)=>g(this,null,function*(){let t=yield n(...e);if(t.ok){let s=t.headers,a=[],o=m=>a.push(...m.filter(E=>!s.has(E))),h=e[0].toString(),f=new URL(h);if([ge,be,Ee,Se,Re].some(m=>f.searchParams.has(m)))return t;if(o(Rs),f.searchParams.get(O)==="true"&&o(bs),(!f.searchParams.has(O)||f.searchParams.get(O)==="false")&&o(ys),a.length>0)throw new Be(h,a)}return t})}var ye,Ae,H,G,L,re,Ye,ct=class{constructor(e){l(this,re);l(this,ye);l(this,Ae);l(this,H,new Map);l(this,G);l(this,L);var t;c(this,ye,(t=e.fetchClient)!=null?t:(...s)=>fetch(...s)),c(this,Ae,e.maxPrefetchedRequests),c(this,G,e.url.toString()),c(this,L,r(this,G)),d(this,re,Ye).call(this,e.url,e.requestInit)}abort(){r(this,H).forEach(([e,t])=>t.abort())}consume(...e){var a;let t=e[0].toString(),s=(a=r(this,H).get(t))==null?void 0:a[0];if(!(!s||t!==r(this,G)))return r(this,H).delete(t),s.then(o=>{let i=ht(t,o);c(this,G,i),r(this,L)&&!r(this,H).has(r(this,L))&&d(this,re,Ye).call(this,r(this,L),e[1])}).catch(()=>{}),s}};ye=new WeakMap,Ae=new WeakMap,H=new WeakMap,G=new WeakMap,L=new WeakMap,re=new WeakSet,Ye=function(...e){var a,o;let t=e[0].toString();if(r(this,H).size>=r(this,Ae))return;let s=new AbortController;try{let{signal:i,cleanup:h}=As(s,(a=e[1])==null?void 0:a.signal),f=r(this,ye).call(this,t,pe(S({},(o=e[1])!=null?o:{}),{signal:i}));r(this,H).set(t,[f,s]),f.then(p=>{if(!p.ok||s.signal.aborted)return;let m=ht(t,p);if(!m||m===t){c(this,L,void 0);return}return c(this,L,m),d(this,re,Ye).call(this,m,e[1])}).catch(()=>{}).finally(h)}catch(i){}};function ht(n,e){let t=e.headers.get(me),s=e.headers.get(Ve),a=e.headers.has(Ot);if(!t||!s||a)return;let o=new URL(n);if(!o.searchParams.has(O))return o.searchParams.set(te,t),o.searchParams.set(se,s),o.searchParams.sort(),o.toString()}function As(n,e){let t=Ps;if(e)if(e.aborted)n.abort();else{let s=()=>n.abort();e.addEventListener("abort",s,{once:!0,signal:n.signal}),t=()=>e.removeEventListener("abort",s)}return{signal:n.signal,cleanup:t}}function Ps(){}import{fetchEventSource as _s}from"@microsoft/fetch-event-source";var lt=class{constructor(){this.data={};this.max=250;this.storageKey="electric_expired_shapes";this.load()}getExpiredHandle(e){let t=this.data[e];return t?(t.lastUsed=Date.now(),this.save(),t.expiredHandle):null}markExpired(e,t){this.data[e]={expiredHandle:t,lastUsed:Date.now()};let s=Object.keys(this.data);if(s.length>this.max){let a=s.reduce((o,i)=>this.data[i].lastUsed<this.data[o].lastUsed?i:o);delete this.data[a]}this.save()}save(){if(typeof localStorage!="undefined")try{localStorage.setItem(this.storageKey,JSON.stringify(this.data))}catch(e){}}load(){if(typeof localStorage!="undefined")try{let e=localStorage.getItem(this.storageKey);e&&(this.data=JSON.parse(e))}catch(e){this.data={}}}clear(){this.data={},this.save()}},ft=new lt;var Ke=class{constructor(){this.activeSnapshots=new Map;this.xmaxSnapshots=new Map;this.snapshotsByDatabaseLsn=new Map}addSnapshot(e,t){var o,i,h,f;this.activeSnapshots.set(e.snapshot_mark,{xmin:BigInt(e.xmin),xmax:BigInt(e.xmax),xip_list:e.xip_list.map(BigInt),keys:t});let s=(i=(o=this.xmaxSnapshots.get(BigInt(e.xmax)))==null?void 0:o.add(e.snapshot_mark))!=null?i:new Set([e.snapshot_mark]);this.xmaxSnapshots.set(BigInt(e.xmax),s);let a=(f=(h=this.snapshotsByDatabaseLsn.get(BigInt(e.database_lsn)))==null?void 0:h.add(e.snapshot_mark))!=null?f:new Set([e.snapshot_mark]);this.snapshotsByDatabaseLsn.set(BigInt(e.database_lsn),a)}removeSnapshot(e){this.activeSnapshots.delete(e)}shouldRejectMessage(e){let t=e.headers.txids||[];if(t.length===0)return!1;let s=Math.max(...t);for(let[a,o]of this.xmaxSnapshots.entries())if(s>=a)for(let i of o)this.removeSnapshot(i);return[...this.activeSnapshots.values()].some(a=>a.keys.has(e.key)&&tt(s,a))}lastSeenUpdate(e){for(let[t,s]of this.snapshotsByDatabaseLsn.entries())if(t<=e)for(let a of s)this.removeSnapshot(a)}};var xs=new Set([je,te,O,se]);function Qt(n){return g(this,null,function*(){return typeof n=="function"?n():n})}function ws(n){return g(this,null,function*(){let e=Object.entries(n),t=yield Promise.all(e.map(o=>g(this,[o],function*([s,a]){if(a===void 0)return[s,void 0];let i=yield Qt(a);return[s,Array.isArray(i)?i.join(","):i]})));return Object.fromEntries(t.filter(([s,a])=>a!==void 0))})}function Ts(n){return g(this,null,function*(){if(!n)return{};let e=Object.entries(n),t=yield Promise.all(e.map(o=>g(this,[o],function*([s,a]){return[s,yield Qt(a)]})));return Object.fromEntries(t)})}function Yt(n){let e=new URL(n.origin+n.pathname);for(let[t,s]of n.searchParams)ot.includes(t)||e.searchParams.set(t,s);return e.searchParams.sort(),e.toString()}var ne,ie,ae,J,q,C,b,D,z,N,w,X,T,_,V,I,oe,M,Z,B,ce,j,he,xe,Y,F,le,we,Te,Q,We,fe,Ge,Je,Me,u,Pe,_e,dt,Kt,pt,$e,$t,Wt,Gt,mt,gt,Jt,zt,Et,St,Xt,Zt,es,ut=class{constructor(e){l(this,u);l(this,ne,null);l(this,ie);l(this,ae);l(this,J);l(this,q,new Map);l(this,C,!1);l(this,b,"active");l(this,D);l(this,z);l(this,N);l(this,w,!1);l(this,X,!0);l(this,T,!1);l(this,_);l(this,V);l(this,I);l(this,oe);l(this,M);l(this,Z,!1);l(this,B);l(this,ce);l(this,j);l(this,he,Promise.resolve([]));l(this,xe,new Ke);l(this,Y,0);l(this,F);l(this,le);l(this,we);l(this,Te,1e3);l(this,Q,0);l(this,We,3);l(this,fe,!1);l(this,Ge,100);l(this,Je,5e3);l(this,Me);var o,i,h,f;this.options=S({subscribe:!0},e),Ms(this.options),c(this,D,(o=this.options.offset)!=null?o:"-1"),c(this,z,""),c(this,_,this.options.handle),c(this,J,new qe(e.parser,e.transformer)),c(this,oe,this.options.onError),c(this,V,(i=this.options.log)!=null?i:"full");let t=(h=e.fetchClient)!=null?h:(...p)=>fetch(...p),s=pe(S({},(f=e.backoffOptions)!=null?f:Qe),{onFailedAttempt:()=>{var p,m;c(this,T,!1),(m=(p=e.backoffOptions)==null?void 0:p.onFailedAttempt)==null||m.call(p)}}),a=qt(t,s);c(this,ae,jt(Vt(a))),c(this,ie,Nt(r(this,ae))),d(this,u,Xt).call(this)}get shapeHandle(){return r(this,_)}get error(){return r(this,ne)}get isUpToDate(){return r(this,w)}get lastOffset(){return r(this,D)}get mode(){return r(this,V)}subscribe(e,t=()=>{}){let s=Math.random();return r(this,q).set(s,[e,t]),r(this,C)||d(this,u,Pe).call(this),()=>{r(this,q).delete(s)}}unsubscribeAll(){var e;r(this,q).clear(),(e=r(this,Me))==null||e.call(this)}lastSyncedAt(){return r(this,N)}lastSynced(){return r(this,N)===void 0?1/0:Date.now()-r(this,N)}isConnected(){return r(this,T)}isLoading(){return!r(this,w)}hasStarted(){return r(this,C)}isPaused(){return r(this,b)==="paused"}forceDisconnectAndRefresh(){return g(this,null,function*(){var e,t;c(this,Z,!0),r(this,w)&&!((e=r(this,M))!=null&&e.signal.aborted)&&((t=r(this,M))==null||t.abort(nt)),yield d(this,u,Jt).call(this),c(this,Z,!1)})}requestSnapshot(e){return g(this,null,function*(){if(r(this,V)==="full")throw new Error(`Snapshot requests are not supported in ${r(this,V)} mode, as the consumer is guaranteed to observe all data`);r(this,C)||(yield d(this,u,Pe).call(this)),yield d(this,u,zt).call(this),Ue(this,Y)._++;try{r(this,Y)===1&&d(this,u,mt).call(this);let{fetchUrl:t,requestHeaders:s}=yield d(this,u,dt).call(this,this.options.url,!0,e),{metadata:a,data:o}=yield d(this,u,es).call(this,t,s),i=o.concat([{headers:S({control:"snapshot-end"},a)}]);return r(this,xe).addSnapshot(a,new Set(o.map(h=>h.key))),d(this,u,$e).call(this,i,!1),{metadata:a,data:o}}finally{Ue(this,Y)._--,r(this,Y)===0&&d(this,u,gt).call(this)}})}};ne=new WeakMap,ie=new WeakMap,ae=new WeakMap,J=new WeakMap,q=new WeakMap,C=new WeakMap,b=new WeakMap,D=new WeakMap,z=new WeakMap,N=new WeakMap,w=new WeakMap,X=new WeakMap,T=new WeakMap,_=new WeakMap,V=new WeakMap,I=new WeakMap,oe=new WeakMap,M=new WeakMap,Z=new WeakMap,B=new WeakMap,ce=new WeakMap,j=new WeakMap,he=new WeakMap,xe=new WeakMap,Y=new WeakMap,F=new WeakMap,le=new WeakMap,we=new WeakMap,Te=new WeakMap,Q=new WeakMap,We=new WeakMap,fe=new WeakMap,Ge=new WeakMap,Je=new WeakMap,Me=new WeakMap,u=new WeakSet,Pe=function(){return g(this,null,function*(){var e,t,s,a,o;c(this,C,!0);try{yield d(this,u,_e).call(this)}catch(i){if(c(this,ne,i),r(this,oe)){let h=yield r(this,oe).call(this,i);if(h&&typeof h=="object"){h.params&&(this.options.params=S(S({},(e=this.options.params)!=null?e:{}),h.params)),h.headers&&(this.options.headers=S(S({},(t=this.options.headers)!=null?t:{}),h.headers)),c(this,ne,null),c(this,C,!1),yield d(this,u,Pe).call(this);return}i instanceof Error&&d(this,u,St).call(this,i),c(this,T,!1),(s=r(this,j))==null||s.call(this);return}throw i instanceof Error&&d(this,u,St).call(this,i),c(this,T,!1),(a=r(this,j))==null||a.call(this),i}c(this,T,!1),(o=r(this,j))==null||o.call(this)})},_e=function(){return g(this,null,function*(){var f,p;if(r(this,b)==="pause-requested"){c(this,b,"paused");return}if(!this.options.subscribe&&((f=this.options.signal)!=null&&f.aborted||r(this,w)))return;let e=r(this,b)==="paused";c(this,b,"active");let{url:t,signal:s}=this.options,{fetchUrl:a,requestHeaders:o}=yield d(this,u,dt).call(this,t,e),i=yield d(this,u,Kt).call(this,s),h=r(this,M);try{yield d(this,u,$t).call(this,{fetchUrl:a,requestAbortController:h,headers:o,resumingFromPause:e})}catch(m){if((m instanceof A||m instanceof U)&&h.signal.aborted&&h.signal.reason===nt)return d(this,u,_e).call(this);if(m instanceof U){let E=r(this,b);h.signal.aborted&&h.signal.reason===it&&E==="pause-requested"&&c(this,b,"paused");return}if(!(m instanceof A))throw m;if(m.status==409){if(r(this,_)){let k=Yt(a);ft.markExpired(k,r(this,_))}let E=m.headers[me]||`${r(this,_)}-next`;return d(this,u,Zt).call(this,E),yield d(this,u,Et).call(this,Array.isArray(m.json)?m.json:[m.json]),d(this,u,_e).call(this)}else throw m}finally{i&&s&&s.removeEventListener("abort",i),c(this,M,void 0)}return(p=r(this,ce))==null||p.call(this),d(this,u,_e).call(this)})},dt=function(e,t,s){return g(this,null,function*(){let[a,o]=yield Promise.all([Ts(this.options.headers),this.options.params?ws(vs(this.options.params)):void 0]);o&&ts(o);let i=new URL(e);if(o){o.table&&x(i,Lt,o.table),o.where&&x(i,Dt,o.where),o.columns&&x(i,Ht,o.columns),o.replica&&x(i,It,o.replica),o.params&&x(i,Bt,o.params);let p=S({},o);delete p.table,delete p.where,delete p.columns,delete p.replica,delete p.params;for(let[m,E]of Object.entries(p))x(i,m,E)}s&&(s.where&&x(i,ge,s.where),s.params&&x(i,be,s.params),s.limit&&x(i,Ee,s.limit),s.offset&&x(i,Se,s.offset),s.orderBy&&x(i,Re,s.orderBy)),i.searchParams.set(se,r(this,D)),i.searchParams.set(at,r(this,V)),r(this,w)&&(!r(this,Z)&&!t&&i.searchParams.set(O,"true"),i.searchParams.set(je,r(this,z))),r(this,_)&&i.searchParams.set(te,r(this,_));let h=Yt(i),f=ft.getExpiredHandle(h);return f&&i.searchParams.set(st,f),i.searchParams.sort(),{fetchUrl:i,requestHeaders:a}})},Kt=function(e){return g(this,null,function*(){var t;if(c(this,M,new AbortController),e){let s=()=>{var a;(a=r(this,M))==null||a.abort(e.reason)};return e.addEventListener("abort",s,{once:!0}),e.aborted&&((t=r(this,M))==null||t.abort(e.reason)),s}})},pt=function(e){return g(this,null,function*(){var f;let{headers:t,status:s}=e,a=t.get(me);a&&c(this,_,a);let o=t.get(Ve);o&&c(this,D,o);let i=t.get(kt);i&&c(this,z,i);let h=()=>{let p=t.get(Ut);return p?JSON.parse(p):{}};c(this,I,(f=r(this,I))!=null?f:h()),s===204&&c(this,N,Date.now())})},$e=function(e,t=!1){return g(this,null,function*(){var s;if(e.length>0){c(this,X,!0);let a=e[e.length-1];if(et(a)){if(t){let i=Ct(a);i&&c(this,D,i)}c(this,N,Date.now()),c(this,w,!0),c(this,X,!1),(s=r(this,le))==null||s.call(this)}let o=e.filter(i=>ee(i)?!r(this,xe).shouldRejectMessage(i):!0);yield d(this,u,Et).call(this,o)}})},$t=function(e){return g(this,null,function*(){var s;let t=(s=this.options.liveSse)!=null?s:this.options.experimentalLiveSse;return r(this,w)&&t&&!r(this,Z)&&!e.resumingFromPause&&!r(this,fe)?(e.fetchUrl.searchParams.set(Ft,"true"),e.fetchUrl.searchParams.set(rt,"true"),d(this,u,Gt).call(this,e)):d(this,u,Wt).call(this,e)})},Wt=function(e){return g(this,null,function*(){let{fetchUrl:t,requestAbortController:s,headers:a}=e,o=yield r(this,ie).call(this,t.toString(),{signal:s.signal,headers:a});c(this,T,!0),yield d(this,u,pt).call(this,o);let i=r(this,I),f=(yield o.text())||"[]",p=r(this,J).parse(f,i);yield d(this,u,$e).call(this,p)})},Gt=function(e){return g(this,null,function*(){let{fetchUrl:t,requestAbortController:s,headers:a}=e,o=r(this,ae);c(this,we,Date.now());try{let i=[];yield _s(t.toString(),{headers:a,fetch:o,onopen:h=>g(this,null,function*(){c(this,T,!0),yield d(this,u,pt).call(this,h)}),onmessage:h=>{if(h.data){let f=r(this,I),p=r(this,J).parse(h.data,f);i.push(p),et(p)&&(d(this,u,$e).call(this,i,!0),i=[])}},onerror:h=>{throw h},signal:s.signal})}catch(i){throw s.signal.aborted?new U:i}finally{let i=Date.now()-r(this,we),h=s.signal.aborted;if(i<r(this,Te)&&!h)if(Ue(this,Q)._++,r(this,Q)>=r(this,We))c(this,fe,!0),console.warn("[Electric] SSE connections are closing immediately (possibly due to proxy buffering or misconfiguration). Falling back to long polling. Your proxy must support streaming SSE responses (not buffer the complete response). Configuration: Nginx add 'X-Accel-Buffering: no', Caddy add 'flush_interval -1' to reverse_proxy. Note: Do NOT disable caching entirely - Electric uses cache headers to enable request collapsing for efficiency.");else{let f=Math.min(r(this,Je),r(this,Ge)*Math.pow(2,r(this,Q))),p=Math.floor(Math.random()*f);yield new Promise(m=>setTimeout(m,p))}else i>=r(this,Te)&&c(this,Q,0)}})},mt=function(){var e;r(this,C)&&r(this,b)==="active"&&(c(this,b,"pause-requested"),(e=r(this,M))==null||e.abort(it))},gt=function(){r(this,C)&&(r(this,b)==="paused"||r(this,b)==="pause-requested")&&(r(this,b)==="pause-requested"&&c(this,b,"active"),d(this,u,Pe).call(this))},Jt=function(){return g(this,null,function*(){return r(this,B)?r(this,B):(c(this,B,new Promise((e,t)=>{c(this,ce,e),c(this,j,t)})),r(this,B).finally(()=>{c(this,B,void 0),c(this,ce,void 0),c(this,j,void 0)}),r(this,B))})},zt=function(){return g(this,null,function*(){if(r(this,X))return r(this,F)?r(this,F):(c(this,F,new Promise(e=>{c(this,le,e)})),r(this,F).finally(()=>{c(this,F,void 0),c(this,le,void 0)}),r(this,F))})},Et=function(e){return g(this,null,function*(){return c(this,he,r(this,he).then(()=>Promise.all(Array.from(r(this,q).values()).map(a=>g(this,[a],function*([t,s]){try{yield t(e)}catch(o){queueMicrotask(()=>{throw o})}}))))),r(this,he)})},St=function(e){r(this,q).forEach(([t,s])=>{s==null||s(e)})},Xt=function(){if(typeof document=="object"&&typeof document.hidden=="boolean"&&typeof document.addEventListener=="function"){let e=()=>{document.hidden?d(this,u,mt).call(this):d(this,u,gt).call(this)};document.addEventListener("visibilitychange",e),c(this,Me,()=>{document.removeEventListener("visibilitychange",e)})}},Zt=function(e){c(this,D,"-1"),c(this,z,""),c(this,_,e),c(this,w,!1),c(this,X,!0),c(this,T,!1),c(this,I,void 0),c(this,Y,0),c(this,Q,0),c(this,fe,!1)},es=function(e,t){return g(this,null,function*(){let s=yield r(this,ie).call(this,e.toString(),{headers:t});if(!s.ok)throw new A(s.status,void 0,void 0,Object.fromEntries([...s.headers.entries()]),e.toString());let{metadata:a,data:o}=yield s.json(),i=r(this,J).parse(JSON.stringify(o),r(this,I));return{metadata:a,data:i}})},ut.Replica={FULL:"full",DEFAULT:"default"};function ts(n){if(!n)return;let e=Object.keys(n).filter(t=>xs.has(t));if(e.length>0)throw new De(e)}function Ms(n){if(!n.url)throw new Oe;if(n.signal&&!(n.signal instanceof AbortSignal))throw new He;if(n.offset!==void 0&&n.offset!=="-1"&&n.offset!=="now"&&!n.handle)throw new Le;ts(n.params)}function x(n,e,t){if(!(t===void 0||t==null))if(typeof t=="string")n.searchParams.set(e,t);else if(typeof t=="object")for(let[s,a]of Object.entries(t))n.searchParams.set(`${e}[${s}]`,a);else n.searchParams.set(e,t.toString())}function vs(n){return Array.isArray(n.params)?pe(S({},n),{params:Object.fromEntries(n.params.map((e,t)=>[t+1,e]))}):n}var P,K,$,ve,ue,de,W,R,rs,ns,Rt,ze,is,bt,ss=class{constructor(e){l(this,R);l(this,P,new Map);l(this,K,new Map);l(this,$,new Set);l(this,ve,new Set);l(this,ue,!1);l(this,de,"syncing");l(this,W,!1);this.stream=e,this.stream.subscribe(d(this,R,rs).bind(this),d(this,R,is).bind(this))}get isUpToDate(){return r(this,de)==="up-to-date"}get lastOffset(){return this.stream.lastOffset}get handle(){return this.stream.shapeHandle}get rows(){return this.value.then(e=>Array.from(e.values()))}get currentRows(){return Array.from(this.currentValue.values())}get value(){return new Promise((e,t)=>{if(this.stream.isUpToDate)e(this.currentValue);else{let s=this.subscribe(({value:a})=>{s(),r(this,W)&&t(r(this,W)),e(a)})}})}get currentValue(){return r(this,P)}get error(){return r(this,W)}lastSyncedAt(){return this.stream.lastSyncedAt()}lastSynced(){return this.stream.lastSynced()}isLoading(){return this.stream.isLoading()}isConnected(){return this.stream.isConnected()}get mode(){return this.stream.mode}requestSnapshot(e){return g(this,null,function*(){let t=JSON.stringify(e);r(this,ve).add(t),yield d(this,R,Rt).call(this),yield this.stream.requestSnapshot(e)})}subscribe(e){let t=Math.random();return r(this,K).set(t,e),()=>{r(this,K).delete(t)}}unsubscribeAll(){r(this,K).clear()}get numSubscribers(){return r(this,K).size}};P=new WeakMap,K=new WeakMap,$=new WeakMap,ve=new WeakMap,ue=new WeakMap,de=new WeakMap,W=new WeakMap,R=new WeakSet,rs=function(e){let t=!1;e.forEach(s=>{if(ee(s))if(t=d(this,R,ze).call(this,"syncing"),this.mode==="full")switch(s.headers.operation){case"insert":r(this,P).set(s.key,s.value);break;case"update":r(this,P).set(s.key,S(S({},r(this,P).get(s.key)),s.value));break;case"delete":r(this,P).delete(s.key);break}else switch(s.headers.operation){case"insert":r(this,$).add(s.key),r(this,P).set(s.key,s.value);break;case"update":r(this,$).has(s.key)&&r(this,P).set(s.key,S(S({},r(this,P).get(s.key)),s.value));break;case"delete":r(this,$).has(s.key)&&(r(this,P).delete(s.key),r(this,$).delete(s.key));break}if(Ne(s))switch(s.headers.control){case"up-to-date":t=d(this,R,ze).call(this,"up-to-date"),r(this,ue)&&(c(this,ue,!1),d(this,R,ns).call(this));break;case"must-refetch":r(this,P).clear(),r(this,$).clear(),c(this,W,!1),t=d(this,R,ze).call(this,"syncing"),c(this,ue,!0);break}}),t&&d(this,R,bt).call(this)},ns=function(){return g(this,null,function*(){yield d(this,R,Rt).call(this),yield Promise.all(Array.from(r(this,ve)).map(e=>g(this,null,function*(){try{let t=JSON.parse(e);yield this.stream.requestSnapshot(t)}catch(t){}})))})},Rt=function(){return g(this,null,function*(){this.stream.isUpToDate||(yield new Promise(e=>{let t=()=>{this.stream.isUpToDate&&(clearInterval(s),a(),e())},s=setInterval(t,10),a=this.stream.subscribe(()=>t(),()=>t());t()}))})},ze=function(e){let t=r(this,de)!==e;return c(this,de,e),t&&e==="up-to-date"},is=function(e){e instanceof A&&(c(this,W,e),d(this,R,bt).call(this))},bt=function(){r(this,K).forEach(e=>{e({value:this.currentValue,rows:this.currentRows})})};export{Qe as BackoffDefaults,ot as ELECTRIC_PROTOCOL_QUERY_PARAMS,A as FetchError,ss as Shape,ut as ShapeStream,ee as isChangeMessage,Ne as isControlMessage,tt as isVisibleInSnapshot,Qt as resolveValue};
5
+ For more information visit the troubleshooting guide: /docs/guides/troubleshooting/missing-headers`,super(s)}};var qe=r=>Number(r),ys=r=>r==="true"||r==="t",Rs=r=>BigInt(r),It=r=>JSON.parse(r),bs=r=>r,As={int2:qe,int4:qe,int8:Rs,bool:ys,float4:qe,float8:qe,json:It,jsonb:It};function _s(r,e){let t=0,s=null,a="",o=!1,i=0,h;function l(u,E,A){let S=u.slice(E,A);return S=S==="NULL"?null:S,e?e(S):S}function m(u){let E=[];for(;t<u.length;t++){if(s=u[t],o)s==="\\"?a+=u[++t]:s==='"'?(E.push(e?e(a):a),a="",o=u[t+1]==='"',i=t+2):a+=s;else if(s==='"')o=!0;else if(s==="{")i=++t,E.push(m(u));else if(s==="}"){o=!1,i<t&&E.push(l(u,i,t)),i=t+1;break}else s===","&&h!=="}"&&h!=='"'&&(E.push(l(u,i,t)),i=t+1);h=s}return i<t&&E.push(E.push(l(u,i,t+1))),E}return m(r)[0]}var je=class{constructor(e,t){this.parser=R(R({},As),e),this.transformer=t}parse(e,t){return JSON.parse(e,(s,a)=>(s==="value"||s==="old_value")&&typeof a=="object"&&a!==null?this.transformMessageValue(a,t):a)}parseSnapshotData(e,t){return e.map(s=>{let a=s;return a.value&&typeof a.value=="object"&&a.value!==null&&(a.value=this.transformMessageValue(a.value,t)),a.old_value&&typeof a.old_value=="object"&&a.old_value!==null&&(a.old_value=this.transformMessageValue(a.old_value,t)),a})}transformMessageValue(e,t){let s=e;return Object.keys(s).forEach(a=>{s[a]=this.parseRow(a,s[a],t)}),this.transformer?this.transformer(s):s}parseRow(e,t,s){var E;let a=s[e];if(!a)return t;let u=a,{type:o,dims:i}=u,h=Ht(u,["type","dims"]),l=(E=this.parser[o])!=null?E:bs,m=Nt(l,a,e);return i&&i>0?Nt((S,y)=>_s(S,m),a,e)(t):m(t,h)}};function Nt(r,e,t){var a;let s=!((a=e.not_null)!=null&&a);return o=>{if(o===null){if(!s)throw new Fe(t!=null?t:"unknown");return null}return r(o,e)}}function nt(r){var h,l,m,u;let e=(l=(h=r.match(/^_+/))==null?void 0:h[0])!=null?l:"",t=r.slice(e.length),s=(u=(m=t.match(/_+$/))==null?void 0:m[0])!=null?u:"",i=(s?t.slice(0,t.length-s.length):t).toLowerCase().replace(/_+([a-z])/g,(E,A)=>A.toUpperCase());return e+i+s}function Bt(r){return r.replace(/([a-z])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").toLowerCase()}function Ft(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 Ve(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=[],a=0;for(;a<r.length;){let h=r[a];if(h==="'"||h==='"'){let l=a,m=h;for(a++;a<r.length;)if(r[a]===m)if(r[a+1]===m)a+=2;else{a++;break}else a++;s.push({start:l,end:a})}else a++}let o=h=>s.some(l=>h>=l.start&&h<l.end),i=new RegExp("(?<![a-zA-Z0-9_])([a-zA-Z_][a-zA-Z0-9_]*)(?![a-zA-Z0-9_])","g");return r.replace(i,(h,l,m)=>o(m)||t.has(h.toUpperCase())||h.startsWith("$")?h:e(h))}function xs(r){if(r){let e={};for(let t of Object.keys(r))e[t]=nt(t);return Ft(e)}return{decode:e=>nt(e),encode:e=>Bt(e)}}function re(r){return"key"in r}function Ye(r){return!re(r)}function at(r){return Ye(r)&&r.headers.control==="up-to-date"}function qt(r){let e=r.headers.global_last_seen_lsn;if(e)return`${e}_0`}function it(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 jt="electric-cursor",ye="electric-handle",We="electric-offset",ot="electric-schema",Vt="electric-up-to-date",Yt="columns",Ke="cursor",ct="expired_handle",ne="handle",O="live",ae="offset",Wt="table",Kt="where",Qt="replica",$t="params",Gt="experimental_live_sse",ht="live_sse",lt="force-disconnect-and-refresh",ut="pause-stream",dt="log",Re="subset__where",be="subset__limit",Ae="subset__offset",_e="subset__order_by",xe="subset__params",ft=[O,ht,ne,ae,Ke,ct,dt,Re,be,Ae,_e,xe];var Ps=[429],$e={initialDelay:100,maxDelay:6e4,multiplier:1.3,maxRetries:1/0};function Ts(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 zt(r,e=$e){let{initialDelay:t,maxDelay:s,multiplier:a,debug:o=!1,onFailedAttempt:i,maxRetries:h=1/0}=e;return(...l)=>g(this,null,function*(){var S;let m=l[0],u=l[1],E=t,A=0;for(;;)try{let y=yield r(...l);if(y.ok)return y;throw yield x.fromResponse(y,m.toString())}catch(y){if(i==null||i(),(S=u==null?void 0:u.signal)!=null&&S.aborted)throw new U;if(y instanceof x&&!Ps.includes(y.status)&&y.status>=400&&y.status<500)throw y;{if(A++,A>h)throw o&&console.log(`Max retries reached (${A}/${h}), giving up`),y;let q=y instanceof x&&y.headers?Ts(y.headers["retry-after"]):0,ms=Math.random()*E,Ct=Math.min(ms,s),kt=Math.max(q,Ct);if(o){let st=q>0?"server+client":"client";console.log(`Retry attempt #${A} after ${kt}ms (${st}, serverMin=${q}ms, clientBackoff=${Ct}ms)`)}yield new Promise(st=>setTimeout(st,kt)),E=Math.min(E*a,s)}}})}var ws=[201,204,205];function Jt(r){return(...e)=>g(this,null,function*(){var a,o;let t=e[0],s=yield r(...e);try{if(s.status<200||ws.includes(s.status))return s;let i=yield s.text();return new Response(i,s)}catch(i){throw(o=(a=e[1])==null?void 0:a.signal)!=null&&o.aborted?new U:new x(s.status,void 0,void 0,Object.fromEntries([...s.headers.entries()]),t.toString(),i instanceof Error?i.message:typeof i=="string"?i:"failed to read body")}})}var Ms={maxChunksToPrefetch:2};function Zt(r,e=Ms){let{maxChunksToPrefetch:t}=e,s;return(...o)=>g(this,null,function*(){let i=o[0].toString(),h=s==null?void 0:s.consume(...o);if(h)return h;s==null||s.abort();let l=yield r(...o),m=mt(i,l);return m&&(s=new pt({fetchClient:r,maxPrefetchedRequests:t,url:m,requestInit:o[1]})),l})}var vs=["electric-offset","electric-handle"],Cs=["electric-cursor"],ks=["electric-schema"];function Xt(r){return(...e)=>g(this,null,function*(){let t=yield r(...e);if(t.ok){let s=t.headers,a=[],o=u=>a.push(...u.filter(E=>!s.has(E))),h=e[0].toString(),l=new URL(h);if([Re,xe,be,Ae,_e].some(u=>l.searchParams.has(u)))return t;if(o(vs),l.searchParams.get(O)==="true"&&o(Cs),(!l.searchParams.has(O)||l.searchParams.get(O)==="false")&&o(ks),a.length>0)throw new se(h,a)}return t})}var Pe,Te,L,J,D,ie,Qe,pt=class{constructor(e){d(this,ie);d(this,Pe);d(this,Te);d(this,L,new Map);d(this,J);d(this,D);var t;c(this,Pe,(t=e.fetchClient)!=null?t:(...s)=>fetch(...s)),c(this,Te,e.maxPrefetchedRequests),c(this,J,e.url.toString()),c(this,D,n(this,J)),p(this,ie,Qe).call(this,e.url,e.requestInit)}abort(){n(this,L).forEach(([e,t])=>t.abort())}consume(...e){var a;let t=e[0].toString(),s=(a=n(this,L).get(t))==null?void 0:a[0];if(!(!s||t!==n(this,J)))return n(this,L).delete(t),s.then(o=>{let i=mt(t,o);c(this,J,i),n(this,D)&&!n(this,L).has(n(this,D))&&p(this,ie,Qe).call(this,n(this,D),e[1])}).catch(()=>{}),s}};Pe=new WeakMap,Te=new WeakMap,L=new WeakMap,J=new WeakMap,D=new WeakMap,ie=new WeakSet,Qe=function(...e){var a,o;let t=e[0].toString();if(n(this,L).size>=n(this,Te))return;let s=new AbortController;try{let{signal:i,cleanup:h}=Us(s,(a=e[1])==null?void 0:a.signal),l=n(this,Pe).call(this,t,Se(R({},(o=e[1])!=null?o:{}),{signal:i}));n(this,L).set(t,[l,s]),l.then(m=>{if(!m.ok||s.signal.aborted)return;let u=mt(t,m);if(!u||u===t){c(this,D,void 0);return}return c(this,D,u),p(this,ie,Qe).call(this,u,e[1])}).catch(()=>{}).finally(h)}catch(i){}};function mt(r,e){let t=e.headers.get(ye),s=e.headers.get(We),a=e.headers.has(Vt);if(!t||!s||a)return;let o=new URL(r);if(!o.searchParams.has(O))return o.searchParams.set(ne,t),o.searchParams.set(ae,s),o.searchParams.sort(),o.toString()}function Us(r,e){let t=Os;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 Os(){}import{fetchEventSource as Ls}from"@microsoft/fetch-event-source";var gt=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 gt;var St=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 a=s.reduce((o,i)=>this.data[i].timestamp<this.data[o].timestamp?i:o);delete this.data[a]}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 a of t)e-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(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()}},yt=new St;var Ge=class{constructor(){this.activeSnapshots=new Map;this.xmaxSnapshots=new Map;this.snapshotsByDatabaseLsn=new Map}addSnapshot(e,t){var o,i,h,l;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=(l=(h=this.snapshotsByDatabaseLsn.get(BigInt(e.database_lsn)))==null?void 0:h.add(e.snapshot_mark))!=null?l: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)&&it(s,a))}lastSeenUpdate(e){for(let[t,s]of this.snapshotsByDatabaseLsn.entries())if(t<=e)for(let a of s)this.removeSnapshot(a)}};var Ds=new Set([Ke,ne,O,ae]);function ts(r){return g(this,null,function*(){return typeof r=="function"?r():r})}function Hs(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 ts(a);return[s,Array.isArray(i)?i.join(","):i]})));return Object.fromEntries(t.filter(([s,a])=>a!==void 0))})}function Is(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 ts(a)]})));return Object.fromEntries(t)})}function ze(r){let e=new URL(r.origin+r.pathname);for(let[t,s]of r.searchParams)ft.includes(t)||e.searchParams.set(t,s);return e.searchParams.sort(),e.toString()}var oe,ce,he,Z,j,k,_,H,I,V,T,X,M,w,Y,N,le,v,ee,B,ue,W,de,ve,K,F,fe,te,pe,Ce,ke,Q,Ze,me,Xe,et,Ue,f,bt,we,Me,At,ss,_t,Je,rs,ns,as,xt,Pt,is,os,Tt,wt,cs,hs,Rt=class{constructor(e){d(this,f);d(this,oe,null);d(this,ce);d(this,he);d(this,Z);d(this,j,new Map);d(this,k,!1);d(this,_,"active");d(this,H);d(this,I);d(this,V);d(this,T,!1);d(this,X,!0);d(this,M,!1);d(this,w);d(this,Y);d(this,N);d(this,le);d(this,v);d(this,ee,!1);d(this,B);d(this,ue);d(this,W);d(this,de,Promise.resolve([]));d(this,ve,new Ge);d(this,K,0);d(this,F);d(this,fe);d(this,te);d(this,pe);d(this,Ce);d(this,ke,1e3);d(this,Q,0);d(this,Ze,3);d(this,me,!1);d(this,Xe,100);d(this,et,5e3);d(this,Ue);var i,h,l,m;this.options=R({subscribe:!0},e),Ns(this.options),c(this,H,(i=this.options.offset)!=null?i:"-1"),c(this,I,""),c(this,w,this.options.handle);let t;if(e.columnMapper){let u=E=>{let A={};for(let[S,y]of Object.entries(E)){let q=e.columnMapper.decode(S);A[q]=y}return A};t=e.transformer?E=>e.transformer(u(E)):u}else t=e.transformer;c(this,Z,new je(e.parser,t)),c(this,le,this.options.onError),c(this,Y,(h=this.options.log)!=null?h:"full");let s=(l=e.fetchClient)!=null?l:(...u)=>fetch(...u),a=Se(R({},(m=e.backoffOptions)!=null?m:$e),{onFailedAttempt:()=>{var u,E;c(this,M,!1),(E=(u=e.backoffOptions)==null?void 0:u.onFailedAttempt)==null||E.call(u)}}),o=zt(s,a);c(this,he,Xt(Zt(o))),c(this,ce,Jt(n(this,he))),p(this,f,cs).call(this)}get shapeHandle(){return n(this,w)}get error(){return n(this,oe)}get isUpToDate(){return n(this,T)}get lastOffset(){return n(this,H)}get mode(){return n(this,Y)}subscribe(e,t=()=>{}){let s=Math.random();return n(this,j).set(s,[e,t]),n(this,k)||p(this,f,we).call(this),()=>{n(this,j).delete(s)}}unsubscribeAll(){var e;n(this,j).clear(),(e=n(this,Ue))==null||e.call(this)}lastSyncedAt(){return n(this,V)}lastSynced(){return n(this,V)===void 0?1/0:Date.now()-n(this,V)}isConnected(){return n(this,M)}isLoading(){return!n(this,T)}hasStarted(){return n(this,k)}isPaused(){return n(this,_)==="paused"}forceDisconnectAndRefresh(){return g(this,null,function*(){var e,t;c(this,ee,!0),n(this,T)&&!((e=n(this,v))!=null&&e.signal.aborted)&&((t=n(this,v))==null||t.abort(lt)),yield p(this,f,is).call(this),c(this,ee,!1)})}requestSnapshot(e){return g(this,null,function*(){if(n(this,Y)==="full")throw new Error(`Snapshot requests are not supported in ${n(this,Y)} mode, as the consumer is guaranteed to observe all data`);n(this,k)||(yield p(this,f,we).call(this)),yield p(this,f,os).call(this),De(this,K)._++;try{n(this,K)===1&&p(this,f,xt).call(this);let{metadata:t,data:s}=yield this.fetchSnapshot(e),a=s.concat([{headers:R({control:"snapshot-end"},t)}]);return n(this,ve).addSnapshot(t,new Set(s.map(o=>o.key))),p(this,f,Je).call(this,a,!1),{metadata:t,data:s}}finally{De(this,K)._--,n(this,K)===0&&p(this,f,Pt).call(this)}})}fetchSnapshot(e){return g(this,null,function*(){var m;let{fetchUrl:t,requestHeaders:s}=yield p(this,f,At).call(this,this.options.url,!0,e),a=yield n(this,ce).call(this,t.toString(),{headers:s});if(!a.ok)throw new x(a.status,void 0,void 0,Object.fromEntries([...a.headers.entries()]),t.toString());let o=(m=n(this,N))!=null?m:es(a.headers,{required:!0,url:t.toString()}),{metadata:i,data:h}=yield a.json(),l=n(this,Z).parseSnapshotData(h,o);return{metadata:i,data:l}})}};oe=new WeakMap,ce=new WeakMap,he=new WeakMap,Z=new WeakMap,j=new WeakMap,k=new WeakMap,_=new WeakMap,H=new WeakMap,I=new WeakMap,V=new WeakMap,T=new WeakMap,X=new WeakMap,M=new WeakMap,w=new WeakMap,Y=new WeakMap,N=new WeakMap,le=new WeakMap,v=new WeakMap,ee=new WeakMap,B=new WeakMap,ue=new WeakMap,W=new WeakMap,de=new WeakMap,ve=new WeakMap,K=new WeakMap,F=new WeakMap,fe=new WeakMap,te=new WeakMap,pe=new WeakMap,Ce=new WeakMap,ke=new WeakMap,Q=new WeakMap,Ze=new WeakMap,me=new WeakMap,Xe=new WeakMap,et=new WeakMap,Ue=new WeakMap,f=new WeakSet,bt=function(){return n(this,te)!==void 0},we=function(){return g(this,null,function*(){var e,t,s,a,o;c(this,k,!0);try{yield p(this,f,Me).call(this)}catch(i){if(c(this,oe,i),n(this,le)){let h=yield n(this,le).call(this,i);if(h&&typeof h=="object"){h.params&&(this.options.params=R(R({},(e=this.options.params)!=null?e:{}),h.params)),h.headers&&(this.options.headers=R(R({},(t=this.options.headers)!=null?t:{}),h.headers)),c(this,oe,null),c(this,k,!1),yield p(this,f,we).call(this);return}i instanceof Error&&p(this,f,wt).call(this,i),c(this,M,!1),(s=n(this,W))==null||s.call(this);return}throw i instanceof Error&&p(this,f,wt).call(this,i),c(this,M,!1),(a=n(this,W))==null||a.call(this),i}c(this,M,!1),(o=n(this,W))==null||o.call(this)})},Me=function(){return g(this,null,function*(){var l,m;if(n(this,_)==="pause-requested"){c(this,_,"paused");return}if(!this.options.subscribe&&((l=this.options.signal)!=null&&l.aborted||n(this,T)))return;let e=n(this,_)==="paused";c(this,_,"active");let{url:t,signal:s}=this.options,{fetchUrl:a,requestHeaders:o}=yield p(this,f,At).call(this,t,e),i=yield p(this,f,ss).call(this,s),h=n(this,v);try{yield p(this,f,rs).call(this,{fetchUrl:a,requestAbortController:h,headers:o,resumingFromPause:e})}catch(u){if((u instanceof x||u instanceof U)&&h.signal.aborted&&h.signal.reason===lt)return p(this,f,Me).call(this);if(u instanceof U){let E=n(this,_);h.signal.aborted&&h.signal.reason===ut&&E==="pause-requested"&&c(this,_,"paused");return}if(!(u instanceof x))throw u;if(u.status==409){if(n(this,w)){let A=ze(a);Et.markExpired(A,n(this,w))}let E=u.headers[ye]||`${n(this,w)}-next`;return p(this,f,hs).call(this,E),yield p(this,f,Tt).call(this,Array.isArray(u.json)?u.json:[u.json]),p(this,f,Me).call(this)}else throw u}finally{i&&s&&s.removeEventListener("abort",i),c(this,v,void 0)}return(m=n(this,ue))==null||m.call(this),p(this,f,Me).call(this)})},At=function(e,t,s){return g(this,null,function*(){var u,E,A;let[a,o]=yield Promise.all([Is(this.options.headers),this.options.params?Hs(Bs(this.options.params)):void 0]);o&&ls(o);let i=new URL(e);if(o){if(o.table&&C(i,Wt,o.table),o.where&&typeof o.where=="string"){let y=Ve(o.where,(u=this.options.columnMapper)==null?void 0:u.encode);C(i,Kt,y)}o.columns&&C(i,Yt,o.columns),o.replica&&C(i,Qt,o.replica),o.params&&C(i,$t,o.params);let S=R({},o);delete S.table,delete S.where,delete S.columns,delete S.replica,delete S.params;for(let[y,q]of Object.entries(S))C(i,y,q)}if(s){if(s.where&&typeof s.where=="string"){let S=Ve(s.where,(E=this.options.columnMapper)==null?void 0:E.encode);C(i,Re,S)}if(s.params&&i.searchParams.set(xe,JSON.stringify(s.params)),s.limit&&C(i,be,s.limit),s.offset&&C(i,Ae,s.offset),s.orderBy&&typeof s.orderBy=="string"){let S=Ve(s.orderBy,(A=this.options.columnMapper)==null?void 0:A.encode);C(i,_e,S)}}i.searchParams.set(ae,n(this,H)),i.searchParams.set(dt,n(this,Y));let h=s!==void 0;n(this,T)&&!h&&(!n(this,ee)&&!t&&i.searchParams.set(O,"true"),i.searchParams.set(Ke,n(this,I))),n(this,w)&&i.searchParams.set(ne,n(this,w));let l=ze(i),m=Et.getExpiredHandle(l);return m&&i.searchParams.set(ct,m),i.searchParams.sort(),{fetchUrl:i,requestHeaders:a}})},ss=function(e){return g(this,null,function*(){var t;if(c(this,v,new AbortController),e){let s=()=>{var a;(a=n(this,v))==null||a.abort(e.reason)};return e.addEventListener("abort",s,{once:!0}),e.aborted&&((t=n(this,v))==null||t.abort(e.reason)),s}})},_t=function(e){return g(this,null,function*(){var h;let{headers:t,status:s}=e,a=t.get(ye);a&&c(this,w,a);let o=t.get(We);o&&c(this,H,o);let i=t.get(jt);i&&c(this,I,i),c(this,N,(h=n(this,N))!=null?h:es(t)),s===204&&c(this,V,Date.now())})},Je=function(e,t=!1){return g(this,null,function*(){var s;if(e.length>0){c(this,X,!0);let a=e[e.length-1];if(at(a)){if(t){let i=qt(a);i&&c(this,H,i)}if(c(this,V,Date.now()),c(this,T,!0),c(this,X,!1),(s=n(this,fe))==null||s.call(this),n(this,f,bt)&&!t&&n(this,I)===n(this,te))return;if(c(this,te,void 0),n(this,pe)){let i=ze(n(this,pe));yt.recordUpToDate(i,n(this,I))}}let o=e.filter(i=>re(i)?!n(this,ve).shouldRejectMessage(i):!0);yield p(this,f,Tt).call(this,o)}})},rs=function(e){return g(this,null,function*(){var s;if(c(this,pe,e.fetchUrl),!n(this,T)&&!n(this,f,bt)){let a=ze(e.fetchUrl),o=yt.shouldEnterReplayMode(a);o&&c(this,te,o)}let t=(s=this.options.liveSse)!=null?s:this.options.experimentalLiveSse;return n(this,T)&&t&&!n(this,ee)&&!e.resumingFromPause&&!n(this,me)?(e.fetchUrl.searchParams.set(Gt,"true"),e.fetchUrl.searchParams.set(ht,"true"),p(this,f,as).call(this,e)):p(this,f,ns).call(this,e)})},ns=function(e){return g(this,null,function*(){let{fetchUrl:t,requestAbortController:s,headers:a}=e,o=yield n(this,ce).call(this,t.toString(),{signal:s.signal,headers:a});c(this,M,!0),yield p(this,f,_t).call(this,o);let i=n(this,N),l=(yield o.text())||"[]",m=n(this,Z).parse(l,i);yield p(this,f,Je).call(this,m)})},as=function(e){return g(this,null,function*(){let{fetchUrl:t,requestAbortController:s,headers:a}=e,o=n(this,he);c(this,Ce,Date.now());try{let i=[];yield Ls(t.toString(),{headers:a,fetch:o,onopen:h=>g(this,null,function*(){c(this,M,!0),yield p(this,f,_t).call(this,h)}),onmessage:h=>{if(h.data){let l=n(this,N),m=n(this,Z).parse(h.data,l);i.push(m),at(m)&&(p(this,f,Je).call(this,i,!0),i=[])}},onerror:h=>{throw h},signal:s.signal})}catch(i){throw s.signal.aborted?new U:i}finally{let i=Date.now()-n(this,Ce),h=s.signal.aborted;if(i<n(this,ke)&&!h)if(De(this,Q)._++,n(this,Q)>=n(this,Ze))c(this,me,!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 l=Math.min(n(this,et),n(this,Xe)*Math.pow(2,n(this,Q))),m=Math.floor(Math.random()*l);yield new Promise(u=>setTimeout(u,m))}else i>=n(this,ke)&&c(this,Q,0)}})},xt=function(){var e;n(this,k)&&n(this,_)==="active"&&(c(this,_,"pause-requested"),(e=n(this,v))==null||e.abort(ut))},Pt=function(){n(this,k)&&(n(this,_)==="paused"||n(this,_)==="pause-requested")&&(n(this,_)==="pause-requested"&&c(this,_,"active"),p(this,f,we).call(this))},is=function(){return g(this,null,function*(){return n(this,B)?n(this,B):(c(this,B,new Promise((e,t)=>{c(this,ue,e),c(this,W,t)})),n(this,B).finally(()=>{c(this,B,void 0),c(this,ue,void 0),c(this,W,void 0)}),n(this,B))})},os=function(){return g(this,null,function*(){if(n(this,X))return n(this,F)?n(this,F):(c(this,F,new Promise(e=>{c(this,fe,e)})),n(this,F).finally(()=>{c(this,F,void 0),c(this,fe,void 0)}),n(this,F))})},Tt=function(e){return g(this,null,function*(){return c(this,de,n(this,de).then(()=>Promise.all(Array.from(n(this,j).values()).map(a=>g(this,[a],function*([t,s]){try{yield t(e)}catch(o){queueMicrotask(()=>{throw o})}}))))),n(this,de)})},wt=function(e){n(this,j).forEach(([t,s])=>{s==null||s(e)})},cs=function(){if(typeof document=="object"&&typeof document.hidden=="boolean"&&typeof document.addEventListener=="function"){let e=()=>{document.hidden?p(this,f,xt).call(this):p(this,f,Pt).call(this)};document.addEventListener("visibilitychange",e),c(this,Ue,()=>{document.removeEventListener("visibilitychange",e)})}},hs=function(e){c(this,H,"-1"),c(this,I,""),c(this,w,e),c(this,T,!1),c(this,X,!0),c(this,M,!1),c(this,N,void 0),c(this,K,0),c(this,Q,0),c(this,me,!1)},Rt.Replica={FULL:"full",DEFAULT:"default"};function es(r,e){let t=r.get(ot);if(!t){if(e!=null&&e.required&&(e!=null&&e.url))throw new se(e.url,[ot]);return{}}return JSON.parse(t)}function ls(r){if(!r)return;let e=Object.keys(r).filter(t=>Ds.has(t));if(e.length>0)throw new Be(e)}function Ns(r){if(!r.url)throw new He;if(r.signal&&!(r.signal instanceof AbortSignal))throw new Ie;if(r.offset!==void 0&&r.offset!=="-1"&&r.offset!=="now"&&!r.handle)throw new Ne;ls(r.params)}function C(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 Bs(r){return Array.isArray(r.params)?Se(R({},r),{params:Object.fromEntries(r.params.map((e,t)=>[t+1,e]))}):r}var P,$,G,Oe,ge,Ee,z,b,ds,fs,Mt,tt,ps,vt,us=class{constructor(e){d(this,b);d(this,P,new Map);d(this,$,new Map);d(this,G,new Set);d(this,Oe,new Set);d(this,ge,!1);d(this,Ee,"syncing");d(this,z,!1);this.stream=e,this.stream.subscribe(p(this,b,ds).bind(this),p(this,b,ps).bind(this))}get isUpToDate(){return n(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:a})=>{s(),n(this,z)&&t(n(this,z)),e(a)})}})}get currentValue(){return n(this,P)}get error(){return n(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}requestSnapshot(e){return g(this,null,function*(){let t=JSON.stringify(e);n(this,Oe).add(t),yield p(this,b,Mt).call(this),yield this.stream.requestSnapshot(e)})}subscribe(e){let t=Math.random();return n(this,$).set(t,e),()=>{n(this,$).delete(t)}}unsubscribeAll(){n(this,$).clear()}get numSubscribers(){return n(this,$).size}};P=new WeakMap,$=new WeakMap,G=new WeakMap,Oe=new WeakMap,ge=new WeakMap,Ee=new WeakMap,z=new WeakMap,b=new WeakSet,ds=function(e){let t=!1;e.forEach(s=>{if(re(s))if(t=p(this,b,tt).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,R(R({},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,G).add(s.key),n(this,P).set(s.key,s.value);break;case"update":n(this,G).has(s.key)&&n(this,P).set(s.key,R(R({},n(this,P).get(s.key)),s.value));break;case"delete":n(this,G).has(s.key)&&(n(this,P).delete(s.key),n(this,G).delete(s.key));break}if(Ye(s))switch(s.headers.control){case"up-to-date":t=p(this,b,tt).call(this,"up-to-date"),n(this,ge)&&(c(this,ge,!1),p(this,b,fs).call(this));break;case"must-refetch":n(this,P).clear(),n(this,G).clear(),c(this,z,!1),t=p(this,b,tt).call(this,"syncing"),c(this,ge,!0);break}}),t&&p(this,b,vt).call(this)},fs=function(){return g(this,null,function*(){yield p(this,b,Mt).call(this),yield Promise.all(Array.from(n(this,Oe)).map(e=>g(this,null,function*(){try{let t=JSON.parse(e);yield this.stream.requestSnapshot(t)}catch(t){}})))})},Mt=function(){return g(this,null,function*(){this.stream.isUpToDate||(yield new Promise(e=>{let t=()=>{this.stream.isUpToDate&&(clearInterval(s),a(),e())},s=setInterval(t,10),a=this.stream.subscribe(()=>t(),()=>t());t()}))})},tt=function(e){let t=n(this,Ee)!==e;return c(this,Ee,e),t&&e==="up-to-date"},ps=function(e){e instanceof x&&(c(this,z,e),p(this,b,vt).call(this))},vt=function(){n(this,$).forEach(e=>{e({value:this.currentValue,rows:this.currentRows})})};export{$e as BackoffDefaults,ft as ELECTRIC_PROTOCOL_QUERY_PARAMS,x as FetchError,us as Shape,Rt as ShapeStream,Bt as camelToSnake,Ft as createColumnMapper,re as isChangeMessage,Ye as isControlMessage,it as isVisibleInSnapshot,ts as resolveValue,xs as snakeCamelMapper,nt as snakeToCamel};
6
6
  //# sourceMappingURL=index.browser.mjs.map