prostgles-client 1.5.138 → 1.5.139

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.
@@ -62,15 +62,15 @@ export declare type MultiSyncHandles<T = POJO> = {
62
62
  $unsync: () => void;
63
63
  $upsert: (newData: T[]) => any;
64
64
  };
65
- export declare type SubscriptionSingle<T = POJO> = {
66
- _onChange: (data: T, delta?: Partial<T>) => T;
67
- notify: (data: T, delta?: Partial<T>) => T;
65
+ export declare type SubscriptionSingle<T = POJO, Full extends boolean = false> = {
66
+ _onChange: SingleChangeListener<T, Full>;
67
+ notify: (data: T, delta?: DeepPartial<T>) => T;
68
68
  idObj: Partial<T>;
69
69
  handlesOnData?: boolean;
70
- handles?: SingleSyncHandles;
70
+ handles?: SingleSyncHandles<T, Full>;
71
71
  };
72
72
  export declare type SubscriptionMulti<T = POJO> = {
73
- _onChange: (data: T[], delta: Partial<T>[]) => T[];
73
+ _onChange: MultiChangeListener<T>;
74
74
  notify: (data: T[], delta: Partial<T>[]) => T[];
75
75
  idObj?: Partial<T>;
76
76
  handlesOnData?: boolean;
@@ -82,7 +82,7 @@ declare const STORAGE_TYPES: {
82
82
  readonly object: "object";
83
83
  };
84
84
  export declare type MultiChangeListener<T = POJO> = (items: SyncDataItem<T>[], delta: DeepPartial<T>[]) => any;
85
- export declare type SingleChangeListener<T = POJO, Full extends boolean = false> = (item: SyncDataItem<T, Full>, delta: DeepPartial<T>) => any;
85
+ export declare type SingleChangeListener<T = POJO, Full extends boolean = false> = (item: SyncDataItem<T, Full>, delta?: DeepPartial<T>) => any;
86
86
  export declare type SyncedTableOptions = {
87
87
  name: string;
88
88
  filter?: POJO;
@@ -98,6 +98,10 @@ export declare type SyncedTableOptions = {
98
98
  onReady: () => any;
99
99
  skipIncomingDeltaCheck?: boolean;
100
100
  };
101
+ export declare type DbTableSync = {
102
+ unsync: () => void;
103
+ syncData: (data?: AnyObject[], deleted?: AnyObject[], cb?: (err?: any) => void) => void;
104
+ };
101
105
  export declare class SyncedTable {
102
106
  db: any;
103
107
  name: string;
@@ -123,7 +127,7 @@ export declare class SyncedTable {
123
127
  get multiSubscriptions(): SubscriptionMulti[];
124
128
  set singleSubscriptions(sSubs: SubscriptionSingle[]);
125
129
  get singleSubscriptions(): SubscriptionSingle[];
126
- dbSync: any;
130
+ dbSync?: DbTableSync;
127
131
  items: POJO[];
128
132
  storageType: string;
129
133
  itemsObj: POJO;
@@ -152,13 +156,13 @@ export declare class SyncedTable {
152
156
  * @param onChange change listener <(item: object, delta: object) => any >
153
157
  * @param handlesOnData If true then $update, $delete and $unsync handles will be added on the data item. True by default;
154
158
  */
155
- syncOne<T = POJO>(idObj: Partial<T>, onChange: SingleChangeListener, handlesOnData?: boolean): SingleSyncHandles<T>;
159
+ syncOne<T = POJO, Full extends boolean = false>(idObj: Partial<T>, onChange: SingleChangeListener<T, Full>, handlesOnData?: boolean): SingleSyncHandles<T, Full>;
156
160
  /**
157
161
  * Notifies multi subs with ALL data + deltas. Attaches handles on data if required
158
162
  * @param newData -> updates. Must include id_fields + updates
159
163
  */
160
164
  private notifySubscribers;
161
- unsubscribe: (onChange: any) => string;
165
+ unsubscribe: (onChange: Function) => string;
162
166
  private getIdStr;
163
167
  private getIdObj;
164
168
  private getRowSyncObj;
@@ -185,7 +189,7 @@ export declare class SyncedTable {
185
189
  * @param from_server : <boolean> If false then updates will be sent to server
186
190
  */
187
191
  upsert: (items: ItemUpdate[], from_server?: boolean) => Promise<any>;
188
- getItem<T = POJO>(idObj: Partial<T>): {
192
+ getItem<T = AnyObject>(idObj: Partial<T>): {
189
193
  data?: T;
190
194
  index: number;
191
195
  };
@@ -196,7 +200,7 @@ export declare class SyncedTable {
196
200
  * @param isFullData
197
201
  * @param deleteItem
198
202
  */
199
- setItem(item: POJO, index: number, isFullData?: boolean, deleteItem?: boolean): void;
203
+ setItem(item: POJO, index: number | undefined, isFullData?: boolean, deleteItem?: boolean): void;
200
204
  /**
201
205
  * Sets the current data
202
206
  * @param items data
@@ -205,7 +209,7 @@ export declare class SyncedTable {
205
209
  /**
206
210
  * Returns the current data ordered by synced_field ASC and matching the main filter;
207
211
  */
208
- getItems: () => POJO[];
212
+ getItems: () => AnyObject[];
209
213
  /**
210
214
  * Sync data request
211
215
  * @param param0: SyncBatchRequest
@@ -219,12 +223,14 @@ export declare class SyncedTable {
219
223
  * @param item
220
224
  * @returns {boolean}
221
225
  */
222
- export declare function isObject(item: AnyObject): boolean;
226
+ export declare function isObject(item: any): item is AnyObject;
223
227
  /**
224
228
  * Deep merge two objects.
225
229
  * @param target
226
230
  * @param ...sources
227
231
  */
228
232
  export declare function mergeDeep(target: AnyObject, ...sources: AnyObject[]): AnyObject;
233
+ export declare const isDefined: <T>(v: void | T | undefined) => v is T;
234
+ export declare function getKeys<T>(o: T): Array<keyof T>;
229
235
  export {};
230
236
  //# sourceMappingURL=SyncedTable.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"SyncedTable.d.ts","sourceRoot":"","sources":["../lib/SyncedTable.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAyB,GAAG,EAAW,SAAS,EAAqB,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAClI,oBAAY,IAAI,GAAG;IAAE,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAA;CAAE,CAAC;AAI1C,eAAO,MAAM,KAAK,EAAE,GAInB,CAAC;AAMF,oBAAY,WAAW,GAAG,OAAO,CAAC,kBAAkB,CAAC,GAAG;IACpD,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,aAAa,CAAC,EAAE,OAAO,CAAC;CAC3B,CAAA;AACD,oBAAY,cAAc,GAAG,OAAO,CAAC,kBAAkB,CAAC,GAAG;IACvD,aAAa,CAAC,EAAE,OAAO,CAAC;CAC3B,CAAA;AAED;;GAEG;AACH,oBAAY,IAAI,GAAG,CAAC,CAAC,GAAG,IAAI,EAAE,WAAW,EAAE,GAAG,EAAE,OAAO,EAAE,WAAW,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AAC,MAAM,CAAC,CAAC,CAE/C"}
@@ -1,14 +1,15 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.mergeDeep = exports.isObject = exports.SyncedTable = exports.debug = void 0;
3
+ exports.getKeys = exports.isDefined = exports.mergeDeep = exports.isObject = exports.SyncedTable = exports.debug = void 0;
4
4
  const prostgles_types_1 = require("prostgles-types");
5
5
  const DEBUG_KEY = "DEBUG_SYNCEDTABLE";
6
6
  const hasWnd = typeof window !== "undefined";
7
- exports.debug = function (...args) {
7
+ const debug = function (...args) {
8
8
  if (hasWnd && window[DEBUG_KEY]) {
9
9
  window[DEBUG_KEY](...args);
10
10
  }
11
11
  };
12
+ exports.debug = debug;
12
13
  const STORAGE_TYPES = {
13
14
  array: "array",
14
15
  localStorage: "localStorage",
@@ -47,11 +48,11 @@ class SyncedTable {
47
48
  if (initial) {
48
49
  txtCols.map(c => {
49
50
  if (!id_keys.includes(c.name) && c.name in current) {
50
- patchedDelta = patchedDelta || { ...current };
51
- patchedDelta[c.name] = prostgles_types_1.getTextPatch(initial[c.name], current[c.name]);
51
+ patchedDelta !== null && patchedDelta !== void 0 ? patchedDelta : (patchedDelta = { ...current });
52
+ patchedDelta[c.name] = (0, prostgles_types_1.getTextPatch)(initial[c.name], current[c.name]);
52
53
  }
53
54
  });
54
- if (patchedDelta) {
55
+ if (patchedDelta && this.wal) {
55
56
  patchedItems.push(patchedDelta);
56
57
  patched.push([
57
58
  this.wal.getIdObj(patchedDelta),
@@ -140,7 +141,7 @@ class SyncedTable {
140
141
  this.unsubscribe = (onChange) => {
141
142
  this.singleSubscriptions = this.singleSubscriptions.filter(s => s._onChange !== onChange);
142
143
  this.multiSubscriptions = this.multiSubscriptions.filter(s => s._onChange !== onChange);
143
- exports.debug("unsubscribe", this);
144
+ (0, exports.debug)("unsubscribe", this);
144
145
  return "ok";
145
146
  };
146
147
  this.unsync = () => {
@@ -153,11 +154,11 @@ class SyncedTable {
153
154
  this.singleSubscriptions = [];
154
155
  this.itemsObj = {};
155
156
  this.items = [];
156
- this.onChange = null;
157
+ this.onChange = undefined;
157
158
  };
158
159
  this.delete = async (item, from_server = false) => {
159
160
  const idObj = this.getIdObj(item);
160
- this.setItem(idObj, null, true, true);
161
+ this.setItem(idObj, undefined, true, true);
161
162
  if (!from_server) {
162
163
  await this.db[this.name].delete(idObj);
163
164
  }
@@ -183,6 +184,7 @@ class SyncedTable {
183
184
  * @param from_server : <boolean> If false then updates will be sent to server
184
185
  */
185
186
  this.upsert = async (items, from_server = false) => {
187
+ var _a;
186
188
  if ((!items || !items.length) && !from_server)
187
189
  throw "No data provided for upsert";
188
190
  /* If data has been deleted then wait for it to sync with server before continuing */
@@ -211,7 +213,7 @@ class SyncedTable {
211
213
  }
212
214
  let oItm = this.getItem(idObj), oldIdx = oItm.index, oldItem = oItm.data;
213
215
  /* Calc delta if missing or if from server */
214
- if ((from_server || prostgles_types_1.isEmpty(delta)) && !prostgles_types_1.isEmpty(oldItem)) {
216
+ if ((from_server || (0, prostgles_types_1.isEmpty)(delta)) && !(0, prostgles_types_1.isEmpty)(oldItem)) {
215
217
  delta = this.getDelta(oldItem || {}, delta);
216
218
  }
217
219
  /* Add synced if local update */
@@ -238,6 +240,8 @@ class SyncedTable {
238
240
  status = "inserted";
239
241
  }
240
242
  this.setItem(newItem, oldIdx);
243
+ if (!status)
244
+ throw "changeInfo status missing";
241
245
  let changeInfo = { idObj, delta, oldItem, newItem, status, from_server };
242
246
  // const idStr = this.getIdStr(idObj);
243
247
  /* IF Local updates then Keep any existing oldItem to revert to the earliest working item */
@@ -285,7 +289,7 @@ class SyncedTable {
285
289
  current: { ...newItem }
286
290
  });
287
291
  }
288
- if (changeInfo.delta && !prostgles_types_1.isEmpty(changeInfo.delta)) {
292
+ if (changeInfo.delta && !(0, prostgles_types_1.isEmpty)(changeInfo.delta)) {
289
293
  results.push(changeInfo);
290
294
  }
291
295
  /* TODO: Deletes from server */
@@ -301,7 +305,7 @@ class SyncedTable {
301
305
  /* Push to server */
302
306
  if (!from_server && walItems.length) {
303
307
  // this.addWALItems(walItems);
304
- this.wal.addData(walItems);
308
+ (_a = this.wal) === null || _a === void 0 ? void 0 : _a.addData(walItems);
305
309
  }
306
310
  };
307
311
  /**
@@ -352,14 +356,14 @@ class SyncedTable {
352
356
  const s_fields = [this.synced_field, ...this.id_fields.sort()];
353
357
  items = items
354
358
  .filter(d => {
355
- return !this.filter || !Object.keys(this.filter)
359
+ return !this.filter || !getKeys(this.filter)
356
360
  .find(key => d[key] !== this.filter[key]
357
361
  // typeof d[key] === typeof this.filter[key] &&
358
362
  // d[key].toString && this.filter[key].toString &&
359
363
  // d[key].toString() !== this.filter[key].toString()
360
364
  );
361
365
  })
362
- .sort((a, b) => s_fields.map(key => a[key] < b[key] ? -1 : a[key] > b[key] ? 1 : 0).find(v => v));
366
+ .sort((a, b) => s_fields.map(key => (a[key] < b[key] ? -1 : a[key] > b[key] ? 1 : 0)).find(v => v));
363
367
  }
364
368
  else
365
369
  throw "id_fields AND/OR synced_field missing";
@@ -370,7 +374,7 @@ class SyncedTable {
370
374
  * Sync data request
371
375
  * @param param0: SyncBatchRequest
372
376
  */
373
- this.getBatch = ({ from_synced, to_synced, offset, limit } = { offset: 0, limit: null }) => {
377
+ this.getBatch = ({ from_synced, to_synced, offset, limit } = { offset: 0, limit: undefined }) => {
374
378
  let items = this.getItems();
375
379
  // params = params || {};
376
380
  // const { from_synced, to_synced, offset = 0, limit = null } = params;
@@ -378,7 +382,7 @@ class SyncedTable {
378
382
  .filter(c => (!Number.isFinite(from_synced) || +c[this.synced_field] >= +from_synced) &&
379
383
  (!Number.isFinite(to_synced) || +c[this.synced_field] <= +to_synced));
380
384
  if (offset || limit)
381
- res = res.splice(offset, limit || res.length);
385
+ res = res.splice(offset !== null && offset !== void 0 ? offset : 0, limit || res.length);
382
386
  return res;
383
387
  };
384
388
  this.name = name;
@@ -409,12 +413,12 @@ class SyncedTable {
409
413
  this.singleSubscriptions = [];
410
414
  this.onError = onError || function (err) { console.error("Sync internal error: ", err); };
411
415
  const onSyncRequest = (params) => {
412
- let res = { c_lr: null, c_fr: null, c_count: 0 };
416
+ let res = { c_lr: undefined, c_fr: undefined, c_count: 0 };
413
417
  let batch = this.getBatch(params);
414
418
  if (batch.length) {
415
419
  res = {
416
- c_fr: this.getRowSyncObj(batch[0]) || null,
417
- c_lr: this.getRowSyncObj(batch[batch.length - 1]) || null,
420
+ c_fr: this.getRowSyncObj(batch[0]),
421
+ c_lr: this.getRowSyncObj(batch[batch.length - 1]),
418
422
  c_count: batch.length
419
423
  };
420
424
  }
@@ -428,8 +432,9 @@ class SyncedTable {
428
432
  // console.log(`onPullRequest: total(${ data.length })`)
429
433
  return data;
430
434
  }, onUpdates = async (args) => {
435
+ var _a;
431
436
  if ("err" in args && args.err) {
432
- this.onError(args.err);
437
+ (_a = this.onError) === null || _a === void 0 ? void 0 : _a.call(this, args.err);
433
438
  }
434
439
  else if ("isSynced" in args && args.isSynced && !this.isSynced) {
435
440
  this.isSynced = args.isSynced;
@@ -456,7 +461,7 @@ class SyncedTable {
456
461
  }
457
462
  return true;
458
463
  };
459
- db[this.name]._sync(filter, { select }, { onSyncRequest, onPullRequest, onUpdates }).then(s => {
464
+ db[this.name]._sync(filter, { select }, { onSyncRequest, onPullRequest, onUpdates }).then((s) => {
460
465
  this.dbSync = s;
461
466
  function confirmExit() { return "Data may be lost. Are you sure?"; }
462
467
  this.wal = new prostgles_types_1.WAL({
@@ -500,13 +505,13 @@ class SyncedTable {
500
505
  if (this.onChange && !this.skipFirstTrigger) {
501
506
  setTimeout(this.onChange, 0);
502
507
  }
503
- exports.debug(this);
508
+ (0, exports.debug)(this);
504
509
  }
505
510
  /**
506
511
  * add debug mode to fix sudden no data and sync listeners bug
507
512
  */
508
513
  set multiSubscriptions(mSubs) {
509
- exports.debug(mSubs, this._multiSubscriptions);
514
+ (0, exports.debug)(mSubs, this._multiSubscriptions);
510
515
  this._multiSubscriptions = mSubs.slice(0);
511
516
  }
512
517
  ;
@@ -515,7 +520,7 @@ class SyncedTable {
515
520
  }
516
521
  ;
517
522
  set singleSubscriptions(sSubs) {
518
- exports.debug(sSubs, this._singleSubscriptions);
523
+ (0, exports.debug)(sSubs, this._singleSubscriptions);
519
524
  this._singleSubscriptions = sSubs.slice(0);
520
525
  }
521
526
  ;
@@ -617,7 +622,7 @@ class SyncedTable {
617
622
  /* DROPPED SYNC BUG */
618
623
  if (!this.singleSubscriptions.length && !this.multiSubscriptions.length) {
619
624
  console.warn("No sync listeners");
620
- exports.debug("nosync", this._singleSubscriptions, this._multiSubscriptions);
625
+ (0, exports.debug)("nosync", this._singleSubscriptions, this._multiSubscriptions);
621
626
  }
622
627
  this.upsert([{ idObj, delta: newData, opts }]);
623
628
  },
@@ -681,8 +686,8 @@ class SyncedTable {
681
686
  matchesFilter(item) {
682
687
  return Boolean(item &&
683
688
  (!this.filter ||
684
- prostgles_types_1.isEmpty(this.filter) ||
685
- !Object.keys(this.filter).find(k => this.filter[k] !== item[k])));
689
+ (0, prostgles_types_1.isEmpty)(this.filter) ||
690
+ this.filter && !Object.keys(this.filter).find(k => this.filter[k] !== item[k])));
686
691
  }
687
692
  matchesIdObj(a, b) {
688
693
  return Boolean(a && b && !this.id_fields.sort().find(k => a[k] !== b[k]));
@@ -718,7 +723,7 @@ class SyncedTable {
718
723
  * @param n new data item
719
724
  */
720
725
  getDelta(o, n) {
721
- if (prostgles_types_1.isEmpty(o))
726
+ if ((0, prostgles_types_1.isEmpty)(o))
722
727
  return { ...n };
723
728
  return Object.keys({ ...o, ...n })
724
729
  .filter(k => !this.id_fields.includes(k))
@@ -774,13 +779,11 @@ class SyncedTable {
774
779
  * @param deleteItem
775
780
  */
776
781
  setItem(item, index, isFullData = false, deleteItem = false) {
777
- const getExIdx = (arr) => index; // arr.findIndex(d => this.matchesIdObj(d, item));
778
782
  if (this.storageType === STORAGE_TYPES.localStorage) {
779
783
  let items = this.getItems();
780
784
  if (!deleteItem) {
781
- let existing_idx = getExIdx(items);
782
- if (items[existing_idx])
783
- items[existing_idx] = isFullData ? { ...item } : { ...items[existing_idx], ...item };
785
+ if (index !== undefined && items[index])
786
+ items[index] = isFullData ? { ...item } : { ...items[index], ...item };
784
787
  else
785
788
  items.push(item);
786
789
  }
@@ -791,10 +794,10 @@ class SyncedTable {
791
794
  }
792
795
  else if (this.storageType === STORAGE_TYPES.array) {
793
796
  if (!deleteItem) {
794
- if (!this.items[index]) {
797
+ if (index !== undefined && !this.items[index]) {
795
798
  this.items.push(item);
796
799
  }
797
- else {
800
+ else if (index !== undefined) {
798
801
  this.items[index] = isFullData ? { ...item } : { ...this.items[index], ...item };
799
802
  }
800
803
  }
@@ -847,3 +850,9 @@ function mergeDeep(target, ...sources) {
847
850
  return mergeDeep(target, ...sources);
848
851
  }
849
852
  exports.mergeDeep = mergeDeep;
853
+ const isDefined = (v) => v !== undefined && v !== null;
854
+ exports.isDefined = isDefined;
855
+ function getKeys(o) {
856
+ return Object.keys(o);
857
+ }
858
+ exports.getKeys = getKeys;
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- !function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var n=t();for(var i in n)("object"==typeof exports?exports:e)[i]=n[i]}}(this||window,(function(){return(()=>{var e={133:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mergeDeep=t.isObject=t.SyncedTable=t.debug=void 0;const i=n(792),s="DEBUG_SYNCEDTABLE",r="undefined"!=typeof window;t.debug=function(...e){r&&window[s]&&window[s](...e)};const o={array:"array",localStorage:"localStorage",object:"object"};class a{constructor({name:e,filter:n,onChange:s,onReady:a,db:l,skipFirstTrigger:h=!1,select:d="*",storageType:u="object",patchText:f=!1,patchJSON:m=!1,onError:g}){if(this.throttle=100,this.batch_size=50,this.skipFirstTrigger=!1,this.columns=[],this._multiSubscriptions=[],this._singleSubscriptions=[],this.items=[],this.itemsObj={},this.isSynced=!1,this.updatePatches=async e=>{let t=e.map((e=>e.current)),n=[],s=[];if(this.columns&&this.columns.length&&this.db[this.name].updateBatch&&(this.patchText||this.patchJSON)){const r=this.columns.filter((e=>"text"===e.data_type));if(this.patchText&&r.length){t=[];const o=[this.synced_field,...this.id_fields];await Promise.all(e.slice(0).map((async(e,a)=>{const{current:l,initial:c}={...e};let h;c&&(r.map((e=>{!o.includes(e.name)&&e.name in l&&(h=h||{...l},h[e.name]=i.getTextPatch(c[e.name],l[e.name]))})),h&&(s.push(h),n.push([this.wal.getIdObj(h),this.wal.getDeltaObj(h)]))),h||t.push(l)})))}}if(n.length)try{await this.db[this.name].updateBatch(n)}catch(e){console.log("failed to patch update",e),t=t.concat(s)}return t.filter((e=>e))},this.notifySubscribers=(e=[])=>{if(!this.isSynced)return;let t=[],n=[],i=[];e.map((({idObj:e,newItem:s,delta:r})=>{this.singleSubscriptions.filter((t=>this.matchesIdObj(t.idObj,e))).map((async e=>{try{await e.notify(s,r)}catch(e){console.error("SyncedTable failed to notify: ",e)}})),this.matchesFilter(s)&&(t.push(s),n.push(r),i.push(e))}));let s=[],r=[];if(this.getItems().map((e=>{s.push({...e});const i=t.findIndex((t=>this.matchesIdObj(e,t)));r.push(n[i])})),this.onChange)try{this.onChange(s,r)}catch(e){console.error("SyncedTable failed to notify onChange: ",e)}this.multiSubscriptions.map((async e=>{try{await e.notify(s,r)}catch(e){console.error("SyncedTable failed to notify: ",e)}}))},this.unsubscribe=e=>(this.singleSubscriptions=this.singleSubscriptions.filter((t=>t._onChange!==e)),this.multiSubscriptions=this.multiSubscriptions.filter((t=>t._onChange!==e)),t.debug("unsubscribe",this),"ok"),this.unsync=()=>{this.dbSync&&this.dbSync.unsync&&this.dbSync.unsync()},this.destroy=()=>{this.unsync(),this.multiSubscriptions=[],this.singleSubscriptions=[],this.itemsObj={},this.items=[],this.onChange=null},this.delete=async(e,t=!1)=>{const n=this.getIdObj(e);return this.setItem(n,null,!0,!0),t||await this.db[this.name].delete(n),this.notifySubscribers(),!0},this.checkItemCols=e=>{if(this.columns&&this.columns.length){const t=Object.keys({...e}).filter((e=>!this.columns.find((t=>t.name===e))));if(t.length)throw"Unexpected columns in sync item update: "+t.join(", ")}},this.upsert=async(e,t=!1)=>{if(!(e&&e.length||t))throw"No data provided for upsert";let n,s=[],r=[];await Promise.all(e.map((async(e,o)=>{var a;let l={...e.idObj},h={...e.delta};Object.keys(h).map((e=>{void 0===h[e]&&(h[e]=null)})),t||this.checkItemCols({...e.delta,...e.idObj});let d=this.getItem(l),u=d.index,f=d.data;!t&&!i.isEmpty(h)||i.isEmpty(f)||(h=this.getDelta(f||{},h)),t||(h[this.synced_field]=Date.now());let m={...f,...h,...l};f&&!t&&(null===(a=e.opts)||void 0===a?void 0:a.deepMerge)&&(m=c({...f,...l},{...h})),f&&f[this.synced_field]<m[this.synced_field]?n="updated":f||(n="inserted"),this.setItem(m,u);let g={idObj:l,delta:h,oldItem:f,newItem:m,status:n,from_server:t};return t||r.push({initial:f,current:{...m}}),g.delta&&!i.isEmpty(g.delta)&&s.push(g),!0}))).catch((e=>{console.error("SyncedTable failed upsert: ",e)})),this.notifySubscribers(s),!t&&r.length&&this.wal.addData(r)},this.setItems=e=>{if(this.storageType===o.localStorage){if(!r)throw"Cannot access window object. Choose another storage method (array OR object)";window.localStorage.setItem(this.name,JSON.stringify(e))}else this.storageType===o.array?this.items=e:this.itemsObj=e.reduce(((e,t)=>({...e,[this.getIdStr(t)]:{...t}})),{})},this.getItems=()=>{let e=[];if(this.storageType===o.localStorage){if(!r)throw"Cannot access window object. Choose another storage method (array OR object)";let t=window.localStorage.getItem(this.name);if(t)try{e=JSON.parse(t)}catch(e){console.error(e)}}else e=this.storageType===o.array?this.items.map((e=>({...e}))):Object.values({...this.itemsObj});if(!this.id_fields||!this.synced_field)throw"id_fields AND/OR synced_field missing";{const t=[this.synced_field,...this.id_fields.sort()];e=e.filter((e=>!this.filter||!Object.keys(this.filter).find((t=>e[t]!==this.filter[t])))).sort(((e,n)=>t.map((t=>e[t]<n[t]?-1:e[t]>n[t]?1:0)).find((e=>e))))}return e.map((e=>({...e})))},this.getBatch=({from_synced:e,to_synced:t,offset:n,limit:i}={offset:0,limit:null})=>{let s=this.getItems().map((e=>({...e}))).filter((n=>(!Number.isFinite(e)||+n[this.synced_field]>=+e)&&(!Number.isFinite(t)||+n[this.synced_field]<=+t)));return(n||i)&&(s=s.splice(n,i||s.length)),s},this.name=e,this.filter=n,this.select=d,this.onChange=s,!o[u])throw"Invalid storage type. Expecting one of: "+Object.keys(o).join(", ");if(r||u!==o.localStorage||(console.warn("Could not set storageType to localStorage: window object missing\nStorage changed to object"),u="object"),this.storageType=u,this.patchText=f,this.patchJSON=m,!l)throw"db missing";this.db=l;const{id_fields:p,synced_field:y,throttle:b=100,batch_size:S=50}=l[this.name]._syncInfo;if(!p||!y)throw"id_fields/synced_field missing";this.id_fields=p,this.synced_field=y,this.batch_size=S,this.throttle=b,this.skipFirstTrigger=h,this.multiSubscriptions=[],this.singleSubscriptions=[],this.onError=g||function(e){console.error("Sync internal error: ",e)},l[this.name]._sync(n,{select:d},{onSyncRequest:e=>{let t={c_lr:null,c_fr:null,c_count:0},n=this.getBatch(e);return n.length&&(t={c_fr:this.getRowSyncObj(n[0])||null,c_lr:this.getRowSyncObj(n[n.length-1])||null,c_count:n.length}),t},onPullRequest:async e=>this.getBatch(e),onUpdates:async e=>{if("err"in e&&e.err)this.onError(e.err);else if("isSynced"in e&&e.isSynced&&!this.isSynced){this.isSynced=e.isSynced;let t=this.getItems().map((e=>({...e})));this.setItems([]);const n=t.map((e=>({idObj:this.getIdObj(e),delta:{...e}})));await this.upsert(n,!0)}else if("data"in e){let t=e.data.map((e=>({idObj:this.getIdObj(e),delta:e})));await this.upsert(t,!0)}else console.error("Unexpected onUpdates");return!0}}).then((e=>{function t(){return"Data may be lost. Are you sure?"}this.dbSync=e,this.wal=new i.WAL({id_fields:p,synced_field:y,throttle:b,batch_size:S,onSendStart:()=>{r&&(window.onbeforeunload=t)},onSend:async(e,t)=>(await this.updatePatches(t)).length?this.dbSync.syncData(e):[],onSendEnd:()=>{r&&(window.onbeforeunload=null)}}),a()})),l[this.name].getColumns&&l[this.name].getColumns().then((e=>{this.columns=e})),this.onChange&&!this.skipFirstTrigger&&setTimeout(this.onChange,0),t.debug(this)}set multiSubscriptions(e){t.debug(e,this._multiSubscriptions),this._multiSubscriptions=e.slice(0)}get multiSubscriptions(){return this._multiSubscriptions}set singleSubscriptions(e){t.debug(e,this._singleSubscriptions),this._singleSubscriptions=e.slice(0)}get singleSubscriptions(){return this._singleSubscriptions}static create(e){return new Promise(((t,n)=>{try{const n=new a({...e,onReady:()=>{setTimeout((()=>{t(n)}),0)}})}catch(e){n(e)}}))}sync(e,t=!0){const n={$unsync:()=>this.unsubscribe(e),$upsert:e=>{if(e){const t=e=>({idObj:this.getIdObj(e),delta:e});Array.isArray(e)?this.upsert(e.map((e=>t(e)))):this.upsert([t(e)])}}},i={_onChange:e,handlesOnData:t,handles:n,notify:(n,i)=>{let s=[...n],r=[...i];return t&&(s=s.map(((n,i)=>{const s=(n,i)=>({...n,...this.makeSingleSyncHandles(i,e),$get:()=>s(this.getItem(i).data,i),$find:e=>s(this.getItem(e).data,e),$update:(e,t)=>this.upsert([{idObj:i,delta:e,opts:t}]).then((e=>!0)),$delete:async()=>this.delete(i),$cloneMultiSync:e=>this.sync(e,t)}),r=this.wal.getIdObj(n);return s(n,r)}))),e(s,r)}};return this.multiSubscriptions.push(i),this.skipFirstTrigger||setTimeout((()=>{let e=this.getItems();i.notify(e,e)}),0),Object.freeze({...n})}makeSingleSyncHandles(e,n){if(!e||!n)throw"syncOne(idObj, onChange) -> MISSING idObj or onChange";return{$get:()=>this.getItem(e).data,$find:e=>this.getItem(e).data,$unsync:()=>this.unsubscribe(n),$delete:()=>this.delete(e),$update:(n,i)=>{this.singleSubscriptions.length||this.multiSubscriptions.length||(console.warn("No sync listeners"),t.debug("nosync",this._singleSubscriptions,this._multiSubscriptions)),this.upsert([{idObj:e,delta:n,opts:i}])},$cloneSync:t=>this.syncOne(e,t),$cloneMultiSync:e=>this.sync(e,!0)}}syncOne(e,t,n=!0){const i=this.makeSingleSyncHandles(e,t),s={_onChange:t,idObj:e,handlesOnData:n,handles:i,notify:(e,s)=>{let r={...e};return n&&(r.$get=i.$get,r.$find=i.$find,r.$update=i.$update,r.$delete=i.$delete,r.$unsync=i.$unsync,r.$cloneSync=i.$cloneSync),t(r,s)}};return this.singleSubscriptions.push(s),setTimeout((()=>{let e=i.$get();e&&s.notify(e,e)}),0),Object.freeze({...i})}getIdStr(e){return this.id_fields.sort().map((t=>`${e[t]||""}`)).join(".")}getIdObj(e){let t={};return this.id_fields.sort().map((n=>{t[n]=e[n]})),t}getRowSyncObj(e){let t={};return[this.synced_field,...this.id_fields].sort().map((n=>{t[n]=e[n]})),t}matchesFilter(e){return Boolean(e&&(!this.filter||i.isEmpty(this.filter)||!Object.keys(this.filter).find((t=>this.filter[t]!==e[t]))))}matchesIdObj(e,t){return Boolean(e&&t&&!this.id_fields.sort().find((n=>e[n]!==t[n])))}getDelta(e,t){return i.isEmpty(e)?{...t}:Object.keys({...e,...t}).filter((e=>!this.id_fields.includes(e))).reduce(((n,i)=>{let s={};if(i in t&&t[i]!==e[i]){let n={[i]:t[i]};t[i]&&e[i]&&"object"==typeof e[i]?JSON.stringify(t[i])!==JSON.stringify(e[i])&&(s=n):s=n}return{...n,...s}}),{})}deleteAll(){this.getItems().map((e=>this.delete(e)))}getItem(e){let t;return this.storageType===o.localStorage?t=this.getItems().find((t=>this.matchesIdObj(t,e))):this.storageType===o.array?t=this.items.find((t=>this.matchesIdObj(t,e))):(this.itemsObj=this.itemsObj||{},t={...this.itemsObj}[this.getIdStr(e)]),{data:t?{...t}:t,index:-1}}setItem(e,t,n=!1,i=!1){if(this.storageType===o.localStorage){let s=this.getItems();if(i)s=s.filter((t=>!this.matchesIdObj(t,e)));else{let i=t;s[i]?s[i]=n?{...e}:{...s[i],...e}:s.push(e)}r&&window.localStorage.setItem(this.name,JSON.stringify(s))}else if(this.storageType===o.array)i?this.items=this.items.filter((t=>!this.matchesIdObj(t,e))):this.items[t]?this.items[t]=n?{...e}:{...this.items[t],...e}:this.items.push(e);else if(this.itemsObj=this.itemsObj||{},i)delete this.itemsObj[this.getIdStr(e)];else{let t=this.itemsObj[this.getIdStr(e)]||{};this.itemsObj[this.getIdStr(e)]=n?{...e}:{...t,...e}}}}function l(e){return e&&"object"==typeof e&&!Array.isArray(e)}function c(e,...t){if(!t.length)return e;const n=t.shift();if(l(e)&&l(n))for(const t in n)l(n[t])?(e[t]||Object.assign(e,{[t]:{}}),c(e[t],n[t])):Object.assign(e,{[t]:n[t]});return c(e,...t)}t.SyncedTable=a,t.isObject=l,t.mergeDeep=c},274:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.prostgles=t.debug=void 0;const i=n(792),s="DEBUG_SYNCEDTABLE",r="undefined"!=typeof window;t.debug=function(...e){r&&window[s]&&window[s](...e)},t.prostgles=function(e,n){const{socket:s,onReady:r,onDisconnect:o,onReconnect:a,onSchemaChange:l=!0}=e;if(t.debug("prostgles",{initOpts:e}),l){let e;"function"==typeof l&&(e=l),s.removeAllListeners(i.CHANNELS.SCHEMA_CHANGED),e&&s.on(i.CHANNELS.SCHEMA_CHANGED,e)}const c=i.CHANNELS._preffix;let h,d={},u={},f={},m={},g=!1;function p(e,n){return t.debug("_unsubscribe",{channelName:e,handler:n}),new Promise(((t,i)=>{d[e]?(d[e].handlers=d[e].handlers.filter((e=>e!==n)),d[e].handlers.length||(s.emit(e+"unsubscribe",{},((e,t)=>{e&&console.error(e)})),s.removeListener(e,d[e].onCall),delete d[e]),t(!0)):t(!0)}))}function y({tableName:e,command:t,param1:n,param2:i},r){return new Promise(((o,a)=>{s.emit(c,{tableName:e,command:t,param1:n,param2:i},((e,t)=>{if(e)console.error(e),a(e);else if(t){const{id_fields:e,synced_field:n,channelName:i}=t;s.emit(i,{onSyncRequest:r({},t)},(e=>{console.log(e)})),o({id_fields:e,synced_field:n,channelName:i})}}))}))}function b({tableName:e,command:t,param1:n,param2:i}){return new Promise(((r,o)=>{s.emit(c,{tableName:e,command:t,param1:n,param2:i},((e,t)=>{e?(console.error(e),o(e)):t&&r(t.channelName)}))}))}async function S(e,{tableName:t,command:n,param1:i,param2:r},o,a){function l(n){let s={unsubscribe:function(){return p(n,o)},filter:{...i}};return e[t].update&&(s={...s,update:function(n,s){return e[t].update(i,n,s)}}),e[t].delete&&(s={...s,delete:function(n){return e[t].delete(i,n)}}),Object.freeze(s)}const c=Object.keys(d).find((e=>{let s=d[e];return s.tableName===t&&s.command===n&&JSON.stringify(s.param1||{})===JSON.stringify(i||{})&&JSON.stringify(s.param2||{})===JSON.stringify(r||{})}));if(c)return d[c].handlers.push(o),setTimeout((()=>{o&&(null==d?void 0:d[c].lastData)&&o(null==d?void 0:d[c].lastData)}),10),l(c);{const e=await b({tableName:t,command:n,param1:i,param2:r});let c=function(t,n){d[e]?t.data?(d[e].lastData=t.data,d[e].handlers.map((e=>{e(t.data)}))):t.err?d[e].errorHandlers.map((e=>{e(t.err)})):console.error("INTERNAL ERROR: Unexpected data format from subscription: ",t):console.warn("Orphaned subscription: ",e)},h=a||function(t){console.error(`Uncaught error within running subscription \n ${e}`,t)};return s.on(e,c),d[e]={lastData:void 0,tableName:t,command:n,param1:i,param2:r,onCall:c,handlers:[o],errorHandlers:[h],destroy:()=>{d[e]&&(Object.values(d[e]).map((t=>{t&&t.handlers&&t.handlers.map((t=>p(e,t)))})),delete d[e])}},l(e)}}return new Promise(((e,l)=>{o&&s.on("disconnect",o),s.on(i.CHANNELS.SCHEMA,(({schema:o,methods:p,fullSchema:_,auth:O,rawSQL:j,joinTables:w=[],err:N})=>{if(N)throw l(N),N;t.debug("destroySyncs",{subscriptions:d,syncedTables:u}),Object.values(d).map((e=>e.destroy())),d={},f={},Object.values(u).map((e=>{e&&e.destroy&&e.destroy()})),u={},g&&a&&a(s),g=!0;let v=JSON.parse(JSON.stringify(o)),C=JSON.parse(JSON.stringify(p)),T={},E={};if(O){if(O.pathGuard){const e=e=>{var t,n;(null==e?void 0:e.shouldReload)&&"undefined"!=typeof window&&(null===(n=null===(t=null===window||void 0===window?void 0:window.location)||void 0===t?void 0:t.reload)||void 0===n||n.call(t))};s.emit(i.CHANNELS.AUTHGUARD,JSON.stringify(window.location),((t,n)=>{e(n)})),s.removeAllListeners(i.CHANNELS.AUTHGUARD),s.on(i.CHANNELS.AUTHGUARD,(t=>{e(t)}))}E={...O},[i.CHANNELS.LOGIN,i.CHANNELS.LOGOUT,i.CHANNELS.REGISTER].map((e=>{O[e]&&(E[e]=function(t){return new Promise(((n,i)=>{s.emit(c+e,t,((e,t)=>{e?i(e):n(t)}))}))})}))}C.map((e=>{T[e]=function(...t){return new Promise(((n,r)=>{s.emit(i.CHANNELS.METHOD,{method:e,params:t},((e,t)=>{e?r(e):n(t)}))}))}})),T=Object.freeze(T),j&&(v.sql=function(e,t,n){return new Promise(((r,o)=>{s.emit(i.CHANNELS.SQL,{query:e,params:t,options:n},((e,t)=>{if(e)o(e);else if(n&&"noticeSubscription"===n.returnType&&t&&Object.keys(t).sort().join()===["socketChannel","socketUnsubChannel"].sort().join()&&!Object.values(t).find((e=>"string"!=typeof e))){const e=t,n=t=>(((e,t)=>{h=h||{config:t,listeners:[]},h.listeners.length||(s.removeAllListeners(t.socketChannel),s.on(t.socketChannel,(e=>{h&&h.listeners&&h.listeners.length?h.listeners.map((t=>{t(e)})):s.emit(t.socketUnsubChannel,{})}))),h.listeners.push(e)})(t,e),{...e,removeListener:()=>(e=>{h&&(h.listeners=h.listeners.filter((t=>t!==e)),!h.listeners.length&&h.config&&h.config.socketUnsubChannel&&s&&s.emit(h.config.socketUnsubChannel,{}))})(t)}),i={...e,addListener:n};r(i)}else if(n&&n.returnType&&"statement"===n.returnType||!t||Object.keys(t).sort().join()!==["socketChannel","socketUnsubChannel","notifChannel"].sort().join()||Object.values(t).find((e=>"string"!=typeof e)))r(t);else{const e=e=>(((e,t)=>{m=m||{},m[t.notifChannel]?m[t.notifChannel].listeners.push(e):(m[t.notifChannel]={config:t,listeners:[e]},s.removeAllListeners(t.socketChannel),s.on(t.socketChannel,(e=>{m[t.notifChannel]&&m[t.notifChannel].listeners&&m[t.notifChannel].listeners.length?m[t.notifChannel].listeners.map((t=>{t(e)})):s.emit(m[t.notifChannel].config.socketUnsubChannel,{})})))})(e,t),{...t,removeListener:()=>((e,t)=>{m&&m[t.notifChannel]&&(m[t.notifChannel].listeners=m[t.notifChannel].listeners.filter((t=>t!==e)),!m[t.notifChannel].listeners.length&&m[t.notifChannel].config&&m[t.notifChannel].config.socketUnsubChannel&&s&&(s.emit(m[t.notifChannel].config.socketUnsubChannel,{}),delete m[t.notifChannel]))})(e,t)}),n={...t,addListener:e};r(n)}}))}))});const P=e=>"[object Object]"===Object.prototype.toString.call(e),I=(e,t,n,i)=>{if(!P(e)||!P(t)||"function"!=typeof n||i&&"function"!=typeof i)throw"Expecting: ( basicFilter<object>, options<object>, onChange<function> , onError?<function>) but got something else"},A=["subscribe","subscribeOne"];Object.keys(v).forEach((e=>{Object.keys(v[e]).sort(((e,t)=>A.includes(e)-A.includes(t))).forEach((i=>{if(["find","findOne"].includes(i)&&(v[e].getJoinedTables=function(){return(w||[]).filter((t=>Array.isArray(t)&&t.includes(e))).flat().filter((t=>t!==e))}),"sync"===i){if(v[e]._syncInfo={...v[e][i]},n){v[e].getSync=(t,i={})=>n.create({name:e,filter:t,db:v,...i});const t=async(t={},i={},s)=>{const r=`${e}.${JSON.stringify(t)}.${JSON.stringify(i)}`;return u[r]||(u[r]=await n.create({...i,name:e,filter:t,db:v,onError:s})),u[r]};v[e].sync=async(e,n={handlesOnData:!0,select:"*"},i,s)=>{I(e,n,i,s);const r=await t(e,n,s);return await r.sync(i,n.handlesOnData)},v[e].syncOne=async(e,n={handlesOnData:!0},i,s)=>{I(e,n,i,s);const r=await t(e,n,s);return await r.syncOne(e,i,n.handlesOnData)}}v[e]._sync=function(n,r,o){return async function({tableName:e,command:n,param1:i,param2:r},o){const{onPullRequest:a,onSyncRequest:l,onUpdates:c}=o;function h(e,n){return Object.freeze({unsync:function(){!function(e,n){t.debug("_unsync",{channelName:e,triggers:n}),new Promise(((t,i)=>{f[e]&&(f[e].triggers=f[e].triggers.filter((e=>e.onPullRequest!==n.onPullRequest&&e.onSyncRequest!==n.onSyncRequest&&e.onUpdates!==n.onUpdates)),f[e].triggers.length||(s.emit(e+"unsync",{},((e,n)=>{e?i(e):t(n)})),s.removeListener(e,f[e].onCall),delete f[e]))}))}(e,o)},syncData:function(t,n,i){s.emit(e,{onSyncRequest:{...l({}),...{data:t}||{},...{deleted:n}||{}}},i?e=>{i(e)}:null)}})}const d=Object.keys(f).find((t=>{let s=f[t];return s.tableName===e&&s.command===n&&JSON.stringify(s.param1||{})===JSON.stringify(i||{})&&JSON.stringify(s.param2||{})===JSON.stringify(r||{})}));if(d)return f[d].triggers.push(o),h(d,f[d].syncInfo);{const t=await y({tableName:e,command:n,param1:i,param2:r},l),{channelName:a,synced_field:c,id_fields:d}=t;function u(t,n){t&&f[a]&&f[a].triggers.map((({onUpdates:i,onSyncRequest:s,onPullRequest:r})=>{t.data?Promise.resolve(i(t)).then((()=>{n&&n({ok:!0})})).catch((t=>{n?n({err:t}):console.error(e+" onUpdates error",t)})):t.onSyncRequest?Promise.resolve(s(t.onSyncRequest)).then((e=>n({onSyncRequest:e}))).catch((t=>{n?n({err:t}):console.error(e+" onSyncRequest error",t)})):t.onPullRequest?Promise.resolve(r(t.onPullRequest)).then((e=>{n({data:e})})).catch((t=>{n?n({err:t}):console.error(e+" onPullRequest error",t)})):console.log("unexpected response")}))}return f[a]={tableName:e,command:n,param1:i,param2:r,triggers:[o],syncInfo:t,onCall:u},s.on(a,u),h(a)}}({tableName:e,command:i,param1:n,param2:r},o)}}else if(A.includes(i)){v[e][i]=function(t,n,s,r){return I(t,n,s,r),S(v,{tableName:e,command:i,param1:t,param2:n},s,r)};const t="subscribeOne";i!==t&&A.includes(t)||(v[e][t]=function(t,n,s,r){return I(t,n,s,r),S(v,{tableName:e,command:i,param1:t,param2:n},(e=>{s(e[0])}),r)})}else v[e][i]=function(t,n,r){return new Promise(((o,a)=>{s.emit(c,{tableName:e,command:i,param1:t,param2:n,param3:r},((e,t)=>{e?a(e):o(t)}))}))}}))})),d&&Object.keys(d).length&&Object.keys(d).map((async e=>{try{let t=d[e];await b(t),s.on(e,t.onCall)}catch(e){console.error("There was an issue reconnecting old subscriptions",e)}})),f&&Object.keys(f).length&&Object.keys(f).filter((e=>f[e].triggers&&f[e].triggers.length)).map((async e=>{try{let t=f[e];await y(t,t.triggers[0].onSyncRequest),s.on(e,t.onCall)}catch(e){console.error("There was an issue reconnecting olf subscriptions",e)}})),w.flat().map((e=>{function t(t=!0,n,i,s){return{[t?"$leftJoin":"$innerJoin"]:e,filter:n,select:i,...s}}v.innerJoin=v.innerJoin||{},v.leftJoin=v.leftJoin||{},v.innerJoinOne=v.innerJoinOne||{},v.leftJoinOne=v.leftJoinOne||{},v.leftJoin[e]=(e,n,i={})=>t(!0,e,n,i),v.innerJoin[e]=(e,n,i={})=>t(!1,e,n,i),v.leftJoinOne[e]=(e,n,i={})=>t(!0,e,n,{...i,limit:1}),v.innerJoinOne[e]=(e,n,i={})=>t(!1,e,n,{...i,limit:1})})),(async()=>{try{await r(v,T,_,E)}catch(e){console.error("Prostgles: Error within onReady: \n",e),l(e)}e(v)})()}))}))}},792:function(e){this||window,e.exports=(()=>{"use strict";var e={444:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.EXISTS_KEYS=t.GeomFilter_Funcs=t.GeomFilterKeys=t.TextFilterFTSKeys=t.TextFilter_FullTextSearchFilterKeys=t.CompareInFilterKeys=t.CompareFilterKeys=void 0,t.CompareFilterKeys=["=","$eq","<>",">",">=","<=","$eq","$ne","$gt","$gte","$lte"],t.CompareInFilterKeys=["$in","$nin"],t.TextFilter_FullTextSearchFilterKeys=["to_tsquery","plainto_tsquery","phraseto_tsquery","websearch_to_tsquery"],t.TextFilterFTSKeys=["@@","@>","<@","$contains","$containedBy"],t.GeomFilterKeys=["~","~=","@","|&>","|>>",">>","=","<<|","<<","&>","&<|","&<","&&&","&&"];const n=["ST_MakeEnvelope","ST_MakePolygon"];t.GeomFilter_Funcs=n.concat(n.map((e=>e.toLowerCase()))),t.EXISTS_KEYS=["$exists","$notExists","$existsJoined","$notExistsJoined"]},590:function(e,t,n){var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n),Object.defineProperty(e,i,{enumerable:!0,get:function(){return t[n]}})}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),s=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||i(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),t.get=t.WAL=t.unpatchText=t.stableStringify=t.isEmpty=t.getTextPatch=t.asName=t.CHANNELS=t.TS_PG_Types=t._PG_postgis=t._PG_date=t._PG_bool=t._PG_json=t._PG_numbers=t._PG_strings=void 0,t._PG_strings=["bpchar","char","varchar","text","citext","uuid","bytea","inet","time","timetz","interval","name"],t._PG_numbers=["int2","int4","int8","float4","float8","numeric","money","oid"],t._PG_json=["json","jsonb"],t._PG_bool=["bool"],t._PG_date=["date","timestamp","timestamptz"],t._PG_postgis=["geometry","geography"],t.TS_PG_Types={string:t._PG_strings,number:t._PG_numbers,boolean:t._PG_bool,Object:t._PG_json,Date:t._PG_date,"Array<number>":t._PG_numbers.map((e=>`_${e}`)),"Array<boolean>":t._PG_bool.map((e=>`_${e}`)),"Array<string>":t._PG_strings.map((e=>`_${e}`)),"Array<Object>":t._PG_json.map((e=>`_${e}`)),"Array<Date>":t._PG_date.map((e=>`_${e}`)),any:[]};const r="_psqlWS_.";t.CHANNELS={SCHEMA_CHANGED:r+"schema-changed",SCHEMA:r+"schema",DEFAULT:r,SQL:"_psqlWS_.sql",METHOD:"_psqlWS_.method",NOTICE_EV:"_psqlWS_.notice",LISTEN_EV:"_psqlWS_.listen",REGISTER:"_psqlWS_.register",LOGIN:"_psqlWS_.login",LOGOUT:"_psqlWS_.logout",AUTHGUARD:"_psqlWS_.authguard",_preffix:r};var o=n(128);Object.defineProperty(t,"asName",{enumerable:!0,get:function(){return o.asName}}),Object.defineProperty(t,"getTextPatch",{enumerable:!0,get:function(){return o.getTextPatch}}),Object.defineProperty(t,"isEmpty",{enumerable:!0,get:function(){return o.isEmpty}}),Object.defineProperty(t,"stableStringify",{enumerable:!0,get:function(){return o.stableStringify}}),Object.defineProperty(t,"unpatchText",{enumerable:!0,get:function(){return o.unpatchText}}),Object.defineProperty(t,"WAL",{enumerable:!0,get:function(){return o.WAL}}),Object.defineProperty(t,"get",{enumerable:!0,get:function(){return o.get}}),s(n(444),t)},899:(e,t)=>{function n(e,t){var n=e[0],i=e[1],l=e[2],c=e[3];n=s(n,i,l,c,t[0],7,-680876936),c=s(c,n,i,l,t[1],12,-389564586),l=s(l,c,n,i,t[2],17,606105819),i=s(i,l,c,n,t[3],22,-1044525330),n=s(n,i,l,c,t[4],7,-176418897),c=s(c,n,i,l,t[5],12,1200080426),l=s(l,c,n,i,t[6],17,-1473231341),i=s(i,l,c,n,t[7],22,-45705983),n=s(n,i,l,c,t[8],7,1770035416),c=s(c,n,i,l,t[9],12,-1958414417),l=s(l,c,n,i,t[10],17,-42063),i=s(i,l,c,n,t[11],22,-1990404162),n=s(n,i,l,c,t[12],7,1804603682),c=s(c,n,i,l,t[13],12,-40341101),l=s(l,c,n,i,t[14],17,-1502002290),n=r(n,i=s(i,l,c,n,t[15],22,1236535329),l,c,t[1],5,-165796510),c=r(c,n,i,l,t[6],9,-1069501632),l=r(l,c,n,i,t[11],14,643717713),i=r(i,l,c,n,t[0],20,-373897302),n=r(n,i,l,c,t[5],5,-701558691),c=r(c,n,i,l,t[10],9,38016083),l=r(l,c,n,i,t[15],14,-660478335),i=r(i,l,c,n,t[4],20,-405537848),n=r(n,i,l,c,t[9],5,568446438),c=r(c,n,i,l,t[14],9,-1019803690),l=r(l,c,n,i,t[3],14,-187363961),i=r(i,l,c,n,t[8],20,1163531501),n=r(n,i,l,c,t[13],5,-1444681467),c=r(c,n,i,l,t[2],9,-51403784),l=r(l,c,n,i,t[7],14,1735328473),n=o(n,i=r(i,l,c,n,t[12],20,-1926607734),l,c,t[5],4,-378558),c=o(c,n,i,l,t[8],11,-2022574463),l=o(l,c,n,i,t[11],16,1839030562),i=o(i,l,c,n,t[14],23,-35309556),n=o(n,i,l,c,t[1],4,-1530992060),c=o(c,n,i,l,t[4],11,1272893353),l=o(l,c,n,i,t[7],16,-155497632),i=o(i,l,c,n,t[10],23,-1094730640),n=o(n,i,l,c,t[13],4,681279174),c=o(c,n,i,l,t[0],11,-358537222),l=o(l,c,n,i,t[3],16,-722521979),i=o(i,l,c,n,t[6],23,76029189),n=o(n,i,l,c,t[9],4,-640364487),c=o(c,n,i,l,t[12],11,-421815835),l=o(l,c,n,i,t[15],16,530742520),n=a(n,i=o(i,l,c,n,t[2],23,-995338651),l,c,t[0],6,-198630844),c=a(c,n,i,l,t[7],10,1126891415),l=a(l,c,n,i,t[14],15,-1416354905),i=a(i,l,c,n,t[5],21,-57434055),n=a(n,i,l,c,t[12],6,1700485571),c=a(c,n,i,l,t[3],10,-1894986606),l=a(l,c,n,i,t[10],15,-1051523),i=a(i,l,c,n,t[1],21,-2054922799),n=a(n,i,l,c,t[8],6,1873313359),c=a(c,n,i,l,t[15],10,-30611744),l=a(l,c,n,i,t[6],15,-1560198380),i=a(i,l,c,n,t[13],21,1309151649),n=a(n,i,l,c,t[4],6,-145523070),c=a(c,n,i,l,t[11],10,-1120210379),l=a(l,c,n,i,t[2],15,718787259),i=a(i,l,c,n,t[9],21,-343485551),e[0]=u(n,e[0]),e[1]=u(i,e[1]),e[2]=u(l,e[2]),e[3]=u(c,e[3])}function i(e,t,n,i,s,r){return t=u(u(t,e),u(i,r)),u(t<<s|t>>>32-s,n)}function s(e,t,n,s,r,o,a){return i(t&n|~t&s,e,t,r,o,a)}function r(e,t,n,s,r,o,a){return i(t&s|n&~s,e,t,r,o,a)}function o(e,t,n,s,r,o,a){return i(t^n^s,e,t,r,o,a)}function a(e,t,n,s,r,o,a){return i(n^(t|~s),e,t,r,o,a)}function l(e){var t,n=[];for(t=0;t<64;t+=4)n[t>>2]=e.charCodeAt(t)+(e.charCodeAt(t+1)<<8)+(e.charCodeAt(t+2)<<16)+(e.charCodeAt(t+3)<<24);return n}Object.defineProperty(t,"__esModule",{value:!0}),t.md5=t.md5cycle=void 0,t.md5cycle=n;var c="0123456789abcdef".split("");function h(e){for(var t="",n=0;n<4;n++)t+=c[e>>8*n+4&15]+c[e>>8*n&15];return t}function d(e){return function(e){for(var t=0;t<e.length;t++)e[t]=h(e[t]);return e.join("")}(function(e){var t,i=e.length,s=[1732584193,-271733879,-1732584194,271733878];for(t=64;t<=e.length;t+=64)n(s,l(e.substring(t-64,t)));e=e.substring(t-64);var r=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(t=0;t<e.length;t++)r[t>>2]|=e.charCodeAt(t)<<(t%4<<3);if(r[t>>2]|=128<<(t%4<<3),t>55)for(n(s,r),t=0;t<16;t++)r[t]=0;return r[14]=8*i,n(s,r),s}(e))}function u(e,t){return e+t&4294967295}if(t.md5=d,"5d41402abc4b2a76b9719d911017c592"!=d("hello")){function u(e,t){var n=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(n>>16)<<16|65535&n}}},128:function(e,t,n){var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(s,r){function o(e){try{l(i.next(e))}catch(e){r(e)}}function a(e){try{l(i.throw(e))}catch(e){r(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,a)}l((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.get=t.isEmpty=t.WAL=t.unpatchText=t.getTextPatch=t.stableStringify=t.asName=void 0;const s=n(899);function r(e){for(var t in e)return!1;return!0}t.asName=function(e){if(null==e||!e.toString||!e.toString())throw"Expecting a non empty string";return`"${e.toString().replace(/"/g,'""')}"`},t.stableStringify=function(e,t){t||(t={}),"function"==typeof t&&(t={cmp:t});var n,i="boolean"==typeof t.cycles&&t.cycles,s=t.cmp&&(n=t.cmp,function(e){return function(t,i){var s={key:t,value:e[t]},r={key:i,value:e[i]};return n(s,r)}}),r=[];return function e(t){if(t&&t.toJSON&&"function"==typeof t.toJSON&&(t=t.toJSON()),void 0!==t){if("number"==typeof t)return isFinite(t)?""+t:"null";if("object"!=typeof t)return JSON.stringify(t);var n,o;if(Array.isArray(t)){for(o="[",n=0;n<t.length;n++)n&&(o+=","),o+=e(t[n])||"null";return o+"]"}if(null===t)return"null";if(-1!==r.indexOf(t)){if(i)return JSON.stringify("__cycle__");throw new TypeError("Converting circular structure to JSON")}var a=r.push(t)-1,l=Object.keys(t).sort(s&&s(t));for(o="",n=0;n<l.length;n++){var c=l[n],h=e(t[c]);h&&(o&&(o+=","),o+=JSON.stringify(c)+":"+h)}return r.splice(a,1),"{"+o+"}"}}(e)},t.getTextPatch=function(e,t){if(!(e&&t&&e.trim().length&&t.trim().length))return t;if(e===t)return{from:0,to:0,text:"",md5:s.md5(t)};function n(n=1){let i=n<1?-1:0,s=!1;for(;!s&&Math.abs(i)<=t.length;){const r=n<1?[i]:[0,i];e.slice(...r)!==t.slice(...r)?s=!0:i+=1*Math.sign(n)}return i}let i=n()-1,r=e.length+n(-1)+1,o=t.length+n(-1)+1;return{from:i,to:r,text:t.slice(i,o),md5:s.md5(t)}},t.unpatchText=function(e,t){if(!t||"string"==typeof t)return t;const{from:n,to:i,text:r,md5:o}=t;if(null===r||null===e)return r;let a=e.slice(0,n)+r+e.slice(i);if(o&&s.md5(a)!==o)throw"Patch text error: Could not match md5 hash: (original/result) \n"+e+"\n"+a;return a},t.WAL=class{constructor(e){if(this.changed={},this.sending={},this.sentHistory={},this.callbacks=[],this.sort=(e,t)=>{const{orderBy:n}=this.options;return n&&e&&t&&n.map((n=>{if(!(n.fieldName in e)||!(n.fieldName in t))throw"Replication error: \n some orderBy fields missing from data";let i=n.asc?e[n.fieldName]:t[n.fieldName],s=n.asc?t[n.fieldName]:e[n.fieldName],r=+i-+s,o=i<s?-1:i==s?0:1;return"number"===n.tsDataType&&Number.isFinite(r)?r:o})).find((e=>e))||0},this.isInHistory=e=>{if(!e)throw"Provide item";const t=e[this.options.synced_field];if(!Number.isFinite(+t))throw"Provided item Synced field value is missing/invalid ";const n=this.sentHistory[this.getIdStr(e)],i=null==n?void 0:n[this.options.synced_field];if(n){if(!Number.isFinite(+i))throw"Provided historic item Synced field value is missing/invalid";if(+i==+t)return!0}return!1},this.addData=e=>{r(this.changed)&&this.options.onSendStart&&this.options.onSendStart(),e.map((e=>{const{initial:t,current:n}=Object.assign({},e);if(!n)throw"Expecting { current: object, initial?: object }";const i=this.getIdStr(n);this.changed=this.changed||{},this.changed[i]=this.changed[i]||{initial:t,current:n},this.changed[i].current=Object.assign(Object.assign({},this.changed[i].current),n)})),this.sendItems()},this.isOnSending=!1,this.isSendingTimeout=void 0,this.willDeleteHistory=void 0,this.sendItems=()=>i(this,void 0,void 0,(function*(){const{DEBUG_MODE:e,onSend:t,onSendEnd:n,batch_size:i,throttle:s,historyAgeSeconds:o=2}=this.options;if(this.isSendingTimeout||this.sending&&!r(this.sending))return;if(!this.changed||r(this.changed))return;let a,l=[],c=[],h={};Object.keys(this.changed).sort(((e,t)=>this.sort(this.changed[e].current,this.changed[t].current))).slice(0,i).map((e=>{let t=Object.assign({},this.changed[e]);this.sending[e]=Object.assign({},t),c.push(Object.assign({},t)),h[e]=Object.assign({},t.current),delete this.changed[e]})),l=c.map((e=>e.current)),e&&console.log(this.options.id," SENDING lr->",l[l.length-1]),this.isSendingTimeout||(this.isSendingTimeout=setTimeout((()=>{this.isSendingTimeout=void 0,r(this.changed)||this.sendItems()}),s)),this.isOnSending=!0;try{yield t(l,c),o&&(this.sentHistory=Object.assign(Object.assign({},this.sentHistory),h),this.willDeleteHistory||(this.willDeleteHistory=setTimeout((()=>{this.willDeleteHistory=void 0,this.sentHistory={}}),1e3*o)))}catch(e){a=e,console.error("WAL onSend failed:",e,l,c)}if(this.isOnSending=!1,this.callbacks.length){const e=Object.keys(this.sending);this.callbacks.forEach(((t,n)=>{t.idStrs=t.idStrs.filter((t=>e.includes(t))),t.idStrs.length||t.cb(a)})),this.callbacks=this.callbacks.filter((e=>e.idStrs.length))}this.sending={},e&&console.log(this.options.id," SENT lr->",l[l.length-1]),r(this.changed)?n&&n(l,c,a):this.sendItems()})),this.options=Object.assign({},e),!this.options.orderBy){const{synced_field:t,id_fields:n}=e;this.options.orderBy=[t,...n.sort()].map((e=>({fieldName:e,tsDataType:e===t?"number":"string",asc:!0})))}}isSending(){const e=this.isOnSending||!(r(this.sending)&&r(this.changed));return this.options.DEBUG_MODE&&console.log(this.options.id," CHECKING isSending ->",e),e}getIdStr(e){return this.options.id_fields.sort().map((t=>`${e[t]||""}`)).join(".")}getIdObj(e){let t={};return this.options.id_fields.sort().map((n=>{t[n]=e[n]})),t}getDeltaObj(e){let t={};return Object.keys(e).map((n=>{this.options.id_fields.includes(n)||(t[n]=e[n])})),t}},t.isEmpty=r,t.get=function(e,t){let n=t,i=e;return e?("string"==typeof n&&(n=n.split(".")),n.reduce(((e,t)=>e&&e[t]?e[t]:void 0),i)):e}}},t={};return function n(i){if(t[i])return t[i].exports;var s=t[i]={exports:{}};return e[i].call(s.exports,s,s.exports,n),s.exports}(590)})()}},t={};function n(i){var s=t[i];if(void 0!==s)return s.exports;var r=t[i]={exports:{}};return e[i].call(r.exports,r,r.exports,n),r.exports}var i={};return(()=>{"use strict";var e=i;Object.defineProperty(e,"__esModule",{value:!0}),e.prostgles=void 0;const t=n(274),s=n(133);e.prostgles=function(e){return t.prostgles(e,s.SyncedTable)}})(),i})()}));
1
+ !function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var n=t();for(var i in n)("object"==typeof exports?exports:e)[i]=n[i]}}(this||window,(()=>(()=>{var e={133:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getKeys=t.isDefined=t.mergeDeep=t.isObject=t.SyncedTable=t.debug=void 0;const i=n(792),s="DEBUG_SYNCEDTABLE",r="undefined"!=typeof window;t.debug=function(...e){r&&window[s]&&window[s](...e)};const o={array:"array",localStorage:"localStorage",object:"object"};class a{constructor({name:e,filter:n,onChange:s,onReady:a,db:l,skipFirstTrigger:d=!1,select:u="*",storageType:f="object",patchText:m=!1,patchJSON:g=!1,onError:p}){if(this.throttle=100,this.batch_size=50,this.skipFirstTrigger=!1,this.columns=[],this._multiSubscriptions=[],this._singleSubscriptions=[],this.items=[],this.itemsObj={},this.isSynced=!1,this.updatePatches=async e=>{let t=e.map((e=>e.current)),n=[],s=[];if(this.columns&&this.columns.length&&this.db[this.name].updateBatch&&(this.patchText||this.patchJSON)){const r=this.columns.filter((e=>"text"===e.data_type));if(this.patchText&&r.length){t=[];const o=[this.synced_field,...this.id_fields];await Promise.all(e.slice(0).map((async(e,a)=>{const{current:l,initial:c}={...e};let h;c&&(r.map((e=>{!o.includes(e.name)&&e.name in l&&(null!=h||(h={...l}),h[e.name]=(0,i.getTextPatch)(c[e.name],l[e.name]))})),h&&this.wal&&(s.push(h),n.push([this.wal.getIdObj(h),this.wal.getDeltaObj(h)]))),h||t.push(l)})))}}if(n.length)try{await this.db[this.name].updateBatch(n)}catch(e){console.log("failed to patch update",e),t=t.concat(s)}return t.filter((e=>e))},this.notifySubscribers=(e=[])=>{if(!this.isSynced)return;let t=[],n=[],i=[];e.map((({idObj:e,newItem:s,delta:r})=>{this.singleSubscriptions.filter((t=>this.matchesIdObj(t.idObj,e))).map((async e=>{try{await e.notify(s,r)}catch(e){console.error("SyncedTable failed to notify: ",e)}})),this.matchesFilter(s)&&(t.push(s),n.push(r),i.push(e))}));let s=[],r=[];if(this.getItems().map((e=>{s.push({...e});const i=t.findIndex((t=>this.matchesIdObj(e,t)));r.push(n[i])})),this.onChange)try{this.onChange(s,r)}catch(e){console.error("SyncedTable failed to notify onChange: ",e)}this.multiSubscriptions.map((async e=>{try{await e.notify(s,r)}catch(e){console.error("SyncedTable failed to notify: ",e)}}))},this.unsubscribe=e=>(this.singleSubscriptions=this.singleSubscriptions.filter((t=>t._onChange!==e)),this.multiSubscriptions=this.multiSubscriptions.filter((t=>t._onChange!==e)),(0,t.debug)("unsubscribe",this),"ok"),this.unsync=()=>{this.dbSync&&this.dbSync.unsync&&this.dbSync.unsync()},this.destroy=()=>{this.unsync(),this.multiSubscriptions=[],this.singleSubscriptions=[],this.itemsObj={},this.items=[],this.onChange=void 0},this.delete=async(e,t=!1)=>{const n=this.getIdObj(e);return this.setItem(n,void 0,!0,!0),t||await this.db[this.name].delete(n),this.notifySubscribers(),!0},this.checkItemCols=e=>{if(this.columns&&this.columns.length){const t=Object.keys({...e}).filter((e=>!this.columns.find((t=>t.name===e))));if(t.length)throw"Unexpected columns in sync item update: "+t.join(", ")}},this.upsert=async(e,t=!1)=>{var n;if(!(e&&e.length||t))throw"No data provided for upsert";let s,r=[],o=[];await Promise.all(e.map((async(e,n)=>{var a;let l={...e.idObj},h={...e.delta};Object.keys(h).map((e=>{void 0===h[e]&&(h[e]=null)})),t||this.checkItemCols({...e.delta,...e.idObj});let d=this.getItem(l),u=d.index,f=d.data;!t&&!(0,i.isEmpty)(h)||(0,i.isEmpty)(f)||(h=this.getDelta(f||{},h)),t||(h[this.synced_field]=Date.now());let m={...f,...h,...l};if(f&&!t&&(null===(a=e.opts)||void 0===a?void 0:a.deepMerge)&&(m=c({...f,...l},{...h})),f&&f[this.synced_field]<m[this.synced_field]?s="updated":f||(s="inserted"),this.setItem(m,u),!s)throw"changeInfo status missing";let g={idObj:l,delta:h,oldItem:f,newItem:m,status:s,from_server:t};return t||o.push({initial:f,current:{...m}}),g.delta&&!(0,i.isEmpty)(g.delta)&&r.push(g),!0}))).catch((e=>{console.error("SyncedTable failed upsert: ",e)})),this.notifySubscribers(r),!t&&o.length&&(null===(n=this.wal)||void 0===n||n.addData(o))},this.setItems=e=>{if(this.storageType===o.localStorage){if(!r)throw"Cannot access window object. Choose another storage method (array OR object)";window.localStorage.setItem(this.name,JSON.stringify(e))}else this.storageType===o.array?this.items=e:this.itemsObj=e.reduce(((e,t)=>({...e,[this.getIdStr(t)]:{...t}})),{})},this.getItems=()=>{let e=[];if(this.storageType===o.localStorage){if(!r)throw"Cannot access window object. Choose another storage method (array OR object)";let t=window.localStorage.getItem(this.name);if(t)try{e=JSON.parse(t)}catch(e){console.error(e)}}else e=this.storageType===o.array?this.items.map((e=>({...e}))):Object.values({...this.itemsObj});if(!this.id_fields||!this.synced_field)throw"id_fields AND/OR synced_field missing";{const t=[this.synced_field,...this.id_fields.sort()];e=e.filter((e=>!this.filter||!h(this.filter).find((t=>e[t]!==this.filter[t])))).sort(((e,n)=>t.map((t=>e[t]<n[t]?-1:e[t]>n[t]?1:0)).find((e=>e))))}return e.map((e=>({...e})))},this.getBatch=({from_synced:e,to_synced:t,offset:n,limit:i}={offset:0,limit:void 0})=>{let s=this.getItems().map((e=>({...e}))).filter((n=>(!Number.isFinite(e)||+n[this.synced_field]>=+e)&&(!Number.isFinite(t)||+n[this.synced_field]<=+t)));return(n||i)&&(s=s.splice(null!=n?n:0,i||s.length)),s},this.name=e,this.filter=n,this.select=u,this.onChange=s,!o[f])throw"Invalid storage type. Expecting one of: "+Object.keys(o).join(", ");if(r||f!==o.localStorage||(console.warn("Could not set storageType to localStorage: window object missing\nStorage changed to object"),f="object"),this.storageType=f,this.patchText=m,this.patchJSON=g,!l)throw"db missing";this.db=l;const{id_fields:y,synced_field:b,throttle:S=100,batch_size:_=50}=l[this.name]._syncInfo;if(!y||!b)throw"id_fields/synced_field missing";this.id_fields=y,this.synced_field=b,this.batch_size=_,this.throttle=S,this.skipFirstTrigger=d,this.multiSubscriptions=[],this.singleSubscriptions=[],this.onError=p||function(e){console.error("Sync internal error: ",e)},l[this.name]._sync(n,{select:u},{onSyncRequest:e=>{let t={c_lr:void 0,c_fr:void 0,c_count:0},n=this.getBatch(e);return n.length&&(t={c_fr:this.getRowSyncObj(n[0]),c_lr:this.getRowSyncObj(n[n.length-1]),c_count:n.length}),t},onPullRequest:async e=>this.getBatch(e),onUpdates:async e=>{var t;if("err"in e&&e.err)null===(t=this.onError)||void 0===t||t.call(this,e.err);else if("isSynced"in e&&e.isSynced&&!this.isSynced){this.isSynced=e.isSynced;let t=this.getItems().map((e=>({...e})));this.setItems([]);const n=t.map((e=>({idObj:this.getIdObj(e),delta:{...e}})));await this.upsert(n,!0)}else if("data"in e){let t=e.data.map((e=>({idObj:this.getIdObj(e),delta:e})));await this.upsert(t,!0)}else console.error("Unexpected onUpdates");return!0}}).then((e=>{function t(){return"Data may be lost. Are you sure?"}this.dbSync=e,this.wal=new i.WAL({id_fields:y,synced_field:b,throttle:S,batch_size:_,onSendStart:()=>{r&&(window.onbeforeunload=t)},onSend:async(e,t)=>(await this.updatePatches(t)).length?this.dbSync.syncData(e):[],onSendEnd:()=>{r&&(window.onbeforeunload=null)}}),a()})),l[this.name].getColumns&&l[this.name].getColumns().then((e=>{this.columns=e})),this.onChange&&!this.skipFirstTrigger&&setTimeout(this.onChange,0),(0,t.debug)(this)}set multiSubscriptions(e){(0,t.debug)(e,this._multiSubscriptions),this._multiSubscriptions=e.slice(0)}get multiSubscriptions(){return this._multiSubscriptions}set singleSubscriptions(e){(0,t.debug)(e,this._singleSubscriptions),this._singleSubscriptions=e.slice(0)}get singleSubscriptions(){return this._singleSubscriptions}static create(e){return new Promise(((t,n)=>{try{const n=new a({...e,onReady:()=>{setTimeout((()=>{t(n)}),0)}})}catch(e){n(e)}}))}sync(e,t=!0){const n={$unsync:()=>this.unsubscribe(e),$upsert:e=>{if(e){const t=e=>({idObj:this.getIdObj(e),delta:e});Array.isArray(e)?this.upsert(e.map((e=>t(e)))):this.upsert([t(e)])}}},i={_onChange:e,handlesOnData:t,handles:n,notify:(n,i)=>{let s=[...n],r=[...i];return t&&(s=s.map(((n,i)=>{const s=(n,i)=>({...n,...this.makeSingleSyncHandles(i,e),$get:()=>s(this.getItem(i).data,i),$find:e=>s(this.getItem(e).data,e),$update:(e,t)=>this.upsert([{idObj:i,delta:e,opts:t}]).then((e=>!0)),$delete:async()=>this.delete(i),$cloneMultiSync:e=>this.sync(e,t)}),r=this.wal.getIdObj(n);return s(n,r)}))),e(s,r)}};return this.multiSubscriptions.push(i),this.skipFirstTrigger||setTimeout((()=>{let e=this.getItems();i.notify(e,e)}),0),Object.freeze({...n})}makeSingleSyncHandles(e,n){if(!e||!n)throw"syncOne(idObj, onChange) -> MISSING idObj or onChange";const i={$get:()=>this.getItem(e).data,$find:e=>this.getItem(e).data,$unsync:()=>this.unsubscribe(n),$delete:()=>this.delete(e),$update:(n,i)=>{this.singleSubscriptions.length||this.multiSubscriptions.length||(console.warn("No sync listeners"),(0,t.debug)("nosync",this._singleSubscriptions,this._multiSubscriptions)),this.upsert([{idObj:e,delta:n,opts:i}])},$cloneSync:t=>this.syncOne(e,t),$cloneMultiSync:e=>this.sync(e,!0)};return i}syncOne(e,t,n=!0){const i=this.makeSingleSyncHandles(e,t),s={_onChange:t,idObj:e,handlesOnData:n,handles:i,notify:(e,s)=>{let r={...e};return n&&(r.$get=i.$get,r.$find=i.$find,r.$update=i.$update,r.$delete=i.$delete,r.$unsync=i.$unsync,r.$cloneSync=i.$cloneSync),t(r,s)}};return this.singleSubscriptions.push(s),setTimeout((()=>{let e=i.$get();e&&s.notify(e,e)}),0),Object.freeze({...i})}getIdStr(e){return this.id_fields.sort().map((t=>`${e[t]||""}`)).join(".")}getIdObj(e){let t={};return this.id_fields.sort().map((n=>{t[n]=e[n]})),t}getRowSyncObj(e){let t={};return[this.synced_field,...this.id_fields].sort().map((n=>{t[n]=e[n]})),t}matchesFilter(e){return Boolean(e&&(!this.filter||(0,i.isEmpty)(this.filter)||this.filter&&!Object.keys(this.filter).find((t=>this.filter[t]!==e[t]))))}matchesIdObj(e,t){return Boolean(e&&t&&!this.id_fields.sort().find((n=>e[n]!==t[n])))}getDelta(e,t){return(0,i.isEmpty)(e)?{...t}:Object.keys({...e,...t}).filter((e=>!this.id_fields.includes(e))).reduce(((n,i)=>{let s={};if(i in t&&t[i]!==e[i]){let n={[i]:t[i]};t[i]&&e[i]&&"object"==typeof e[i]?JSON.stringify(t[i])!==JSON.stringify(e[i])&&(s=n):s=n}return{...n,...s}}),{})}deleteAll(){this.getItems().map((e=>this.delete(e)))}getItem(e){let t;return this.storageType===o.localStorage?t=this.getItems().find((t=>this.matchesIdObj(t,e))):this.storageType===o.array?t=this.items.find((t=>this.matchesIdObj(t,e))):(this.itemsObj=this.itemsObj||{},t={...this.itemsObj}[this.getIdStr(e)]),{data:t?{...t}:t,index:-1}}setItem(e,t,n=!1,i=!1){if(this.storageType===o.localStorage){let s=this.getItems();i?s=s.filter((t=>!this.matchesIdObj(t,e))):void 0!==t&&s[t]?s[t]=n?{...e}:{...s[t],...e}:s.push(e),r&&window.localStorage.setItem(this.name,JSON.stringify(s))}else if(this.storageType===o.array)i?this.items=this.items.filter((t=>!this.matchesIdObj(t,e))):void 0===t||this.items[t]?void 0!==t&&(this.items[t]=n?{...e}:{...this.items[t],...e}):this.items.push(e);else if(this.itemsObj=this.itemsObj||{},i)delete this.itemsObj[this.getIdStr(e)];else{let t=this.itemsObj[this.getIdStr(e)]||{};this.itemsObj[this.getIdStr(e)]=n?{...e}:{...t,...e}}}}function l(e){return e&&"object"==typeof e&&!Array.isArray(e)}function c(e,...t){if(!t.length)return e;const n=t.shift();if(l(e)&&l(n))for(const t in n)l(n[t])?(e[t]||Object.assign(e,{[t]:{}}),c(e[t],n[t])):Object.assign(e,{[t]:n[t]});return c(e,...t)}function h(e){return Object.keys(e)}t.SyncedTable=a,t.isObject=l,t.mergeDeep=c,t.isDefined=e=>null!=e,t.getKeys=h},274:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.prostgles=t.debug=void 0;const i=n(792),s="DEBUG_SYNCEDTABLE",r="undefined"!=typeof window;t.debug=function(...e){r&&window[s]&&window[s](...e)},t.prostgles=function(e,n){const{socket:s,onReady:r,onDisconnect:o,onReconnect:a,onSchemaChange:l=!0}=e;if((0,t.debug)("prostgles",{initOpts:e}),l){let e;"function"==typeof l&&(e=l),s.removeAllListeners(i.CHANNELS.SCHEMA_CHANGED),e&&s.on(i.CHANNELS.SCHEMA_CHANGED,e)}const c=i.CHANNELS._preffix;let h,d={},u={},f={},m={},g=!1;function p(e,n){return(0,t.debug)("_unsubscribe",{channelName:e,handler:n}),new Promise(((t,i)=>{d[e]?(d[e].handlers=d[e].handlers.filter((e=>e!==n)),d[e].handlers.length||(s.emit(e+"unsubscribe",{},((e,t)=>{e&&console.error(e)})),s.removeListener(e,d[e].onCall),delete d[e]),t(!0)):t(!0)}))}function y({tableName:e,command:t,param1:n,param2:i},r){return new Promise(((o,a)=>{s.emit(c,{tableName:e,command:t,param1:n,param2:i},((e,t)=>{if(e)console.error(e),a(e);else if(t){const{id_fields:e,synced_field:n,channelName:i}=t;s.emit(i,{onSyncRequest:r({})},(e=>{console.log(e)})),o({id_fields:e,synced_field:n,channelName:i})}}))}))}function b({tableName:e,command:t,param1:n,param2:i}){return new Promise(((r,o)=>{s.emit(c,{tableName:e,command:t,param1:n,param2:i},((e,t)=>{e?(console.error(e),o(e)):t&&r(t.channelName)}))}))}async function S(e,{tableName:t,command:n,param1:i,param2:r},o,a){function l(n){let s={unsubscribe:function(){return p(n,o)},filter:{...i}};return e[t].update&&(s={...s,update:function(n,s){return e[t].update(i,n,s)}}),e[t].delete&&(s={...s,delete:function(n){return e[t].delete(i,n)}}),Object.freeze(s)}const c=Object.keys(d).find((e=>{let s=d[e];return s.tableName===t&&s.command===n&&JSON.stringify(s.param1||{})===JSON.stringify(i||{})&&JSON.stringify(s.param2||{})===JSON.stringify(r||{})}));if(c)return d[c].handlers.push(o),setTimeout((()=>{o&&(null==d?void 0:d[c].lastData)&&o(null==d?void 0:d[c].lastData)}),10),l(c);{const e=await b({tableName:t,command:n,param1:i,param2:r});let c=function(t,n){d[e]?t.data?(d[e].lastData=t.data,d[e].handlers.map((e=>{e(t.data)}))):t.err?d[e].errorHandlers.map((e=>{e(t.err)})):console.error("INTERNAL ERROR: Unexpected data format from subscription: ",t):console.warn("Orphaned subscription: ",e)},h=a||function(t){console.error(`Uncaught error within running subscription \n ${e}`,t)};return s.on(e,c),d[e]={lastData:void 0,tableName:t,command:n,param1:i,param2:r,onCall:c,handlers:[o],errorHandlers:[h],destroy:()=>{d[e]&&(Object.values(d[e]).map((t=>{t&&t.handlers&&t.handlers.map((t=>p(e,t)))})),delete d[e])}},l(e)}}return new Promise(((e,l)=>{o&&s.on("disconnect",o),s.on(i.CHANNELS.SCHEMA,(({schema:o,methods:p,fullSchema:_,auth:O,rawSQL:j,joinTables:w=[],err:N})=>{if(N)throw l(N),N;(0,t.debug)("destroySyncs",{subscriptions:d,syncedTables:u}),Object.values(d).map((e=>e.destroy())),d={},f={},Object.values(u).map((e=>{e&&e.destroy&&e.destroy()})),u={},g&&a&&a(s),g=!0;let v=JSON.parse(JSON.stringify(o)),C=JSON.parse(JSON.stringify(p)),T={},E={};if(O){if(O.pathGuard){const e=e=>{var t,n;(null==e?void 0:e.shouldReload)&&"undefined"!=typeof window&&(null===(n=null===(t=null===window||void 0===window?void 0:window.location)||void 0===t?void 0:t.reload)||void 0===n||n.call(t))};s.emit(i.CHANNELS.AUTHGUARD,JSON.stringify(window.location),((t,n)=>{e(n)})),s.removeAllListeners(i.CHANNELS.AUTHGUARD),s.on(i.CHANNELS.AUTHGUARD,(t=>{e(t)}))}E={...O},[i.CHANNELS.LOGIN,i.CHANNELS.LOGOUT,i.CHANNELS.REGISTER].map((e=>{O[e]&&(E[e]=function(t){return new Promise(((n,i)=>{s.emit(c+e,t,((e,t)=>{e?i(e):n(t)}))}))})}))}C.map((e=>{T[e]=function(...t){return new Promise(((n,r)=>{s.emit(i.CHANNELS.METHOD,{method:e,params:t},((e,t)=>{e?r(e):n(t)}))}))}})),T=Object.freeze(T),j&&(v.sql=function(e,t,n){return new Promise(((r,o)=>{s.emit(i.CHANNELS.SQL,{query:e,params:t,options:n},((e,t)=>{if(e)o(e);else if(n&&"noticeSubscription"===n.returnType&&t&&Object.keys(t).sort().join()===["socketChannel","socketUnsubChannel"].sort().join()&&!Object.values(t).find((e=>"string"!=typeof e))){const e=t,n=t=>(((e,t)=>{h=h||{config:t,listeners:[]},h.listeners.length||(s.removeAllListeners(t.socketChannel),s.on(t.socketChannel,(e=>{h&&h.listeners&&h.listeners.length?h.listeners.map((t=>{t(e)})):s.emit(t.socketUnsubChannel,{})}))),h.listeners.push(e)})(t,e),{...e,removeListener:()=>(e=>{h&&(h.listeners=h.listeners.filter((t=>t!==e)),!h.listeners.length&&h.config&&h.config.socketUnsubChannel&&s&&s.emit(h.config.socketUnsubChannel,{}))})(t)}),i={...e,addListener:n};r(i)}else if(n&&n.returnType&&"statement"===n.returnType||!t||Object.keys(t).sort().join()!==["socketChannel","socketUnsubChannel","notifChannel"].sort().join()||Object.values(t).find((e=>"string"!=typeof e)))r(t);else{const e=e=>(((e,t)=>{m=m||{},m[t.notifChannel]?m[t.notifChannel].listeners.push(e):(m[t.notifChannel]={config:t,listeners:[e]},s.removeAllListeners(t.socketChannel),s.on(t.socketChannel,(e=>{m[t.notifChannel]&&m[t.notifChannel].listeners&&m[t.notifChannel].listeners.length?m[t.notifChannel].listeners.map((t=>{t(e)})):s.emit(m[t.notifChannel].config.socketUnsubChannel,{})})))})(e,t),{...t,removeListener:()=>((e,t)=>{m&&m[t.notifChannel]&&(m[t.notifChannel].listeners=m[t.notifChannel].listeners.filter((t=>t!==e)),!m[t.notifChannel].listeners.length&&m[t.notifChannel].config&&m[t.notifChannel].config.socketUnsubChannel&&s&&(s.emit(m[t.notifChannel].config.socketUnsubChannel,{}),delete m[t.notifChannel]))})(e,t)}),n={...t,addListener:e};r(n)}}))}))});const I=e=>"[object Object]"===Object.prototype.toString.call(e),P=(e,t,n,i)=>{if(!I(e)||!I(t)||"function"!=typeof n||i&&"function"!=typeof i)throw"Expecting: ( basicFilter<object>, options<object>, onChange<function> , onError?<function>) but got something else"},A=["subscribe","subscribeOne"];Object.keys(v).forEach((e=>{Object.keys(v[e]).sort(((e,t)=>A.includes(e)-A.includes(t))).forEach((i=>{if(["find","findOne"].includes(i)&&(v[e].getJoinedTables=function(){return(w||[]).filter((t=>Array.isArray(t)&&t.includes(e))).flat().filter((t=>t!==e))}),"sync"===i){if(v[e]._syncInfo={...v[e][i]},n){v[e].getSync=(t,i={})=>n.create({name:e,filter:t,db:v,...i});const t=async(t={},i={},s)=>{const r=`${e}.${JSON.stringify(t)}.${JSON.stringify(i)}`;return u[r]||(u[r]=await n.create({...i,name:e,filter:t,db:v,onError:s})),u[r]};v[e].sync=async(e,n={handlesOnData:!0,select:"*"},i,s)=>{P(e,n,i,s);const r=await t(e,n,s);return await r.sync(i,n.handlesOnData)},v[e].syncOne=async(e,n={handlesOnData:!0},i,s)=>{P(e,n,i,s);const r=await t(e,n,s);return await r.syncOne(e,i,n.handlesOnData)}}v[e]._sync=function(n,r,o){return async function({tableName:e,command:n,param1:i,param2:r},o){const{onPullRequest:a,onSyncRequest:l,onUpdates:c}=o;function h(e){return Object.freeze({unsync:function(){!function(e,n){(0,t.debug)("_unsync",{channelName:e,triggers:n}),new Promise(((t,i)=>{f[e]&&(f[e].triggers=f[e].triggers.filter((e=>e.onPullRequest!==n.onPullRequest&&e.onSyncRequest!==n.onSyncRequest&&e.onUpdates!==n.onUpdates)),f[e].triggers.length||(s.emit(e+"unsync",{},((e,n)=>{e?i(e):t(n)})),s.removeListener(e,f[e].onCall),delete f[e]))}))}(e,o)},syncData:function(t,n,i){s.emit(e,{onSyncRequest:{...l({}),...{data:t}||{},...{deleted:n}||{}}},i?e=>{i(e)}:null)}})}const d=Object.keys(f).find((t=>{let s=f[t];return s.tableName===e&&s.command===n&&JSON.stringify(s.param1||{})===JSON.stringify(i||{})&&JSON.stringify(s.param2||{})===JSON.stringify(r||{})}));if(d)return f[d].triggers.push(o),h(d);{const u=await y({tableName:e,command:n,param1:i,param2:r},l),{channelName:m,synced_field:g,id_fields:p}=u;function b(t,n){t&&f[m]&&f[m].triggers.map((({onUpdates:i,onSyncRequest:s,onPullRequest:r})=>{t.data?Promise.resolve(i(t)).then((()=>{n&&n({ok:!0})})).catch((t=>{n?n({err:t}):console.error(e+" onUpdates error",t)})):t.onSyncRequest?Promise.resolve(s(t.onSyncRequest)).then((e=>n({onSyncRequest:e}))).catch((t=>{n?n({err:t}):console.error(e+" onSyncRequest error",t)})):t.onPullRequest?Promise.resolve(r(t.onPullRequest)).then((e=>{n({data:e})})).catch((t=>{n?n({err:t}):console.error(e+" onPullRequest error",t)})):console.log("unexpected response")}))}return f[m]={tableName:e,command:n,param1:i,param2:r,triggers:[o],syncInfo:u,onCall:b},s.on(m,b),h(m)}}({tableName:e,command:i,param1:n,param2:r},o)}}else if(A.includes(i)){v[e][i]=function(t,n,s,r){return P(t,n,s,r),S(v,{tableName:e,command:i,param1:t,param2:n},s,r)};const t="subscribeOne";i!==t&&A.includes(t)||(v[e][t]=function(t,n,s,r){return P(t,n,s,r),S(v,{tableName:e,command:i,param1:t,param2:n},(e=>{s(e[0])}),r)})}else v[e][i]=function(t,n,r){return new Promise(((o,a)=>{s.emit(c,{tableName:e,command:i,param1:t,param2:n,param3:r},((e,t)=>{e?a(e):o(t)}))}))}}))})),d&&Object.keys(d).length&&Object.keys(d).map((async e=>{try{let t=d[e];await b(t),s.on(e,t.onCall)}catch(e){console.error("There was an issue reconnecting old subscriptions",e)}})),f&&Object.keys(f).length&&Object.keys(f).filter((e=>f[e].triggers&&f[e].triggers.length)).map((async e=>{try{let t=f[e];await y(t,t.triggers[0].onSyncRequest),s.on(e,t.onCall)}catch(e){console.error("There was an issue reconnecting olf subscriptions",e)}})),w.flat().map((e=>{function t(t=!0,n,i,s){return{[t?"$leftJoin":"$innerJoin"]:e,filter:n,select:i,...s}}v.innerJoin=v.innerJoin||{},v.leftJoin=v.leftJoin||{},v.innerJoinOne=v.innerJoinOne||{},v.leftJoinOne=v.leftJoinOne||{},v.leftJoin[e]=(e,n,i={})=>t(!0,e,n,i),v.innerJoin[e]=(e,n,i={})=>t(!1,e,n,i),v.leftJoinOne[e]=(e,n,i={})=>t(!0,e,n,{...i,limit:1}),v.innerJoinOne[e]=(e,n,i={})=>t(!1,e,n,{...i,limit:1})})),(async()=>{try{await r(v,T,_,E)}catch(e){console.error("Prostgles: Error within onReady: \n",e),l(e)}e(v)})()}))}))}},792:function(e){var t;this||window,t=()=>(()=>{"use strict";var e={444:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.EXISTS_KEYS=t.GeomFilter_Funcs=t.GeomFilterKeys=t.TextFilterFTSKeys=t.TextFilter_FullTextSearchFilterKeys=t.CompareInFilterKeys=t.CompareFilterKeys=void 0,t.CompareFilterKeys=["=","$eq","<>",">",">=","<=","$eq","$ne","$gt","$gte","$lte"],t.CompareInFilterKeys=["$in","$nin"],t.TextFilter_FullTextSearchFilterKeys=["to_tsquery","plainto_tsquery","phraseto_tsquery","websearch_to_tsquery"],t.TextFilterFTSKeys=["@@","@>","<@","$contains","$containedBy"],t.GeomFilterKeys=["~","~=","@","|&>","|>>",">>","=","<<|","<<","&>","&<|","&<","&&&","&&"];const n=["ST_MakeEnvelope","ST_MakePolygon"];t.GeomFilter_Funcs=n.concat(n.map((e=>e.toLowerCase()))),t.EXISTS_KEYS=["$exists","$notExists","$existsJoined","$notExistsJoined"]},590:function(e,t,n){var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var s=Object.getOwnPropertyDescriptor(t,n);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,s)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),s=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||i(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),t.get=t.WAL=t.unpatchText=t.stableStringify=t.isEmpty=t.getTextPatch=t.asName=t.RULE_METHODS=t.CHANNELS=t.TS_PG_Types=t._PG_postgis=t._PG_date=t._PG_bool=t._PG_json=t._PG_numbers=t._PG_strings=void 0,t._PG_strings=["bpchar","char","varchar","text","citext","uuid","bytea","inet","time","timetz","interval","name"],t._PG_numbers=["int2","int4","int8","float4","float8","numeric","money","oid"],t._PG_json=["json","jsonb"],t._PG_bool=["bool"],t._PG_date=["date","timestamp","timestamptz"],t._PG_postgis=["geometry","geography"],t.TS_PG_Types={string:t._PG_strings,number:t._PG_numbers,boolean:t._PG_bool,Object:t._PG_json,Date:t._PG_date,"Array<number>":t._PG_numbers.map((e=>`_${e}`)),"Array<boolean>":t._PG_bool.map((e=>`_${e}`)),"Array<string>":t._PG_strings.map((e=>`_${e}`)),"Array<Object>":t._PG_json.map((e=>`_${e}`)),"Array<Date>":t._PG_date.map((e=>`_${e}`)),any:[]};const r="_psqlWS_.";t.CHANNELS={SCHEMA_CHANGED:r+"schema-changed",SCHEMA:r+"schema",DEFAULT:r,SQL:"_psqlWS_.sql",METHOD:"_psqlWS_.method",NOTICE_EV:"_psqlWS_.notice",LISTEN_EV:"_psqlWS_.listen",REGISTER:"_psqlWS_.register",LOGIN:"_psqlWS_.login",LOGOUT:"_psqlWS_.logout",AUTHGUARD:"_psqlWS_.authguard",_preffix:r},t.RULE_METHODS={getColumns:["getColumns"],getInfo:["getInfo"],insert:["insert","upsert"],update:["update","upsert","updateBatch"],select:["findOne","find","count","size"],delete:["delete","remove"],sync:["sync","unsync"],subscribe:["unsubscribe","subscribe","subscribeOne"]};var o=n(128);Object.defineProperty(t,"asName",{enumerable:!0,get:function(){return o.asName}}),Object.defineProperty(t,"getTextPatch",{enumerable:!0,get:function(){return o.getTextPatch}}),Object.defineProperty(t,"isEmpty",{enumerable:!0,get:function(){return o.isEmpty}}),Object.defineProperty(t,"stableStringify",{enumerable:!0,get:function(){return o.stableStringify}}),Object.defineProperty(t,"unpatchText",{enumerable:!0,get:function(){return o.unpatchText}}),Object.defineProperty(t,"WAL",{enumerable:!0,get:function(){return o.WAL}}),Object.defineProperty(t,"get",{enumerable:!0,get:function(){return o.get}}),s(n(444),t)},899:(e,t)=>{function n(e,t){var n=e[0],i=e[1],l=e[2],c=e[3];n=s(n,i,l,c,t[0],7,-680876936),c=s(c,n,i,l,t[1],12,-389564586),l=s(l,c,n,i,t[2],17,606105819),i=s(i,l,c,n,t[3],22,-1044525330),n=s(n,i,l,c,t[4],7,-176418897),c=s(c,n,i,l,t[5],12,1200080426),l=s(l,c,n,i,t[6],17,-1473231341),i=s(i,l,c,n,t[7],22,-45705983),n=s(n,i,l,c,t[8],7,1770035416),c=s(c,n,i,l,t[9],12,-1958414417),l=s(l,c,n,i,t[10],17,-42063),i=s(i,l,c,n,t[11],22,-1990404162),n=s(n,i,l,c,t[12],7,1804603682),c=s(c,n,i,l,t[13],12,-40341101),l=s(l,c,n,i,t[14],17,-1502002290),n=r(n,i=s(i,l,c,n,t[15],22,1236535329),l,c,t[1],5,-165796510),c=r(c,n,i,l,t[6],9,-1069501632),l=r(l,c,n,i,t[11],14,643717713),i=r(i,l,c,n,t[0],20,-373897302),n=r(n,i,l,c,t[5],5,-701558691),c=r(c,n,i,l,t[10],9,38016083),l=r(l,c,n,i,t[15],14,-660478335),i=r(i,l,c,n,t[4],20,-405537848),n=r(n,i,l,c,t[9],5,568446438),c=r(c,n,i,l,t[14],9,-1019803690),l=r(l,c,n,i,t[3],14,-187363961),i=r(i,l,c,n,t[8],20,1163531501),n=r(n,i,l,c,t[13],5,-1444681467),c=r(c,n,i,l,t[2],9,-51403784),l=r(l,c,n,i,t[7],14,1735328473),n=o(n,i=r(i,l,c,n,t[12],20,-1926607734),l,c,t[5],4,-378558),c=o(c,n,i,l,t[8],11,-2022574463),l=o(l,c,n,i,t[11],16,1839030562),i=o(i,l,c,n,t[14],23,-35309556),n=o(n,i,l,c,t[1],4,-1530992060),c=o(c,n,i,l,t[4],11,1272893353),l=o(l,c,n,i,t[7],16,-155497632),i=o(i,l,c,n,t[10],23,-1094730640),n=o(n,i,l,c,t[13],4,681279174),c=o(c,n,i,l,t[0],11,-358537222),l=o(l,c,n,i,t[3],16,-722521979),i=o(i,l,c,n,t[6],23,76029189),n=o(n,i,l,c,t[9],4,-640364487),c=o(c,n,i,l,t[12],11,-421815835),l=o(l,c,n,i,t[15],16,530742520),n=a(n,i=o(i,l,c,n,t[2],23,-995338651),l,c,t[0],6,-198630844),c=a(c,n,i,l,t[7],10,1126891415),l=a(l,c,n,i,t[14],15,-1416354905),i=a(i,l,c,n,t[5],21,-57434055),n=a(n,i,l,c,t[12],6,1700485571),c=a(c,n,i,l,t[3],10,-1894986606),l=a(l,c,n,i,t[10],15,-1051523),i=a(i,l,c,n,t[1],21,-2054922799),n=a(n,i,l,c,t[8],6,1873313359),c=a(c,n,i,l,t[15],10,-30611744),l=a(l,c,n,i,t[6],15,-1560198380),i=a(i,l,c,n,t[13],21,1309151649),n=a(n,i,l,c,t[4],6,-145523070),c=a(c,n,i,l,t[11],10,-1120210379),l=a(l,c,n,i,t[2],15,718787259),i=a(i,l,c,n,t[9],21,-343485551),e[0]=u(n,e[0]),e[1]=u(i,e[1]),e[2]=u(l,e[2]),e[3]=u(c,e[3])}function i(e,t,n,i,s,r){return t=u(u(t,e),u(i,r)),u(t<<s|t>>>32-s,n)}function s(e,t,n,s,r,o,a){return i(t&n|~t&s,e,t,r,o,a)}function r(e,t,n,s,r,o,a){return i(t&s|n&~s,e,t,r,o,a)}function o(e,t,n,s,r,o,a){return i(t^n^s,e,t,r,o,a)}function a(e,t,n,s,r,o,a){return i(n^(t|~s),e,t,r,o,a)}function l(e){var t,n=[];for(t=0;t<64;t+=4)n[t>>2]=e.charCodeAt(t)+(e.charCodeAt(t+1)<<8)+(e.charCodeAt(t+2)<<16)+(e.charCodeAt(t+3)<<24);return n}Object.defineProperty(t,"__esModule",{value:!0}),t.md5=t.md5cycle=void 0,t.md5cycle=n;var c="0123456789abcdef".split("");function h(e){for(var t="",n=0;n<4;n++)t+=c[e>>8*n+4&15]+c[e>>8*n&15];return t}function d(e){return function(e){for(var t=0;t<e.length;t++)e[t]=h(e[t]);return e.join("")}(function(e){var t,i=e.length,s=[1732584193,-271733879,-1732584194,271733878];for(t=64;t<=e.length;t+=64)n(s,l(e.substring(t-64,t)));e=e.substring(t-64);var r=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(t=0;t<e.length;t++)r[t>>2]|=e.charCodeAt(t)<<(t%4<<3);if(r[t>>2]|=128<<(t%4<<3),t>55)for(n(s,r),t=0;t<16;t++)r[t]=0;return r[14]=8*i,n(s,r),s}(e))}function u(e,t){return e+t&4294967295}t.md5=d,d("hello")},128:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isDefined=t.isObject=t.get=t.isEmpty=t.WAL=t.unpatchText=t.getTextPatch=t.stableStringify=t.asName=void 0;const i=n(899);function s(e){for(var t in e)return!1;return!0}t.asName=function(e){if(null==e||!e.toString||!e.toString())throw"Expecting a non empty string";return`"${e.toString().replace(/"/g,'""')}"`},t.stableStringify=function(e,t){t||(t={}),"function"==typeof t&&(t={cmp:t});var n,i="boolean"==typeof t.cycles&&t.cycles,s=t.cmp&&(n=t.cmp,function(e){return function(t,i){var s={key:t,value:e[t]},r={key:i,value:e[i]};return n(s,r)}}),r=[];return function e(t){if(t&&t.toJSON&&"function"==typeof t.toJSON&&(t=t.toJSON()),void 0!==t){if("number"==typeof t)return isFinite(t)?""+t:"null";if("object"!=typeof t)return JSON.stringify(t);var n,o;if(Array.isArray(t)){for(o="[",n=0;n<t.length;n++)n&&(o+=","),o+=e(t[n])||"null";return o+"]"}if(null===t)return"null";if(-1!==r.indexOf(t)){if(i)return JSON.stringify("__cycle__");throw new TypeError("Converting circular structure to JSON")}var a=r.push(t)-1,l=Object.keys(t).sort(s&&s(t));for(o="",n=0;n<l.length;n++){var c=l[n],h=e(t[c]);h&&(o&&(o+=","),o+=JSON.stringify(c)+":"+h)}return r.splice(a,1),"{"+o+"}"}}(e)},t.getTextPatch=function(e,t){if(!(e&&t&&e.trim().length&&t.trim().length))return t;if(e===t)return{from:0,to:0,text:"",md5:(0,i.md5)(t)};function n(n=1){let i=n<1?-1:0,s=!1;for(;!s&&Math.abs(i)<=t.length;){const r=n<1?[i]:[0,i];e.slice(...r)!==t.slice(...r)?s=!0:i+=1*Math.sign(n)}return i}let s=n()-1,r=e.length+n(-1)+1,o=t.length+n(-1)+1;return{from:s,to:r,text:t.slice(s,o),md5:(0,i.md5)(t)}},t.unpatchText=function(e,t){if(!t||"string"==typeof t)return t;const{from:n,to:s,text:r,md5:o}=t;if(null===r||null===e)return r;let a=e.slice(0,n)+r+e.slice(s);if(o&&(0,i.md5)(a)!==o)throw"Patch text error: Could not match md5 hash: (original/result) \n"+e+"\n"+a;return a},t.WAL=class{constructor(e){if(this.changed={},this.sending={},this.sentHistory={},this.callbacks=[],this.sort=(e,t)=>{const{orderBy:n}=this.options;return n&&e&&t&&n.map((n=>{if(!(n.fieldName in e)||!(n.fieldName in t))throw"Replication error: \n some orderBy fields missing from data";let i=n.asc?e[n.fieldName]:t[n.fieldName],s=n.asc?t[n.fieldName]:e[n.fieldName],r=+i-+s,o=i<s?-1:i==s?0:1;return"number"===n.tsDataType&&Number.isFinite(r)?r:o})).find((e=>e))||0},this.isInHistory=e=>{if(!e)throw"Provide item";const t=e[this.options.synced_field];if(!Number.isFinite(+t))throw"Provided item Synced field value is missing/invalid ";const n=this.sentHistory[this.getIdStr(e)],i=n?.[this.options.synced_field];if(n){if(!Number.isFinite(+i))throw"Provided historic item Synced field value is missing/invalid";if(+i==+t)return!0}return!1},this.addData=e=>{s(this.changed)&&this.options.onSendStart&&this.options.onSendStart(),e.map((e=>{const{initial:t,current:n}={...e};if(!n)throw"Expecting { current: object, initial?: object }";const i=this.getIdStr(n);this.changed=this.changed||{},this.changed[i]=this.changed[i]||{initial:t,current:n},this.changed[i].current={...this.changed[i].current,...n}})),this.sendItems()},this.isOnSending=!1,this.isSendingTimeout=void 0,this.willDeleteHistory=void 0,this.sendItems=async()=>{const{DEBUG_MODE:e,onSend:t,onSendEnd:n,batch_size:i,throttle:r,historyAgeSeconds:o=2}=this.options;if(this.isSendingTimeout||this.sending&&!s(this.sending))return;if(!this.changed||s(this.changed))return;let a,l=[],c=[],h={};Object.keys(this.changed).sort(((e,t)=>this.sort(this.changed[e].current,this.changed[t].current))).slice(0,i).map((e=>{let t={...this.changed[e]};this.sending[e]={...t},c.push({...t}),h[e]={...t.current},delete this.changed[e]})),l=c.map((e=>e.current)),e&&console.log(this.options.id," SENDING lr->",l[l.length-1]),this.isSendingTimeout||(this.isSendingTimeout=setTimeout((()=>{this.isSendingTimeout=void 0,s(this.changed)||this.sendItems()}),r)),this.isOnSending=!0;try{await t(l,c),o&&(this.sentHistory={...this.sentHistory,...h},this.willDeleteHistory||(this.willDeleteHistory=setTimeout((()=>{this.willDeleteHistory=void 0,this.sentHistory={}}),1e3*o)))}catch(e){a=e,console.error("WAL onSend failed:",e,l,c)}if(this.isOnSending=!1,this.callbacks.length){const e=Object.keys(this.sending);this.callbacks.forEach(((t,n)=>{t.idStrs=t.idStrs.filter((t=>e.includes(t))),t.idStrs.length||t.cb(a)})),this.callbacks=this.callbacks.filter((e=>e.idStrs.length))}this.sending={},e&&console.log(this.options.id," SENT lr->",l[l.length-1]),s(this.changed)?n&&n(l,c,a):this.sendItems()},this.options={...e},!this.options.orderBy){const{synced_field:t,id_fields:n}=e;this.options.orderBy=[t,...n.sort()].map((e=>({fieldName:e,tsDataType:e===t?"number":"string",asc:!0})))}}isSending(){const e=this.isOnSending||!(s(this.sending)&&s(this.changed));return this.options.DEBUG_MODE&&console.log(this.options.id," CHECKING isSending ->",e),e}getIdStr(e){return this.options.id_fields.sort().map((t=>`${e[t]||""}`)).join(".")}getIdObj(e){let t={};return this.options.id_fields.sort().map((n=>{t[n]=e[n]})),t}getDeltaObj(e){let t={};return Object.keys(e).map((n=>{this.options.id_fields.includes(n)||(t[n]=e[n])})),t}},t.isEmpty=s,t.get=function(e,t){let n=t,i=e;return e?("string"==typeof n&&(n=n.split(".")),n.reduce(((e,t)=>e&&e[t]?e[t]:void 0),i)):e},t.isObject=function(e){return Boolean(e&&"object"==typeof e&&!Array.isArray(e))},t.isDefined=function(e){return null!=e}}},t={};return function n(i){var s=t[i];if(void 0!==s)return s.exports;var r=t[i]={exports:{}};return e[i].call(r.exports,r,r.exports,n),r.exports}(590)})(),e.exports=t()}},t={};function n(i){var s=t[i];if(void 0!==s)return s.exports;var r=t[i]={exports:{}};return e[i].call(r.exports,r,r.exports,n),r.exports}var i={};return(()=>{"use strict";var e=i;Object.defineProperty(e,"__esModule",{value:!0}),e.prostgles=void 0;const t=n(274),s=n(133);e.prostgles=function(e){return(0,t.prostgles)(e,s.SyncedTable)}})(),i})()));