@auxilium/datalynk-client 0.9.12 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -78,6 +78,106 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
78
78
  return this.from(super.finally(res));
79
79
  }
80
80
  }
81
+ function formatDate(format = "YYYY-MM-DD H:mm", date = /* @__PURE__ */ new Date(), tz) {
82
+ const timezones = [
83
+ ["IDLW", -12],
84
+ ["SST", -11],
85
+ ["HST", -10],
86
+ ["AKST", -9],
87
+ ["PST", -8],
88
+ ["MST", -7],
89
+ ["CST", -6],
90
+ ["EST", -5],
91
+ ["AST", -4],
92
+ ["BRT", -3],
93
+ ["MAT", -2],
94
+ ["AZOT", -1],
95
+ ["UTC", 0],
96
+ ["CET", 1],
97
+ ["EET", 2],
98
+ ["MSK", 3],
99
+ ["AST", 4],
100
+ ["PKT", 5],
101
+ ["IST", 5.5],
102
+ ["BST", 6],
103
+ ["ICT", 7],
104
+ ["CST", 8],
105
+ ["JST", 9],
106
+ ["AEST", 10],
107
+ ["SBT", 11],
108
+ ["FJT", 12],
109
+ ["TOT", 13],
110
+ ["LINT", 14]
111
+ ];
112
+ function adjustTz(date2, gmt) {
113
+ const currentOffset = date2.getTimezoneOffset();
114
+ const adjustedOffset = gmt * 60;
115
+ return new Date(date2.getTime() + (adjustedOffset + currentOffset) * 6e4);
116
+ }
117
+ function day(num) {
118
+ return ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"][num] || "Unknown";
119
+ }
120
+ function doy(date2) {
121
+ const start = /* @__PURE__ */ new Date(`${date2.getFullYear()}-01-01 0:00:00`);
122
+ return Math.ceil((date2.getTime() - start.getTime()) / (1e3 * 60 * 60 * 24));
123
+ }
124
+ function month(num) {
125
+ return ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"][num] || "Unknown";
126
+ }
127
+ function suffix(num) {
128
+ if (num % 100 >= 11 && num % 100 <= 13) return `${num}th`;
129
+ switch (num % 10) {
130
+ case 1:
131
+ return `${num}st`;
132
+ case 2:
133
+ return `${num}nd`;
134
+ case 3:
135
+ return `${num}rd`;
136
+ default:
137
+ return `${num}th`;
138
+ }
139
+ }
140
+ function tzOffset(offset) {
141
+ const hours = ~~(offset / 60);
142
+ const minutes = offset % 60;
143
+ return (offset > 0 ? "-" : "") + `${hours}:${minutes.toString().padStart(2, "0")}`;
144
+ }
145
+ if (typeof date == "number" || typeof date == "string") date = new Date(date);
146
+ let t;
147
+ if (tz == null) tz = -(date.getTimezoneOffset() / 60);
148
+ t = timezones.find((t2) => isNaN(tz) ? t2[0] == tz : t2[1] == tz);
149
+ if (!t) throw new Error(`Unknown timezone: ${tz}`);
150
+ date = adjustTz(date, t[1]);
151
+ const tokens = {
152
+ "YYYY": date.getFullYear().toString(),
153
+ "YY": date.getFullYear().toString().slice(2),
154
+ "MMMM": month(date.getMonth()),
155
+ "MMM": month(date.getMonth()).slice(0, 3),
156
+ "MM": (date.getMonth() + 1).toString().padStart(2, "0"),
157
+ "M": (date.getMonth() + 1).toString(),
158
+ "DDD": doy(date).toString(),
159
+ "DD": date.getDate().toString().padStart(2, "0"),
160
+ "Do": suffix(date.getDate()),
161
+ "D": date.getDate().toString(),
162
+ "dddd": day(date.getDay()),
163
+ "ddd": day(date.getDay()).slice(0, 3),
164
+ "HH": date.getHours().toString().padStart(2, "0"),
165
+ "H": date.getHours().toString(),
166
+ "hh": (date.getHours() % 12 || 12).toString().padStart(2, "0"),
167
+ "h": (date.getHours() % 12 || 12).toString(),
168
+ "mm": date.getMinutes().toString().padStart(2, "0"),
169
+ "m": date.getMinutes().toString(),
170
+ "ss": date.getSeconds().toString().padStart(2, "0"),
171
+ "s": date.getSeconds().toString(),
172
+ "SSS": date.getMilliseconds().toString().padStart(3, "0"),
173
+ "A": date.getHours() >= 12 ? "PM" : "AM",
174
+ "a": date.getHours() >= 12 ? "pm" : "am",
175
+ "ZZ": tzOffset(t[1] * 60).replace(":", ""),
176
+ "Z": tzOffset(t[1] * 60),
177
+ "z": typeof tz == "string" ? tz : t[0]
178
+ };
179
+ return format.replace(/YYYY|YY|MMMM|MMM|MM|M|DDD|DD|Do|D|dddd|ddd|HH|H|hh|h|mm|m|ss|s|SSS|A|a|ZZ|Z|z/g, (token) => tokens[token]);
180
+ }
81
181
  class TypedEmitter {
82
182
  constructor() {
83
183
  __publicField2(this, "listeners", {});
@@ -297,6 +397,25 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
297
397
  return new CustomError(message, code);
298
398
  }
299
399
  }
400
+ class HttpResponse extends Response {
401
+ constructor(resp, stream) {
402
+ const body = [204, 205, 304].includes(resp.status) ? null : stream;
403
+ super(body, {
404
+ headers: resp.headers,
405
+ status: resp.status,
406
+ statusText: resp.statusText
407
+ });
408
+ __publicField2(this, "data");
409
+ __publicField2(this, "ok");
410
+ __publicField2(this, "redirected");
411
+ __publicField2(this, "type");
412
+ __publicField2(this, "url");
413
+ this.ok = resp.ok;
414
+ this.redirected = resp.redirected;
415
+ this.type = resp.type;
416
+ this.url = resp.url;
417
+ }
418
+ }
300
419
  const _Http = class _Http2 {
301
420
  constructor(defaults = {}) {
302
421
  __publicField2(this, "interceptors", {});
@@ -325,8 +444,9 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
325
444
  request(opts = {}) {
326
445
  var _a;
327
446
  if (!this.url && !opts.url) throw new Error("URL needs to be set");
328
- let url = (((_a = opts.url) == null ? void 0 : _a.startsWith("http")) ? opts.url : (this.url || "") + (opts.url || "")).replace(/([^:]\/)\/+/g, "$1");
329
- if (opts.fragment) url.includes("#") ? url.replace(/#.*(\?|\n)/g, (match, arg1) => `#${opts.fragment}${arg1}`) : url += "#" + opts.fragment;
447
+ let url = ((_a = opts.url) == null ? void 0 : _a.startsWith("http")) ? opts.url : (this.url || "") + (opts.url || "");
448
+ url = url.replaceAll(/([^:]\/)\/+/g, "$1");
449
+ if (opts.fragment) url.includes("#") ? url.replace(/#.*(\?|\n)/g, (match, arg1) => `#${opts.fragment}${arg1}`) : `${url}#${opts.fragment}`;
330
450
  if (opts.query) {
331
451
  const q = Array.isArray(opts.query) ? opts.query : Object.keys(opts.query).map((k) => ({ key: k, value: opts.query[k] }));
332
452
  url += (url.includes("?") ? "&" : "?") + q.map((q2) => `${q2.key}=${q2.value}`).join("&");
@@ -368,13 +488,13 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
368
488
  push();
369
489
  }
370
490
  });
371
- resp.data = new Response(stream);
372
- if (opts.decode == null || opts.decode) {
491
+ resp = new HttpResponse(resp, stream);
492
+ if (opts.decode !== false) {
373
493
  const content = (_b = resp.headers.get("Content-Type")) == null ? void 0 : _b.toLowerCase();
374
- if (content == null ? void 0 : content.includes("form")) resp.data = await resp.data.formData();
375
- else if (content == null ? void 0 : content.includes("json")) resp.data = await resp.data.json();
376
- else if (content == null ? void 0 : content.includes("text")) resp.data = await resp.data.text();
377
- else if (content == null ? void 0 : content.includes("application")) resp.data = await resp.data.blob();
494
+ if (content == null ? void 0 : content.includes("form")) resp.data = await resp.formData();
495
+ else if (content == null ? void 0 : content.includes("json")) resp.data = await resp.json();
496
+ else if (content == null ? void 0 : content.includes("text")) resp.data = await resp.text();
497
+ else if (content == null ? void 0 : content.includes("application")) resp.data = await resp.blob();
378
498
  }
379
499
  if (resp.ok) res(resp);
380
500
  else rej(resp);
@@ -394,31 +514,13 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
394
514
  }).join("")));
395
515
  }
396
516
  const CliEffects = {
397
- CLEAR: "\x1B[0m",
398
- BRIGHT: "\x1B[1m",
399
- DIM: "\x1B[2m",
400
- UNDERSCORE: "\x1B[4m",
401
- BLINK: "\x1B[5m",
402
- REVERSE: "\x1B[7m",
403
- HIDDEN: "\x1B[8m"
517
+ CLEAR: "\x1B[0m"
404
518
  };
405
519
  const CliForeground = {
406
- BLACK: "\x1B[30m",
407
520
  RED: "\x1B[31m",
408
- GREEN: "\x1B[32m",
409
521
  YELLOW: "\x1B[33m",
410
522
  BLUE: "\x1B[34m",
411
- MAGENTA: "\x1B[35m",
412
- CYAN: "\x1B[36m",
413
- LIGHT_GREY: "\x1B[37m",
414
- GREY: "\x1B[90m",
415
- LIGHT_RED: "\x1B[91m",
416
- LIGHT_GREEN: "\x1B[92m",
417
- LIGHT_YELLOW: "\x1B[93m",
418
- LIGHT_BLUE: "\x1B[94m",
419
- LIGHT_MAGENTA: "\x1B[95m",
420
- LIGHT_CYAN: "\x1B[96m",
421
- WHITE: "\x1B[97m"
523
+ LIGHT_GREY: "\x1B[37m"
422
524
  };
423
525
  const _Logger = class _Logger2 extends TypedEmitter {
424
526
  constructor(namespace) {
@@ -462,112 +564,6 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
462
564
  }
463
565
  };
464
566
  __publicField2(_Logger, "LOG_LEVEL", 4);
465
- function formatDate(format = "YYYY-MM-DD H:mm", date = /* @__PURE__ */ new Date(), tz) {
466
- const timezones = [
467
- ["IDLW", -12],
468
- ["SST", -11],
469
- ["HST", -10],
470
- ["AKST", -9],
471
- ["PST", -8],
472
- ["MST", -7],
473
- ["CST", -6],
474
- ["EST", -5],
475
- ["AST", -4],
476
- ["BRT", -3],
477
- ["MAT", -2],
478
- ["AZOT", -1],
479
- ["UTC", 0],
480
- ["CET", 1],
481
- ["EET", 2],
482
- ["MSK", 3],
483
- ["AST", 4],
484
- ["PKT", 5],
485
- ["IST", 5.5],
486
- ["BST", 6],
487
- ["ICT", 7],
488
- ["CST", 8],
489
- ["JST", 9],
490
- ["AEST", 10],
491
- ["SBT", 11],
492
- ["FJT", 12],
493
- ["TOT", 13],
494
- ["LINT", 14]
495
- ];
496
- function adjustTz(date2, gmt) {
497
- const currentOffset = date2.getTimezoneOffset();
498
- const adjustedOffset = gmt * 60;
499
- return new Date(date2.getTime() + (adjustedOffset + currentOffset) * 6e4);
500
- }
501
- function day(num) {
502
- return ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"][num] || "Unknown";
503
- }
504
- function doy(date2) {
505
- const start = /* @__PURE__ */ new Date(`${date2.getFullYear()}-01-01 0:00:00`);
506
- return Math.ceil((date2.getTime() - start.getTime()) / (1e3 * 60 * 60 * 24));
507
- }
508
- function month(num) {
509
- return ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"][num] || "Unknown";
510
- }
511
- function suffix(num) {
512
- if (num % 100 >= 11 && num % 100 <= 13) return `${num}th`;
513
- switch (num % 10) {
514
- case 1:
515
- return `${num}st`;
516
- case 2:
517
- return `${num}nd`;
518
- case 3:
519
- return `${num}rd`;
520
- default:
521
- return `${num}th`;
522
- }
523
- }
524
- function tzOffset(offset) {
525
- const hours = ~~(offset / 60);
526
- const minutes = offset % 60;
527
- return (offset > 0 ? "-" : "") + `${hours}:${minutes.toString().padStart(2, "0")}`;
528
- }
529
- if (typeof date == "number" || typeof date == "string") date = new Date(date);
530
- let t;
531
- if (tz == null) tz = -(date.getTimezoneOffset() / 60);
532
- t = timezones.find((t2) => isNaN(tz) ? t2[0] == tz : t2[1] == tz);
533
- if (!t) throw new Error(`Unknown timezone: ${tz}`);
534
- date = adjustTz(date, t[1]);
535
- const tokens = {
536
- "YYYY": date.getFullYear().toString(),
537
- "YY": date.getFullYear().toString().slice(2),
538
- "MMMM": month(date.getMonth()),
539
- "MMM": month(date.getMonth()).slice(0, 3),
540
- "MM": (date.getMonth() + 1).toString().padStart(2, "0"),
541
- "M": (date.getMonth() + 1).toString(),
542
- "DDD": doy(date).toString(),
543
- "DD": date.getDate().toString().padStart(2, "0"),
544
- "Do": suffix(date.getDate()),
545
- "D": date.getDate().toString(),
546
- "dddd": day(date.getDay()),
547
- "ddd": day(date.getDay()).slice(0, 3),
548
- "HH": date.getHours().toString().padStart(2, "0"),
549
- "H": date.getHours().toString(),
550
- "hh": (date.getHours() % 12 || 12).toString().padStart(2, "0"),
551
- "h": (date.getHours() % 12 || 12).toString(),
552
- "mm": date.getMinutes().toString().padStart(2, "0"),
553
- "m": date.getMinutes().toString(),
554
- "ss": date.getSeconds().toString().padStart(2, "0"),
555
- "s": date.getSeconds().toString(),
556
- "SSS": date.getMilliseconds().toString().padStart(3, "0"),
557
- "A": date.getHours() >= 12 ? "PM" : "AM",
558
- "a": date.getHours() >= 12 ? "pm" : "am",
559
- "ZZ": tzOffset(t[1] * 60).replace(":", ""),
560
- "Z": tzOffset(t[1] * 60),
561
- "z": typeof tz == "string" ? tz : t[0]
562
- };
563
- return format.replace(/YYYY|YY|MMMM|MMM|MM|M|DDD|DD|Do|D|dddd|ddd|HH|H|hh|h|mm|m|ss|s|SSS|A|a|ZZ|Z|z/g, (token) => tokens[token]);
564
- }
565
- function sleep(ms) {
566
- return new Promise((res) => setTimeout(res, ms));
567
- }
568
- async function sleepWhile(fn, checkInterval = 100) {
569
- while (await fn()) await sleep(checkInterval);
570
- }
571
567
  var extendStatics = function(d, b) {
572
568
  extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
573
569
  d2.__proto__ = b2;
@@ -787,11 +783,7 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
787
783
  }
788
784
  }
789
785
  var config = {
790
- onUnhandledError: null,
791
- onStoppedNotification: null,
792
- Promise: void 0,
793
- useDeprecatedSynchronousErrorHandling: false,
794
- useDeprecatedNextContext: false
786
+ Promise: void 0
795
787
  };
796
788
  var timeoutProvider = {
797
789
  setTimeout: function(handler, timeout) {
@@ -884,10 +876,6 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
884
876
  };
885
877
  return Subscriber2;
886
878
  }(Subscription);
887
- var _bind = Function.prototype.bind;
888
- function bind(fn, thisArg) {
889
- return _bind.call(fn, thisArg);
890
- }
891
879
  var ConsumerObserver = function() {
892
880
  function ConsumerObserver2(partialObserver) {
893
881
  this.partialObserver = partialObserver;
@@ -938,18 +926,7 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
938
926
  complete: complete !== null && complete !== void 0 ? complete : void 0
939
927
  };
940
928
  } else {
941
- var context_1;
942
- if (_this && config.useDeprecatedNextContext) {
943
- context_1 = Object.create(observerOrNext);
944
- context_1.unsubscribe = function() {
945
- return _this.unsubscribe();
946
- };
947
- partialObserver = {
948
- next: observerOrNext.next && bind(observerOrNext.next, context_1),
949
- error: observerOrNext.error && bind(observerOrNext.error, context_1),
950
- complete: observerOrNext.complete && bind(observerOrNext.complete, context_1)
951
- };
952
- } else {
929
+ {
953
930
  partialObserver = observerOrNext;
954
931
  }
955
932
  }
@@ -1679,7 +1656,7 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
1679
1656
  * @return {Promise<boolean>} True if system administrator
1680
1657
  */
1681
1658
  async isSysAdmin() {
1682
- return !!(await this.api.slice("sysadmin").select().where("auth_ref", "==", "$viewer").exec().keys()).length;
1659
+ return !!(await this.api.slice("sysadmin").select().where("auth_ref", "==", "$viewer").rows().exec()).length;
1683
1660
  }
1684
1661
  /**
1685
1662
  * Check if user is a table administrator
@@ -1687,7 +1664,7 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
1687
1664
  * @return {Promise<boolean>} True if table administrator
1688
1665
  */
1689
1666
  async isTableAdmin() {
1690
- return !!(await this.api.slice("tableadmins").select().where("auth_ref", "==", "$viewer").exec().keys()).length;
1667
+ return !!(await this.api.slice("tableadmins").select().where("auth_ref", "==", "$viewer").rows().exec()).length;
1691
1668
  }
1692
1669
  /**
1693
1670
  * Check if user is a user administrator
@@ -1695,7 +1672,7 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
1695
1672
  * @return {Promise<boolean>} True if user administrator
1696
1673
  */
1697
1674
  async isUserAdmin() {
1698
- return !!(await this.api.slice("useradmins").select().where("auth_ref", "==", "$viewer").exec().keys()).length;
1675
+ return !!(await this.api.slice("useradmins").select().where("auth_ref", "==", "$viewer").rows().exec()).length;
1699
1676
  }
1700
1677
  /**
1701
1678
  * Perform login and save the session token
@@ -1797,7 +1774,7 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
1797
1774
  this.url = `${this.api.url}file`;
1798
1775
  }
1799
1776
  associate(fileIds, slice, row, field, execute = true) {
1800
- const req = { [`${execute ? "!" : "$"}/tools/file/update`]: { row, field, slice, ids: fileIds } };
1777
+ const req = { [`${execute ? "!" : "$"}/tools/file/update`]: { slice, row, field, ids: fileIds } };
1801
1778
  if (execute) return this.api.request(req);
1802
1779
  return req;
1803
1780
  }
@@ -1836,7 +1813,7 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
1836
1813
  })).then(async (files2) => {
1837
1814
  if (associate) {
1838
1815
  let id = typeof associate.row == "number" ? associate.row : associate.row[associate.pk || "id"];
1839
- if (!id) id = await this.api.slice(associate.slice).insert(associate.row).exec().key();
1816
+ if (!id) id = await this.api.slice(associate.slice).insert(associate.row).id();
1840
1817
  await this.associate(files2.map((f2) => f2.id), associate == null ? void 0 : associate.slice, associate == null ? void 0 : associate.row, associate == null ? void 0 : associate.field);
1841
1818
  }
1842
1819
  return files2;
@@ -1996,112 +1973,6 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
1996
1973
  }
1997
1974
  }
1998
1975
  };
1999
- class SlicePromise {
2000
- /**
2001
- * An object to provide helpers for Datalynk results
2002
- *
2003
- * @param slice
2004
- * @param {SliceResponse<T>} promise Datalynk promise to handle
2005
- */
2006
- constructor(slice, promise) {
2007
- this.slice = slice;
2008
- this.promise = promise;
2009
- }
2010
- /**
2011
- * Catch promise errors
2012
- */
2013
- catch(callback) {
2014
- return this.promise.catch(callback);
2015
- }
2016
- /**
2017
- * Count rows or fetch count alias result
2018
- */
2019
- async count() {
2020
- var _a, _b;
2021
- const rows = await this.rows();
2022
- if (typeof ((_a = rows == null ? void 0 : rows[0]) == null ? void 0 : _a["count"]) == "number") return (_b = rows == null ? void 0 : rows[0]) == null ? void 0 : _b["count"];
2023
- return rows.length;
2024
- }
2025
- /**
2026
- * Log the raw result to the console for inspection
2027
- */
2028
- debug() {
2029
- this.promise.then((resp) => console.log(resp));
2030
- return this;
2031
- }
2032
- /**
2033
- * Fields that failed
2034
- */
2035
- async failed() {
2036
- let resp = await this.promise;
2037
- return resp.failed;
2038
- }
2039
- /**
2040
- * Catch promise errors
2041
- */
2042
- finally(callback) {
2043
- return this.promise.finally(callback);
2044
- }
2045
- /**
2046
- * Fields that were ignored (Perms or readonly)
2047
- */
2048
- async ignored() {
2049
- let resp = await this.promise;
2050
- return resp["ignored-fields"];
2051
- }
2052
- /**
2053
- * ID of first affected row
2054
- */
2055
- async key() {
2056
- return (await this.keys())[0];
2057
- }
2058
- /**
2059
- * IDs of all affected rows
2060
- */
2061
- async keys() {
2062
- let resp = await this.promise;
2063
- return resp.keys;
2064
- }
2065
- /**
2066
- * Fields that were affected successfully
2067
- */
2068
- async granted() {
2069
- let resp = await this.promise;
2070
- return resp.granted;
2071
- }
2072
- /**
2073
- * First row of data
2074
- */
2075
- async row() {
2076
- return (await this.rows())[0];
2077
- }
2078
- /**
2079
- * All rows of data
2080
- */
2081
- async rows() {
2082
- let resp = await this.promise;
2083
- return resp.rows;
2084
- }
2085
- /**
2086
- * Handle as normal request
2087
- */
2088
- then(success, error) {
2089
- return this.promise.then(success, error);
2090
- }
2091
- /**
2092
- * Get the raw promise
2093
- */
2094
- toPromise() {
2095
- return this.promise;
2096
- }
2097
- /**
2098
- * Get the transaction ID
2099
- */
2100
- async transaction() {
2101
- let resp = await this.promise;
2102
- return resp.tx;
2103
- }
2104
- }
2105
1976
  const _Slice = class _Slice {
2106
1977
  /**
2107
1978
  * An object to aid in constructing requests
@@ -2111,11 +1982,25 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
2111
1982
  */
2112
1983
  constructor(slice, api) {
2113
1984
  __publicField(this, "operation");
1985
+ __publicField(this, "popField");
2114
1986
  __publicField(this, "request", {});
1987
+ /** Log response automatically */
1988
+ __publicField(this, "debugging");
2115
1989
  /** Unsubscribe from changes, undefined if not subscribed */
2116
1990
  __publicField(this, "unsubscribe");
2117
1991
  /** Cached slice data as an observable */
2118
1992
  __publicField(this, "cache$", new BehaviorSubject([]));
1993
+ /**
1994
+ * Whitelist and alias fields. Alias of `fields()`
1995
+ * @example
1996
+ * ```ts
1997
+ * const id: {id: number, field2: any}[] = await new Slice<T>(12345)
1998
+ * .select().alias({id: 'id', field1: 'field2'}).exec().keys();
1999
+ * ```
2000
+ * @param {object} aliasKeyVals List of properties to whitelist and what to rename them to
2001
+ * @return {Slice<T>}
2002
+ */
2003
+ __publicField(this, "alias", this.fields);
2119
2004
  this.slice = slice;
2120
2005
  this.api = api;
2121
2006
  }
@@ -2129,19 +2014,13 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
2129
2014
  }
2130
2015
  /** Get raw API request */
2131
2016
  get raw() {
2132
- return { [this.operation]: { slice: this.slice, ...this.request } };
2133
- }
2134
- /**
2135
- * Whitelist and alias fields. Alias for the fields functions
2136
- * @example
2137
- * ```ts
2138
- * const id: {id: number, field2: any}[] = await new Slice<T>(12345)
2139
- * .select().alias({id: 'id', field1: 'field2'}).exec().keys();
2140
- * ```
2141
- * @param {object} aliasKeyVals List of properties to whitelist and what to rename them to
2142
- */
2143
- alias(aliasKeyVals) {
2144
- return this.fields(aliasKeyVals);
2017
+ return clean({
2018
+ [this.operation]: {
2019
+ ...this.request,
2020
+ slice: this.slice
2021
+ },
2022
+ "$pop": this.popField ? this.popField : void 0
2023
+ });
2145
2024
  }
2146
2025
  /**
2147
2026
  * Add an 'AND' condition inside the where argument
@@ -2153,6 +2032,7 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
2153
2032
  * .where({field2: 2, field3: 3})
2154
2033
  * .exec().rows();
2155
2034
  * ```
2035
+ * @return {Slice<T>}
2156
2036
  */
2157
2037
  and() {
2158
2038
  var _a;
@@ -2170,17 +2050,20 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
2170
2050
  * .exec().count();
2171
2051
  * ```
2172
2052
  * @param {object | string} arg Count argument
2053
+ * @return {Slice<T>}
2173
2054
  */
2174
2055
  count(arg = "id") {
2175
2056
  this.operation = "$/slice/report";
2176
2057
  this.request.fields = { count: ["$count", typeof arg == "object" ? arg : ["$field", arg]] };
2177
- return this;
2058
+ return this.pop("rows:0:count");
2178
2059
  }
2179
2060
  /**
2180
2061
  * Output the formed request to the console for inspection
2062
+ * @param {boolean} enabled Enable/Disable console logging
2063
+ * @return {Slice<T>}
2181
2064
  */
2182
- debug() {
2183
- console.debug(this.request);
2065
+ debug(enabled = true) {
2066
+ this.debugging = enabled;
2184
2067
  return this;
2185
2068
  }
2186
2069
  /**
@@ -2190,6 +2073,7 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
2190
2073
  * await new Slice(12345).delete(id).exec();
2191
2074
  * ```
2192
2075
  * @param {number | number[]} id ID(s) to delete
2076
+ * @return {Slice<T>}
2193
2077
  */
2194
2078
  delete(id) {
2195
2079
  this.operation = "$/slice/delete";
@@ -2208,6 +2092,7 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
2208
2092
  * .exec().rows();
2209
2093
  * ```
2210
2094
  * @param formula Excel formula to use as where clause
2095
+ * @return {Slice<T>}
2211
2096
  */
2212
2097
  excel(formula) {
2213
2098
  this.where(["$excel", formula]);
@@ -2216,17 +2101,26 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
2216
2101
  /**
2217
2102
  * Compile the request and send it
2218
2103
  * @param {ApiRequestOptions} options API Request options
2219
- * @return {SlicePromise<T>}
2104
+ * @return {Promise<T = any>} API response
2220
2105
  */
2221
2106
  exec(options) {
2222
2107
  if (!this.operation) throw new Error("No operation chosen");
2223
- this.request.slice = this.slice;
2224
- return new SlicePromise(this, this.api.request({ [this.operation]: this.request }, options));
2108
+ return this.api.request(this.raw, options).then((resp) => {
2109
+ if (this.debugging) console.log(resp);
2110
+ return resp;
2111
+ });
2225
2112
  }
2226
2113
  fields(keys) {
2227
2114
  this.request.fields = Array.isArray(keys) ? keys.reduce((acc, key) => ({ ...acc, [key]: key }), {}) : keys;
2228
2115
  return this;
2229
2116
  }
2117
+ /**
2118
+ * Unwrap response returning the first ID
2119
+ * @return {Slice<T>}
2120
+ */
2121
+ id() {
2122
+ return this.pop("rows:0:id");
2123
+ }
2230
2124
  /**
2231
2125
  * Set the request type to insert
2232
2126
  * @example
@@ -2237,6 +2131,7 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
2237
2131
  * ]).exec().keys();
2238
2132
  * ```
2239
2133
  * @param {T | T[]} rows Rows to be inserted into the slice
2134
+ * @return {Slice<T>}
2240
2135
  */
2241
2136
  insert(rows) {
2242
2137
  this.operation = "$/slice/xinsert";
@@ -2253,9 +2148,11 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
2253
2148
  * .exec().rows();
2254
2149
  * ```
2255
2150
  * @param {number} num Number of rows to return
2151
+ * @return {Slice<T>}
2256
2152
  */
2257
2153
  limit(num) {
2258
2154
  this.request.limit = num;
2155
+ return this;
2259
2156
  }
2260
2157
  /**
2261
2158
  * Add an 'OR' condition inside the where argument
@@ -2269,6 +2166,7 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
2269
2166
  * .where(['$gt', ['$field', field4], 4)
2270
2167
  * .exec().rows();
2271
2168
  * ```
2169
+ * @return {Slice<T>}
2272
2170
  */
2273
2171
  or() {
2274
2172
  var _a;
@@ -2289,12 +2187,36 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
2289
2187
  * ```
2290
2188
  * @param {string} field property name
2291
2189
  * @param {boolean} ascending Sort in ascending or descending order
2190
+ * @return {Slice<T>}
2292
2191
  */
2293
2192
  order(field, ascending = true) {
2294
2193
  if (!this.request.order) this.request.order = [];
2295
2194
  this.request.order.push([ascending ? "$asc" : "$desc", ["$field", field]]);
2296
2195
  return this;
2297
2196
  }
2197
+ /**
2198
+ * Unwrap response, returning the field
2199
+ * @param {string} field Colon seperated path: `rows:0`
2200
+ * @return {Slice<T>}
2201
+ */
2202
+ pop(field) {
2203
+ this.popField = field;
2204
+ return this;
2205
+ }
2206
+ /**
2207
+ * Unwrap response returning the first row
2208
+ * @return {Slice<T>}
2209
+ */
2210
+ row() {
2211
+ return this.pop("rows:0");
2212
+ }
2213
+ /**
2214
+ * Unwrap response returning the rows
2215
+ * @return {Slice<T>}
2216
+ */
2217
+ rows() {
2218
+ return this.pop("rows");
2219
+ }
2298
2220
  /**
2299
2221
  * Set the request type to select
2300
2222
  * @example
@@ -2303,6 +2225,7 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
2303
2225
  * const row: T = new Slice<T>(12345).select(id).exec().row();
2304
2226
  * ```
2305
2227
  * @param {number | number[]} id ID(s) to select, leaving blank will return all rows
2228
+ * @return {Slice<T>}
2306
2229
  */
2307
2230
  select(id) {
2308
2231
  this.operation = "$/slice/report";
@@ -2324,10 +2247,10 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
2324
2247
  */
2325
2248
  sync(on = true) {
2326
2249
  if (on) {
2327
- new _Slice(this.slice, this.api).select().exec().rows().then((rows) => this.cache = rows);
2250
+ new _Slice(this.slice, this.api).select().rows().exec().then((rows) => this.cache = rows);
2328
2251
  if (!this.unsubscribe) this.unsubscribe = this.api.socket.sliceEvents(this.slice, (event) => {
2329
2252
  const ids = [...event.data.new, ...event.data.changed];
2330
- new _Slice(this.slice, this.api).select(ids).exec().rows().then((rows) => this.cache = [...this.cache.filter((c) => c.id != null && !ids.includes(c.id)), ...rows]);
2253
+ new _Slice(this.slice, this.api).select(ids).rows().exec().then((rows) => this.cache = [...this.cache.filter((c) => c.id != null && !ids.includes(c.id)), ...rows]);
2331
2254
  this.cache = this.cache.filter((v) => v.id && !event.data.lost.includes(v.id));
2332
2255
  });
2333
2256
  return this.cache$;
@@ -2346,6 +2269,7 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
2346
2269
  * ]).exec().keys();
2347
2270
  * ```
2348
2271
  * @param {T | T[]} rows Rows to be updated, each row must have an ID
2272
+ * @return {Slice<T>}
2349
2273
  */
2350
2274
  update(rows) {
2351
2275
  this.operation = "$/slice/xupdate";
@@ -2368,6 +2292,7 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
2368
2292
  * @param {string | object} field property to compare or a map of equality comparisons
2369
2293
  * @param {string} operator Operation to compare with. Accepts JS operators (>=, ==, !=, ...) as well as datalynk styax ($gte, $eq, $is, $not, ...)
2370
2294
  * @param {any} value value to compare against
2295
+ * @return {Slice<T>}
2371
2296
  */
2372
2297
  where(field, operator, value) {
2373
2298
  if (this.request.where && this.request.where[0] != "$or") this.and();
@@ -2406,6 +2331,7 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
2406
2331
  class Socket {
2407
2332
  constructor(api, options = {}) {
2408
2333
  __publicField(this, "listeners", []);
2334
+ // [ Callback, Re-subscribe ]
2409
2335
  __publicField(this, "retry");
2410
2336
  __publicField(this, "socket");
2411
2337
  __publicField(this, "open", false);
@@ -2426,9 +2352,9 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
2426
2352
  * @param {SocketListener} fn Callback function
2427
2353
  * @return {Unsubscribe} Function to unsubscribe callback
2428
2354
  */
2429
- addListener(fn) {
2430
- this.listeners.push(fn);
2431
- return () => this.listeners = this.listeners.filter((l) => l != fn);
2355
+ addListener(fn, reconnect) {
2356
+ this.listeners.push([fn, reconnect]);
2357
+ return () => this.listeners = this.listeners.filter((l) => l[0] != fn);
2432
2358
  }
2433
2359
  /**
2434
2360
  * Close socket connection
@@ -2466,11 +2392,12 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
2466
2392
  if (payload.connected) {
2467
2393
  this.open = true;
2468
2394
  console.debug("Datalynk socket: connected");
2395
+ this.listeners.forEach((l) => l[1]());
2469
2396
  } else {
2470
2397
  throw new Error(`Datalynk socket failed: ${payload.error}`);
2471
2398
  }
2472
2399
  } else {
2473
- this.listeners.forEach((l) => l(payload));
2400
+ this.listeners.forEach((l) => l[0](payload));
2474
2401
  }
2475
2402
  };
2476
2403
  }
@@ -2493,15 +2420,12 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
2493
2420
  * @return {Unsubscribe} Run returned function to unsubscribe callback
2494
2421
  */
2495
2422
  sliceEvents(slice, callback) {
2496
- let cancelled = false;
2497
- sleepWhile(() => !this.open).then(() => {
2498
- if (!cancelled) this.send({ onSliceEvents: slice });
2499
- });
2423
+ const listen = () => this.send({ onSliceEvents: slice });
2424
+ if (this.open) listen();
2500
2425
  const unsubscribe = this.addListener((event) => {
2501
2426
  if (event.type == "sliceEvents" && event.data.slice == slice) callback(event);
2502
- });
2427
+ }, () => listen());
2503
2428
  return () => {
2504
- cancelled = true;
2505
2429
  this.send({ offSliceEvents: slice });
2506
2430
  unsubscribe();
2507
2431
  };
@@ -2556,9 +2480,8 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
2556
2480
  __publicField(this, "bundleOngoing", false);
2557
2481
  /** LocalStorage key for persisting logins */
2558
2482
  __publicField(this, "localStorageKey", "datalynk-token");
2559
- /** Pending requests */
2483
+ /** Pending requests cache */
2560
2484
  __publicField(this, "pending", {});
2561
- // Cache for ongoing requests
2562
2485
  /** Authentication helpers */
2563
2486
  __publicField(this, "auth", new Auth(this));
2564
2487
  /** File helpers */
@@ -2569,9 +2492,8 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
2569
2492
  __publicField(this, "socket");
2570
2493
  /** Superuser helpers */
2571
2494
  __publicField(this, "superuser", new Superuser(this));
2572
- /** API endpoint */
2495
+ /** API URL endpoint */
2573
2496
  __publicField(this, "url");
2574
- // API URL endpoint for requests
2575
2497
  /** API Session token */
2576
2498
  __publicField(this, "token$", new BehaviorSubject(null));
2577
2499
  this.options = options;
@@ -2651,10 +2573,21 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
2651
2573
  /**
2652
2574
  * Chain multiple requests to execute together
2653
2575
  * @param {Slice<any>} requests List of requests to chain
2654
- * @return {Promise<SlicePromise[]>} API Response
2576
+ * @return {Promise<any>} API Response
2655
2577
  */
2656
2578
  chain(...requests) {
2657
- return this.request({ "$/tools/action_chain": requests.flatMap((r) => r instanceof Slice ? r.raw : r) });
2579
+ const arr = requests.length == 1 && Array.isArray(requests[0]) ? requests[0] : requests;
2580
+ return this.request({ "$/tools/action_chain": arr.map((r) => {
2581
+ if (!(r instanceof Slice)) return r;
2582
+ const req = r.raw;
2583
+ Object.keys(req).forEach((key) => {
2584
+ if (key.startsWith("$/")) {
2585
+ req[key.replace("$", "!")] = req[key];
2586
+ delete req[key];
2587
+ }
2588
+ });
2589
+ return req;
2590
+ }) });
2658
2591
  }
2659
2592
  /**
2660
2593
  * Organize multiple requests into a single mapped request
@@ -2663,11 +2596,37 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
2663
2596
  */
2664
2597
  chainMap(request) {
2665
2598
  return this.request({ "$/tools/do": [
2666
- ...Object.entries(request).flatMap(([key, r]) => [key, r instanceof Slice ? r.raw : r]),
2599
+ ...Object.entries(request).flatMap(([key, r]) => {
2600
+ if (!(r instanceof Slice)) return [key, r];
2601
+ const req = r.raw;
2602
+ Object.keys(req).forEach((key2) => {
2603
+ if (key2.startsWith("$/")) {
2604
+ req[key2.replace("$", "!")] = req[key2];
2605
+ delete req[key2];
2606
+ }
2607
+ });
2608
+ return [key, req];
2609
+ }),
2667
2610
  "returnAllBoilerplate",
2668
2611
  { "$_": "*" }
2669
2612
  ] }, {});
2670
2613
  }
2614
+ /**
2615
+ * Exact same as `request` method, but logs the response in the console automatically
2616
+ *
2617
+ * @param {object | string} data Datalynk request as object or string
2618
+ * @param {ApiRequestOptions} options
2619
+ * @returns {Promise<any>} Datalynk response
2620
+ */
2621
+ debug(data, options = {}) {
2622
+ return this.request(data, options).then((data2) => {
2623
+ console.log(data2);
2624
+ return data2;
2625
+ }).catch((err) => {
2626
+ console.error(err);
2627
+ return err;
2628
+ });
2629
+ }
2671
2630
  /**
2672
2631
  * Send a request to Datalynk
2673
2632
  *
@@ -2682,7 +2641,7 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
2682
2641
  */
2683
2642
  request(data, options = {}) {
2684
2643
  data = typeof data == "string" ? { [data]: {} } : data;
2685
- if (options.force) {
2644
+ if (options.noOptimize) {
2686
2645
  return new Promise((res, rej) => {
2687
2646
  this._request(data, options).then((resp) => {
2688
2647
  (resp == null ? void 0 : resp.error) ? rej(resp) : res(resp);
@@ -2720,27 +2679,11 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
2720
2679
  * ```
2721
2680
  *
2722
2681
  * @param {number} slice Slice number the object will target
2723
- * @returns {Slice<T extends SliceMeta>} Object for making requests & caching rows
2682
+ * @returns {Slice<T = any>} Object for making requests & caching rows
2724
2683
  */
2725
2684
  slice(slice) {
2726
2685
  return new Slice(slice, this);
2727
2686
  }
2728
- /**
2729
- * Exact same as `request` method, but logs the response in the console automatically
2730
- *
2731
- * @param {object | string} data Datalynk request as object or string
2732
- * @param {ApiRequestOptions} options
2733
- * @returns {Promise<any>} Datalynk response
2734
- */
2735
- test(data, options = {}) {
2736
- return this.request(data, options).then((data2) => {
2737
- console.log(data2);
2738
- return data2;
2739
- }).catch((err) => {
2740
- console.error(err);
2741
- return err;
2742
- });
2743
- }
2744
2687
  }
2745
2688
  exports2.Api = Api;
2746
2689
  exports2.Auth = Auth;
@@ -2749,7 +2692,6 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
2749
2692
  exports2.Pdf = Pdf;
2750
2693
  exports2.Serializer = Serializer;
2751
2694
  exports2.Slice = Slice;
2752
- exports2.SlicePromise = SlicePromise;
2753
2695
  exports2.Socket = Socket;
2754
2696
  exports2.Superuser = Superuser;
2755
2697
  Object.defineProperty(exports2, Symbol.toStringTag, { value: "Module" });