@auxilium/datalynk-client 1.0.15 → 1.0.16

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 ADDED
@@ -0,0 +1,2754 @@
1
+ (function(global, factory) {
2
+ typeof exports === "object" && typeof module !== "undefined" ? factory(exports) : typeof define === "function" && define.amd ? define(["exports"], factory) : (global = typeof globalThis !== "undefined" ? globalThis : global || self, factory(global.utils = {}));
3
+ })(this, function(exports2) {
4
+ "use strict";var __defProp = Object.defineProperty;
5
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
6
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
7
+
8
+ var __defProp2 = Object.defineProperty;
9
+ var __defNormalProp2 = (obj, key, value2) => key in obj ? __defProp2(obj, key, { enumerable: true, configurable: true, writable: true, value: value2 }) : obj[key] = value2;
10
+ var __publicField2 = (obj, key, value2) => __defNormalProp2(obj, typeof key !== "symbol" ? key + "" : key, value2);
11
+ function clean(obj, undefinedOnly = false) {
12
+ if (obj == null) throw new Error("Cannot clean a NULL value");
13
+ if (Array.isArray(obj)) {
14
+ obj = obj.filter((o) => o != null);
15
+ } else {
16
+ Object.entries(obj).forEach(([key, value2]) => {
17
+ if (undefinedOnly && value2 === void 0 || !undefinedOnly && value2 == null) delete obj[key];
18
+ });
19
+ }
20
+ return obj;
21
+ }
22
+ function JSONAttemptParse(json) {
23
+ try {
24
+ return JSON.parse(json);
25
+ } catch {
26
+ return json;
27
+ }
28
+ }
29
+ function JSONSanitize(obj, space) {
30
+ return JSON.stringify(obj, (key, value2) => {
31
+ return value2;
32
+ }, space);
33
+ }
34
+ function blackOrWhite(background) {
35
+ const exploded = background == null ? void 0 : background.match(background.length >= 6 ? /\w\w/g : /\w/g);
36
+ if (!exploded) return "black";
37
+ const [r2, g, b2] = exploded.map((hex) => parseInt(hex, 16));
38
+ const luminance = (0.299 * r2 + 0.587 * g + 0.114 * b2) / 255;
39
+ return luminance > 0.5 ? "black" : "white";
40
+ }
41
+ class PromiseProgress extends Promise {
42
+ constructor(executor) {
43
+ super((resolve, reject) => executor(
44
+ (value2) => resolve(value2),
45
+ (reason) => reject(reason),
46
+ (progress) => this.progress = progress
47
+ ));
48
+ __publicField2(this, "listeners", []);
49
+ __publicField2(this, "_progress", 0);
50
+ }
51
+ get progress() {
52
+ return this._progress;
53
+ }
54
+ set progress(p2) {
55
+ if (p2 == this._progress) return;
56
+ this._progress = p2;
57
+ this.listeners.forEach((l) => l(p2));
58
+ }
59
+ static from(promise) {
60
+ if (promise instanceof PromiseProgress) return promise;
61
+ return new PromiseProgress((res, rej) => promise.then((...args) => res(...args)).catch((...args) => rej(...args)));
62
+ }
63
+ from(promise) {
64
+ const newPromise = PromiseProgress.from(promise);
65
+ this.onProgress((p2) => newPromise.progress = p2);
66
+ return newPromise;
67
+ }
68
+ onProgress(callback) {
69
+ this.listeners.push(callback);
70
+ return this;
71
+ }
72
+ then(res, rej) {
73
+ const resp = super.then(res, rej);
74
+ return this.from(resp);
75
+ }
76
+ catch(rej) {
77
+ return this.from(super.catch(rej));
78
+ }
79
+ finally(res) {
80
+ return this.from(super.finally(res));
81
+ }
82
+ }
83
+ function formatDate(format = "YYYY-MM-DD H:mm", date = /* @__PURE__ */ new Date(), tz) {
84
+ const timezones = [
85
+ ["IDLW", -12],
86
+ ["SST", -11],
87
+ ["HST", -10],
88
+ ["AKST", -9],
89
+ ["PST", -8],
90
+ ["MST", -7],
91
+ ["CST", -6],
92
+ ["EST", -5],
93
+ ["AST", -4],
94
+ ["BRT", -3],
95
+ ["MAT", -2],
96
+ ["AZOT", -1],
97
+ ["UTC", 0],
98
+ ["CET", 1],
99
+ ["EET", 2],
100
+ ["MSK", 3],
101
+ ["AST", 4],
102
+ ["PKT", 5],
103
+ ["IST", 5.5],
104
+ ["BST", 6],
105
+ ["ICT", 7],
106
+ ["CST", 8],
107
+ ["JST", 9],
108
+ ["AEST", 10],
109
+ ["SBT", 11],
110
+ ["FJT", 12],
111
+ ["TOT", 13],
112
+ ["LINT", 14]
113
+ ];
114
+ function adjustTz(date2, gmt) {
115
+ const currentOffset = date2.getTimezoneOffset();
116
+ const adjustedOffset = gmt * 60;
117
+ return new Date(date2.getTime() + (adjustedOffset + currentOffset) * 6e4);
118
+ }
119
+ function day(num) {
120
+ return ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"][num] || "Unknown";
121
+ }
122
+ function doy(date2) {
123
+ const start = /* @__PURE__ */ new Date(`${date2.getFullYear()}-01-01 0:00:00`);
124
+ return Math.ceil((date2.getTime() - start.getTime()) / (1e3 * 60 * 60 * 24));
125
+ }
126
+ function month(num) {
127
+ return ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"][num] || "Unknown";
128
+ }
129
+ function suffix(num) {
130
+ if (num % 100 >= 11 && num % 100 <= 13) return `${num}th`;
131
+ switch (num % 10) {
132
+ case 1:
133
+ return `${num}st`;
134
+ case 2:
135
+ return `${num}nd`;
136
+ case 3:
137
+ return `${num}rd`;
138
+ default:
139
+ return `${num}th`;
140
+ }
141
+ }
142
+ function tzOffset(offset) {
143
+ const hours = ~~(offset / 60);
144
+ const minutes = offset % 60;
145
+ return (offset > 0 ? "-" : "") + `${hours}:${minutes.toString().padStart(2, "0")}`;
146
+ }
147
+ if (typeof date == "number" || typeof date == "string") date = new Date(date);
148
+ let t;
149
+ if (tz == null) tz = -(date.getTimezoneOffset() / 60);
150
+ t = timezones.find((t2) => isNaN(tz) ? t2[0] == tz : t2[1] == tz);
151
+ if (!t) throw new Error(`Unknown timezone: ${tz}`);
152
+ date = adjustTz(date, t[1]);
153
+ const tokens = {
154
+ "YYYY": date.getFullYear().toString(),
155
+ "YY": date.getFullYear().toString().slice(2),
156
+ "MMMM": month(date.getMonth()),
157
+ "MMM": month(date.getMonth()).slice(0, 3),
158
+ "MM": (date.getMonth() + 1).toString().padStart(2, "0"),
159
+ "M": (date.getMonth() + 1).toString(),
160
+ "DDD": doy(date).toString(),
161
+ "DD": date.getDate().toString().padStart(2, "0"),
162
+ "Do": suffix(date.getDate()),
163
+ "D": date.getDate().toString(),
164
+ "dddd": day(date.getDay()),
165
+ "ddd": day(date.getDay()).slice(0, 3),
166
+ "HH": date.getHours().toString().padStart(2, "0"),
167
+ "H": date.getHours().toString(),
168
+ "hh": (date.getHours() % 12 || 12).toString().padStart(2, "0"),
169
+ "h": (date.getHours() % 12 || 12).toString(),
170
+ "mm": date.getMinutes().toString().padStart(2, "0"),
171
+ "m": date.getMinutes().toString(),
172
+ "ss": date.getSeconds().toString().padStart(2, "0"),
173
+ "s": date.getSeconds().toString(),
174
+ "SSS": date.getMilliseconds().toString().padStart(3, "0"),
175
+ "A": date.getHours() >= 12 ? "PM" : "AM",
176
+ "a": date.getHours() >= 12 ? "pm" : "am",
177
+ "ZZ": tzOffset(t[1] * 60).replace(":", ""),
178
+ "Z": tzOffset(t[1] * 60),
179
+ "z": typeof tz == "string" ? tz : t[0]
180
+ };
181
+ 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]);
182
+ }
183
+ class TypedEmitter {
184
+ constructor() {
185
+ __publicField2(this, "listeners", {});
186
+ }
187
+ static emit(event, ...args) {
188
+ (this.listeners["*"] || []).forEach((l) => l(event, ...args));
189
+ (this.listeners[event.toString()] || []).forEach((l) => l(...args));
190
+ }
191
+ static off(event, listener) {
192
+ const e = event.toString();
193
+ this.listeners[e] = (this.listeners[e] || []).filter((l) => l === listener);
194
+ }
195
+ static on(event, listener) {
196
+ var _a;
197
+ const e = event.toString();
198
+ if (!this.listeners[e]) this.listeners[e] = [];
199
+ (_a = this.listeners[e]) == null ? void 0 : _a.push(listener);
200
+ return () => this.off(event, listener);
201
+ }
202
+ static once(event, listener) {
203
+ return new Promise((res) => {
204
+ const unsubscribe = this.on(event, (...args) => {
205
+ res(args.length == 1 ? args[0] : args);
206
+ if (listener) listener(...args);
207
+ unsubscribe();
208
+ });
209
+ });
210
+ }
211
+ emit(event, ...args) {
212
+ (this.listeners["*"] || []).forEach((l) => l(event, ...args));
213
+ (this.listeners[event] || []).forEach((l) => l(...args));
214
+ }
215
+ off(event, listener) {
216
+ this.listeners[event] = (this.listeners[event] || []).filter((l) => l === listener);
217
+ }
218
+ on(event, listener) {
219
+ var _a;
220
+ if (!this.listeners[event]) this.listeners[event] = [];
221
+ (_a = this.listeners[event]) == null ? void 0 : _a.push(listener);
222
+ return () => this.off(event, listener);
223
+ }
224
+ once(event, listener) {
225
+ return new Promise((res) => {
226
+ const unsubscribe = this.on(event, (...args) => {
227
+ res(args.length == 1 ? args[0] : args);
228
+ if (listener) listener(...args);
229
+ unsubscribe();
230
+ });
231
+ });
232
+ }
233
+ }
234
+ __publicField2(TypedEmitter, "listeners", {});
235
+ class CustomError extends Error {
236
+ constructor(message, code) {
237
+ super(message);
238
+ __publicField2(this, "_code");
239
+ if (code != null) this._code = code;
240
+ }
241
+ get code() {
242
+ return this._code || this.constructor.code;
243
+ }
244
+ set code(c) {
245
+ this._code = c;
246
+ }
247
+ static from(err) {
248
+ const code = Number(err.statusCode) ?? Number(err.code);
249
+ const newErr = new this(err.message || err.toString());
250
+ return Object.assign(newErr, {
251
+ stack: err.stack,
252
+ ...err,
253
+ code: code ?? void 0
254
+ });
255
+ }
256
+ static instanceof(err) {
257
+ return err.constructor.code != void 0;
258
+ }
259
+ toString() {
260
+ return this.message || super.toString();
261
+ }
262
+ }
263
+ __publicField2(CustomError, "code", 500);
264
+ class BadRequestError extends CustomError {
265
+ constructor(message = "Bad Request") {
266
+ super(message);
267
+ }
268
+ static instanceof(err) {
269
+ return err.constructor.code == this.code;
270
+ }
271
+ }
272
+ __publicField2(BadRequestError, "code", 400);
273
+ class UnauthorizedError extends CustomError {
274
+ constructor(message = "Unauthorized") {
275
+ super(message);
276
+ }
277
+ static instanceof(err) {
278
+ return err.constructor.code == this.code;
279
+ }
280
+ }
281
+ __publicField2(UnauthorizedError, "code", 401);
282
+ class PaymentRequiredError extends CustomError {
283
+ constructor(message = "Payment Required") {
284
+ super(message);
285
+ }
286
+ static instanceof(err) {
287
+ return err.constructor.code == this.code;
288
+ }
289
+ }
290
+ __publicField2(PaymentRequiredError, "code", 402);
291
+ class ForbiddenError extends CustomError {
292
+ constructor(message = "Forbidden") {
293
+ super(message);
294
+ }
295
+ static instanceof(err) {
296
+ return err.constructor.code == this.code;
297
+ }
298
+ }
299
+ __publicField2(ForbiddenError, "code", 403);
300
+ class NotFoundError extends CustomError {
301
+ constructor(message = "Not Found") {
302
+ super(message);
303
+ }
304
+ static instanceof(err) {
305
+ return err.constructor.code == this.code;
306
+ }
307
+ }
308
+ __publicField2(NotFoundError, "code", 404);
309
+ class MethodNotAllowedError extends CustomError {
310
+ constructor(message = "Method Not Allowed") {
311
+ super(message);
312
+ }
313
+ static instanceof(err) {
314
+ return err.constructor.code == this.code;
315
+ }
316
+ }
317
+ __publicField2(MethodNotAllowedError, "code", 405);
318
+ class NotAcceptableError extends CustomError {
319
+ constructor(message = "Not Acceptable") {
320
+ super(message);
321
+ }
322
+ static instanceof(err) {
323
+ return err.constructor.code == this.code;
324
+ }
325
+ }
326
+ __publicField2(NotAcceptableError, "code", 406);
327
+ class InternalServerError extends CustomError {
328
+ constructor(message = "Internal Server Error") {
329
+ super(message);
330
+ }
331
+ static instanceof(err) {
332
+ return err.constructor.code == this.code;
333
+ }
334
+ }
335
+ __publicField2(InternalServerError, "code", 500);
336
+ class NotImplementedError extends CustomError {
337
+ constructor(message = "Not Implemented") {
338
+ super(message);
339
+ }
340
+ static instanceof(err) {
341
+ return err.constructor.code == this.code;
342
+ }
343
+ }
344
+ __publicField2(NotImplementedError, "code", 501);
345
+ class BadGatewayError extends CustomError {
346
+ constructor(message = "Bad Gateway") {
347
+ super(message);
348
+ }
349
+ static instanceof(err) {
350
+ return err.constructor.code == this.code;
351
+ }
352
+ }
353
+ __publicField2(BadGatewayError, "code", 502);
354
+ class ServiceUnavailableError extends CustomError {
355
+ constructor(message = "Service Unavailable") {
356
+ super(message);
357
+ }
358
+ static instanceof(err) {
359
+ return err.constructor.code == this.code;
360
+ }
361
+ }
362
+ __publicField2(ServiceUnavailableError, "code", 503);
363
+ class GatewayTimeoutError extends CustomError {
364
+ constructor(message = "Gateway Timeout") {
365
+ super(message);
366
+ }
367
+ static instanceof(err) {
368
+ return err.constructor.code == this.code;
369
+ }
370
+ }
371
+ __publicField2(GatewayTimeoutError, "code", 504);
372
+ function errorFromCode(code, message) {
373
+ switch (code) {
374
+ case 400:
375
+ return new BadRequestError(message);
376
+ case 401:
377
+ return new UnauthorizedError(message);
378
+ case 402:
379
+ return new PaymentRequiredError(message);
380
+ case 403:
381
+ return new ForbiddenError(message);
382
+ case 404:
383
+ return new NotFoundError(message);
384
+ case 405:
385
+ return new MethodNotAllowedError(message);
386
+ case 406:
387
+ return new NotAcceptableError(message);
388
+ case 500:
389
+ return new InternalServerError(message);
390
+ case 501:
391
+ return new NotImplementedError(message);
392
+ case 502:
393
+ return new BadGatewayError(message);
394
+ case 503:
395
+ return new ServiceUnavailableError(message);
396
+ case 504:
397
+ return new GatewayTimeoutError(message);
398
+ default:
399
+ return new CustomError(message, code);
400
+ }
401
+ }
402
+ class HttpResponse extends Response {
403
+ constructor(resp, stream) {
404
+ const body = [204, 205, 304].includes(resp.status) ? null : stream;
405
+ super(body, {
406
+ headers: resp.headers,
407
+ status: resp.status,
408
+ statusText: resp.statusText
409
+ });
410
+ __publicField2(this, "data");
411
+ __publicField2(this, "ok");
412
+ __publicField2(this, "redirected");
413
+ __publicField2(this, "type");
414
+ __publicField2(this, "url");
415
+ this.ok = resp.ok;
416
+ this.redirected = resp.redirected;
417
+ this.type = resp.type;
418
+ this.url = resp.url;
419
+ }
420
+ }
421
+ const _Http = class _Http2 {
422
+ constructor(defaults = {}) {
423
+ __publicField2(this, "interceptors", {});
424
+ __publicField2(this, "headers", {});
425
+ __publicField2(this, "url");
426
+ this.url = defaults.url ?? null;
427
+ this.headers = defaults.headers || {};
428
+ if (defaults.interceptors) {
429
+ defaults.interceptors.forEach((i) => _Http2.addInterceptor(i));
430
+ }
431
+ }
432
+ static addInterceptor(fn) {
433
+ const key = Object.keys(_Http2.interceptors).length.toString();
434
+ _Http2.interceptors[key] = fn;
435
+ return () => {
436
+ _Http2.interceptors[key] = null;
437
+ };
438
+ }
439
+ addInterceptor(fn) {
440
+ const key = Object.keys(this.interceptors).length.toString();
441
+ this.interceptors[key] = fn;
442
+ return () => {
443
+ this.interceptors[key] = null;
444
+ };
445
+ }
446
+ request(opts = {}) {
447
+ var _a;
448
+ if (!this.url && !opts.url) throw new Error("URL needs to be set");
449
+ let url = ((_a = opts.url) == null ? void 0 : _a.startsWith("http")) ? opts.url : (this.url || "") + (opts.url || "");
450
+ url = url.replaceAll(/([^:]\/)\/+/g, "$1");
451
+ if (opts.fragment) url.includes("#") ? url.replace(/#.*(\?|\n)/g, (match, arg1) => `#${opts.fragment}${arg1}`) : `${url}#${opts.fragment}`;
452
+ if (opts.query) {
453
+ const q = Array.isArray(opts.query) ? opts.query : Object.keys(opts.query).map((k) => ({ key: k, value: opts.query[k] }));
454
+ url += (url.includes("?") ? "&" : "?") + q.map((q2) => `${q2.key}=${q2.value}`).join("&");
455
+ }
456
+ const headers = clean({
457
+ "Content-Type": !opts.body ? void 0 : opts.body instanceof FormData ? "multipart/form-data" : "application/json",
458
+ ..._Http2.headers,
459
+ ...this.headers,
460
+ ...opts.headers
461
+ });
462
+ if (typeof opts.body == "object" && opts.body != null && headers["Content-Type"] == "application/json")
463
+ opts.body = JSON.stringify(opts.body);
464
+ return new PromiseProgress((res, rej, prog) => {
465
+ try {
466
+ fetch(url, {
467
+ headers,
468
+ method: opts.method || (opts.body ? "POST" : "GET"),
469
+ body: opts.body
470
+ }).then(async (resp) => {
471
+ var _a2, _b;
472
+ for (let fn of [...Object.values(_Http2.interceptors), ...Object.values(this.interceptors)]) {
473
+ await new Promise((res2) => fn(resp, () => res2()));
474
+ }
475
+ const contentLength = resp.headers.get("Content-Length");
476
+ const total = contentLength ? parseInt(contentLength, 10) : 0;
477
+ let loaded = 0;
478
+ const reader = (_a2 = resp.body) == null ? void 0 : _a2.getReader();
479
+ const stream = new ReadableStream({
480
+ start(controller) {
481
+ function push() {
482
+ reader == null ? void 0 : reader.read().then((event) => {
483
+ if (event.done) return controller.close();
484
+ loaded += event.value.byteLength;
485
+ prog(loaded / total);
486
+ controller.enqueue(event.value);
487
+ push();
488
+ }).catch((error) => controller.error(error));
489
+ }
490
+ push();
491
+ }
492
+ });
493
+ resp = new HttpResponse(resp, stream);
494
+ if (opts.decode !== false) {
495
+ const content = (_b = resp.headers.get("Content-Type")) == null ? void 0 : _b.toLowerCase();
496
+ if (content == null ? void 0 : content.includes("form")) resp.data = await resp.formData();
497
+ else if (content == null ? void 0 : content.includes("json")) resp.data = await resp.json();
498
+ else if (content == null ? void 0 : content.includes("text")) resp.data = await resp.text();
499
+ else if (content == null ? void 0 : content.includes("application")) resp.data = await resp.blob();
500
+ }
501
+ if (resp.ok) res(resp);
502
+ else rej(resp);
503
+ }).catch((err) => rej(err));
504
+ } catch (err) {
505
+ rej(err);
506
+ }
507
+ });
508
+ }
509
+ };
510
+ __publicField2(_Http, "interceptors", {});
511
+ __publicField2(_Http, "headers", {});
512
+ function jwtDecode(token) {
513
+ const base64 = token.split(".")[1].replace(/-/g, "+").replace(/_/g, "/");
514
+ return JSONAttemptParse(decodeURIComponent(atob(base64).split("").map(function(c) {
515
+ return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2);
516
+ }).join("")));
517
+ }
518
+ const CliEffects = {
519
+ CLEAR: "\x1B[0m"
520
+ };
521
+ const CliForeground = {
522
+ RED: "\x1B[31m",
523
+ YELLOW: "\x1B[33m",
524
+ BLUE: "\x1B[34m",
525
+ LIGHT_GREY: "\x1B[37m"
526
+ };
527
+ const _Logger = class _Logger2 extends TypedEmitter {
528
+ constructor(namespace) {
529
+ super();
530
+ this.namespace = namespace;
531
+ }
532
+ format(...text) {
533
+ const now = /* @__PURE__ */ new Date();
534
+ const timestamp = `${now.getFullYear()}-${now.getMonth() + 1}-${now.getDate()} ${now.getHours().toString().padStart(2, "0")}:${now.getMinutes().toString().padStart(2, "0")}:${now.getSeconds().toString().padStart(2, "0")}.${now.getMilliseconds().toString().padEnd(3, "0")}`;
535
+ return `${timestamp}${this.namespace ? ` [${this.namespace}]` : ""} ${text.map((t) => typeof t == "string" ? t : JSONSanitize(t, 2)).join(" ")}`;
536
+ }
537
+ debug(...args) {
538
+ if (_Logger2.LOG_LEVEL < 4) return;
539
+ const str = this.format(...args);
540
+ _Logger2.emit(4, str);
541
+ console.debug(CliForeground.LIGHT_GREY + str + CliEffects.CLEAR);
542
+ }
543
+ log(...args) {
544
+ if (_Logger2.LOG_LEVEL < 3) return;
545
+ const str = this.format(...args);
546
+ _Logger2.emit(3, str);
547
+ console.log(CliEffects.CLEAR + str);
548
+ }
549
+ info(...args) {
550
+ if (_Logger2.LOG_LEVEL < 2) return;
551
+ const str = this.format(...args);
552
+ _Logger2.emit(2, str);
553
+ console.info(CliForeground.BLUE + str + CliEffects.CLEAR);
554
+ }
555
+ warn(...args) {
556
+ if (_Logger2.LOG_LEVEL < 1) return;
557
+ const str = this.format(...args);
558
+ _Logger2.emit(1, str);
559
+ console.warn(CliForeground.YELLOW + str + CliEffects.CLEAR);
560
+ }
561
+ error(...args) {
562
+ if (_Logger2.LOG_LEVEL < 0) return;
563
+ const str = this.format(...args);
564
+ _Logger2.emit(0, str);
565
+ console.error(CliForeground.RED + str + CliEffects.CLEAR);
566
+ }
567
+ };
568
+ __publicField2(_Logger, "LOG_LEVEL", 4);
569
+ var extendStatics = function(d, b) {
570
+ extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
571
+ d2.__proto__ = b2;
572
+ } || function(d2, b2) {
573
+ for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p];
574
+ };
575
+ return extendStatics(d, b);
576
+ };
577
+ function __extends(d, b) {
578
+ if (typeof b !== "function" && b !== null)
579
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
580
+ extendStatics(d, b);
581
+ function __() {
582
+ this.constructor = d;
583
+ }
584
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
585
+ }
586
+ function __values(o) {
587
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
588
+ if (m) return m.call(o);
589
+ if (o && typeof o.length === "number") return {
590
+ next: function() {
591
+ if (o && i >= o.length) o = void 0;
592
+ return { value: o && o[i++], done: !o };
593
+ }
594
+ };
595
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
596
+ }
597
+ function __read(o, n) {
598
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
599
+ if (!m) return o;
600
+ var i = m.call(o), r, ar = [], e;
601
+ try {
602
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
603
+ } catch (error) {
604
+ e = { error };
605
+ } finally {
606
+ try {
607
+ if (r && !r.done && (m = i["return"])) m.call(i);
608
+ } finally {
609
+ if (e) throw e.error;
610
+ }
611
+ }
612
+ return ar;
613
+ }
614
+ function __spreadArray(to, from, pack) {
615
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
616
+ if (ar || !(i in from)) {
617
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
618
+ ar[i] = from[i];
619
+ }
620
+ }
621
+ return to.concat(ar || Array.prototype.slice.call(from));
622
+ }
623
+ typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
624
+ var e = new Error(message);
625
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
626
+ };
627
+ function isFunction(value) {
628
+ return typeof value === "function";
629
+ }
630
+ function createErrorClass(createImpl) {
631
+ var _super = function(instance) {
632
+ Error.call(instance);
633
+ instance.stack = new Error().stack;
634
+ };
635
+ var ctorFunc = createImpl(_super);
636
+ ctorFunc.prototype = Object.create(Error.prototype);
637
+ ctorFunc.prototype.constructor = ctorFunc;
638
+ return ctorFunc;
639
+ }
640
+ var UnsubscriptionError = createErrorClass(function(_super) {
641
+ return function UnsubscriptionErrorImpl(errors) {
642
+ _super(this);
643
+ this.message = errors ? errors.length + " errors occurred during unsubscription:\n" + errors.map(function(err, i) {
644
+ return i + 1 + ") " + err.toString();
645
+ }).join("\n ") : "";
646
+ this.name = "UnsubscriptionError";
647
+ this.errors = errors;
648
+ };
649
+ });
650
+ function arrRemove(arr, item) {
651
+ if (arr) {
652
+ var index = arr.indexOf(item);
653
+ 0 <= index && arr.splice(index, 1);
654
+ }
655
+ }
656
+ var Subscription = function() {
657
+ function Subscription2(initialTeardown) {
658
+ this.initialTeardown = initialTeardown;
659
+ this.closed = false;
660
+ this._parentage = null;
661
+ this._finalizers = null;
662
+ }
663
+ Subscription2.prototype.unsubscribe = function() {
664
+ var e_1, _a, e_2, _b;
665
+ var errors;
666
+ if (!this.closed) {
667
+ this.closed = true;
668
+ var _parentage = this._parentage;
669
+ if (_parentage) {
670
+ this._parentage = null;
671
+ if (Array.isArray(_parentage)) {
672
+ try {
673
+ for (var _parentage_1 = __values(_parentage), _parentage_1_1 = _parentage_1.next(); !_parentage_1_1.done; _parentage_1_1 = _parentage_1.next()) {
674
+ var parent_1 = _parentage_1_1.value;
675
+ parent_1.remove(this);
676
+ }
677
+ } catch (e_1_1) {
678
+ e_1 = { error: e_1_1 };
679
+ } finally {
680
+ try {
681
+ if (_parentage_1_1 && !_parentage_1_1.done && (_a = _parentage_1.return)) _a.call(_parentage_1);
682
+ } finally {
683
+ if (e_1) throw e_1.error;
684
+ }
685
+ }
686
+ } else {
687
+ _parentage.remove(this);
688
+ }
689
+ }
690
+ var initialFinalizer = this.initialTeardown;
691
+ if (isFunction(initialFinalizer)) {
692
+ try {
693
+ initialFinalizer();
694
+ } catch (e) {
695
+ errors = e instanceof UnsubscriptionError ? e.errors : [e];
696
+ }
697
+ }
698
+ var _finalizers = this._finalizers;
699
+ if (_finalizers) {
700
+ this._finalizers = null;
701
+ try {
702
+ for (var _finalizers_1 = __values(_finalizers), _finalizers_1_1 = _finalizers_1.next(); !_finalizers_1_1.done; _finalizers_1_1 = _finalizers_1.next()) {
703
+ var finalizer = _finalizers_1_1.value;
704
+ try {
705
+ execFinalizer(finalizer);
706
+ } catch (err) {
707
+ errors = errors !== null && errors !== void 0 ? errors : [];
708
+ if (err instanceof UnsubscriptionError) {
709
+ errors = __spreadArray(__spreadArray([], __read(errors)), __read(err.errors));
710
+ } else {
711
+ errors.push(err);
712
+ }
713
+ }
714
+ }
715
+ } catch (e_2_1) {
716
+ e_2 = { error: e_2_1 };
717
+ } finally {
718
+ try {
719
+ if (_finalizers_1_1 && !_finalizers_1_1.done && (_b = _finalizers_1.return)) _b.call(_finalizers_1);
720
+ } finally {
721
+ if (e_2) throw e_2.error;
722
+ }
723
+ }
724
+ }
725
+ if (errors) {
726
+ throw new UnsubscriptionError(errors);
727
+ }
728
+ }
729
+ };
730
+ Subscription2.prototype.add = function(teardown) {
731
+ var _a;
732
+ if (teardown && teardown !== this) {
733
+ if (this.closed) {
734
+ execFinalizer(teardown);
735
+ } else {
736
+ if (teardown instanceof Subscription2) {
737
+ if (teardown.closed || teardown._hasParent(this)) {
738
+ return;
739
+ }
740
+ teardown._addParent(this);
741
+ }
742
+ (this._finalizers = (_a = this._finalizers) !== null && _a !== void 0 ? _a : []).push(teardown);
743
+ }
744
+ }
745
+ };
746
+ Subscription2.prototype._hasParent = function(parent) {
747
+ var _parentage = this._parentage;
748
+ return _parentage === parent || Array.isArray(_parentage) && _parentage.includes(parent);
749
+ };
750
+ Subscription2.prototype._addParent = function(parent) {
751
+ var _parentage = this._parentage;
752
+ this._parentage = Array.isArray(_parentage) ? (_parentage.push(parent), _parentage) : _parentage ? [_parentage, parent] : parent;
753
+ };
754
+ Subscription2.prototype._removeParent = function(parent) {
755
+ var _parentage = this._parentage;
756
+ if (_parentage === parent) {
757
+ this._parentage = null;
758
+ } else if (Array.isArray(_parentage)) {
759
+ arrRemove(_parentage, parent);
760
+ }
761
+ };
762
+ Subscription2.prototype.remove = function(teardown) {
763
+ var _finalizers = this._finalizers;
764
+ _finalizers && arrRemove(_finalizers, teardown);
765
+ if (teardown instanceof Subscription2) {
766
+ teardown._removeParent(this);
767
+ }
768
+ };
769
+ Subscription2.EMPTY = function() {
770
+ var empty = new Subscription2();
771
+ empty.closed = true;
772
+ return empty;
773
+ }();
774
+ return Subscription2;
775
+ }();
776
+ var EMPTY_SUBSCRIPTION = Subscription.EMPTY;
777
+ function isSubscription(value) {
778
+ return value instanceof Subscription || value && "closed" in value && isFunction(value.remove) && isFunction(value.add) && isFunction(value.unsubscribe);
779
+ }
780
+ function execFinalizer(finalizer) {
781
+ if (isFunction(finalizer)) {
782
+ finalizer();
783
+ } else {
784
+ finalizer.unsubscribe();
785
+ }
786
+ }
787
+ var config = {
788
+ Promise: void 0
789
+ };
790
+ var timeoutProvider = {
791
+ setTimeout: function(handler, timeout) {
792
+ var args = [];
793
+ for (var _i = 2; _i < arguments.length; _i++) {
794
+ args[_i - 2] = arguments[_i];
795
+ }
796
+ return setTimeout.apply(void 0, __spreadArray([handler, timeout], __read(args)));
797
+ },
798
+ clearTimeout: function(handle) {
799
+ return clearTimeout(handle);
800
+ },
801
+ delegate: void 0
802
+ };
803
+ function reportUnhandledError(err) {
804
+ timeoutProvider.setTimeout(function() {
805
+ {
806
+ throw err;
807
+ }
808
+ });
809
+ }
810
+ function noop() {
811
+ }
812
+ function errorContext(cb) {
813
+ {
814
+ cb();
815
+ }
816
+ }
817
+ var Subscriber = function(_super) {
818
+ __extends(Subscriber2, _super);
819
+ function Subscriber2(destination) {
820
+ var _this = _super.call(this) || this;
821
+ _this.isStopped = false;
822
+ if (destination) {
823
+ _this.destination = destination;
824
+ if (isSubscription(destination)) {
825
+ destination.add(_this);
826
+ }
827
+ } else {
828
+ _this.destination = EMPTY_OBSERVER;
829
+ }
830
+ return _this;
831
+ }
832
+ Subscriber2.create = function(next, error, complete) {
833
+ return new SafeSubscriber(next, error, complete);
834
+ };
835
+ Subscriber2.prototype.next = function(value) {
836
+ if (this.isStopped) ;
837
+ else {
838
+ this._next(value);
839
+ }
840
+ };
841
+ Subscriber2.prototype.error = function(err) {
842
+ if (this.isStopped) ;
843
+ else {
844
+ this.isStopped = true;
845
+ this._error(err);
846
+ }
847
+ };
848
+ Subscriber2.prototype.complete = function() {
849
+ if (this.isStopped) ;
850
+ else {
851
+ this.isStopped = true;
852
+ this._complete();
853
+ }
854
+ };
855
+ Subscriber2.prototype.unsubscribe = function() {
856
+ if (!this.closed) {
857
+ this.isStopped = true;
858
+ _super.prototype.unsubscribe.call(this);
859
+ this.destination = null;
860
+ }
861
+ };
862
+ Subscriber2.prototype._next = function(value) {
863
+ this.destination.next(value);
864
+ };
865
+ Subscriber2.prototype._error = function(err) {
866
+ try {
867
+ this.destination.error(err);
868
+ } finally {
869
+ this.unsubscribe();
870
+ }
871
+ };
872
+ Subscriber2.prototype._complete = function() {
873
+ try {
874
+ this.destination.complete();
875
+ } finally {
876
+ this.unsubscribe();
877
+ }
878
+ };
879
+ return Subscriber2;
880
+ }(Subscription);
881
+ var ConsumerObserver = function() {
882
+ function ConsumerObserver2(partialObserver) {
883
+ this.partialObserver = partialObserver;
884
+ }
885
+ ConsumerObserver2.prototype.next = function(value) {
886
+ var partialObserver = this.partialObserver;
887
+ if (partialObserver.next) {
888
+ try {
889
+ partialObserver.next(value);
890
+ } catch (error) {
891
+ handleUnhandledError(error);
892
+ }
893
+ }
894
+ };
895
+ ConsumerObserver2.prototype.error = function(err) {
896
+ var partialObserver = this.partialObserver;
897
+ if (partialObserver.error) {
898
+ try {
899
+ partialObserver.error(err);
900
+ } catch (error) {
901
+ handleUnhandledError(error);
902
+ }
903
+ } else {
904
+ handleUnhandledError(err);
905
+ }
906
+ };
907
+ ConsumerObserver2.prototype.complete = function() {
908
+ var partialObserver = this.partialObserver;
909
+ if (partialObserver.complete) {
910
+ try {
911
+ partialObserver.complete();
912
+ } catch (error) {
913
+ handleUnhandledError(error);
914
+ }
915
+ }
916
+ };
917
+ return ConsumerObserver2;
918
+ }();
919
+ var SafeSubscriber = function(_super) {
920
+ __extends(SafeSubscriber2, _super);
921
+ function SafeSubscriber2(observerOrNext, error, complete) {
922
+ var _this = _super.call(this) || this;
923
+ var partialObserver;
924
+ if (isFunction(observerOrNext) || !observerOrNext) {
925
+ partialObserver = {
926
+ next: observerOrNext !== null && observerOrNext !== void 0 ? observerOrNext : void 0,
927
+ error: error !== null && error !== void 0 ? error : void 0,
928
+ complete: complete !== null && complete !== void 0 ? complete : void 0
929
+ };
930
+ } else {
931
+ {
932
+ partialObserver = observerOrNext;
933
+ }
934
+ }
935
+ _this.destination = new ConsumerObserver(partialObserver);
936
+ return _this;
937
+ }
938
+ return SafeSubscriber2;
939
+ }(Subscriber);
940
+ function handleUnhandledError(error) {
941
+ {
942
+ reportUnhandledError(error);
943
+ }
944
+ }
945
+ function defaultErrorHandler(err) {
946
+ throw err;
947
+ }
948
+ var EMPTY_OBSERVER = {
949
+ closed: true,
950
+ next: noop,
951
+ error: defaultErrorHandler,
952
+ complete: noop
953
+ };
954
+ var observable = function() {
955
+ return typeof Symbol === "function" && Symbol.observable || "@@observable";
956
+ }();
957
+ function identity(x) {
958
+ return x;
959
+ }
960
+ function pipeFromArray(fns) {
961
+ if (fns.length === 0) {
962
+ return identity;
963
+ }
964
+ if (fns.length === 1) {
965
+ return fns[0];
966
+ }
967
+ return function piped(input) {
968
+ return fns.reduce(function(prev, fn) {
969
+ return fn(prev);
970
+ }, input);
971
+ };
972
+ }
973
+ var Observable = function() {
974
+ function Observable2(subscribe) {
975
+ if (subscribe) {
976
+ this._subscribe = subscribe;
977
+ }
978
+ }
979
+ Observable2.prototype.lift = function(operator) {
980
+ var observable2 = new Observable2();
981
+ observable2.source = this;
982
+ observable2.operator = operator;
983
+ return observable2;
984
+ };
985
+ Observable2.prototype.subscribe = function(observerOrNext, error, complete) {
986
+ var _this = this;
987
+ var subscriber = isSubscriber(observerOrNext) ? observerOrNext : new SafeSubscriber(observerOrNext, error, complete);
988
+ errorContext(function() {
989
+ var _a = _this, operator = _a.operator, source = _a.source;
990
+ subscriber.add(operator ? operator.call(subscriber, source) : source ? _this._subscribe(subscriber) : _this._trySubscribe(subscriber));
991
+ });
992
+ return subscriber;
993
+ };
994
+ Observable2.prototype._trySubscribe = function(sink) {
995
+ try {
996
+ return this._subscribe(sink);
997
+ } catch (err) {
998
+ sink.error(err);
999
+ }
1000
+ };
1001
+ Observable2.prototype.forEach = function(next, promiseCtor) {
1002
+ var _this = this;
1003
+ promiseCtor = getPromiseCtor(promiseCtor);
1004
+ return new promiseCtor(function(resolve, reject) {
1005
+ var subscriber = new SafeSubscriber({
1006
+ next: function(value) {
1007
+ try {
1008
+ next(value);
1009
+ } catch (err) {
1010
+ reject(err);
1011
+ subscriber.unsubscribe();
1012
+ }
1013
+ },
1014
+ error: reject,
1015
+ complete: resolve
1016
+ });
1017
+ _this.subscribe(subscriber);
1018
+ });
1019
+ };
1020
+ Observable2.prototype._subscribe = function(subscriber) {
1021
+ var _a;
1022
+ return (_a = this.source) === null || _a === void 0 ? void 0 : _a.subscribe(subscriber);
1023
+ };
1024
+ Observable2.prototype[observable] = function() {
1025
+ return this;
1026
+ };
1027
+ Observable2.prototype.pipe = function() {
1028
+ var operations = [];
1029
+ for (var _i = 0; _i < arguments.length; _i++) {
1030
+ operations[_i] = arguments[_i];
1031
+ }
1032
+ return pipeFromArray(operations)(this);
1033
+ };
1034
+ Observable2.prototype.toPromise = function(promiseCtor) {
1035
+ var _this = this;
1036
+ promiseCtor = getPromiseCtor(promiseCtor);
1037
+ return new promiseCtor(function(resolve, reject) {
1038
+ var value;
1039
+ _this.subscribe(function(x) {
1040
+ return value = x;
1041
+ }, function(err) {
1042
+ return reject(err);
1043
+ }, function() {
1044
+ return resolve(value);
1045
+ });
1046
+ });
1047
+ };
1048
+ Observable2.create = function(subscribe) {
1049
+ return new Observable2(subscribe);
1050
+ };
1051
+ return Observable2;
1052
+ }();
1053
+ function getPromiseCtor(promiseCtor) {
1054
+ var _a;
1055
+ return (_a = promiseCtor !== null && promiseCtor !== void 0 ? promiseCtor : config.Promise) !== null && _a !== void 0 ? _a : Promise;
1056
+ }
1057
+ function isObserver(value) {
1058
+ return value && isFunction(value.next) && isFunction(value.error) && isFunction(value.complete);
1059
+ }
1060
+ function isSubscriber(value) {
1061
+ return value && value instanceof Subscriber || isObserver(value) && isSubscription(value);
1062
+ }
1063
+ function hasLift(source) {
1064
+ return isFunction(source === null || source === void 0 ? void 0 : source.lift);
1065
+ }
1066
+ function operate(init) {
1067
+ return function(source) {
1068
+ if (hasLift(source)) {
1069
+ return source.lift(function(liftedSource) {
1070
+ try {
1071
+ return init(liftedSource, this);
1072
+ } catch (err) {
1073
+ this.error(err);
1074
+ }
1075
+ });
1076
+ }
1077
+ throw new TypeError("Unable to lift unknown Observable type");
1078
+ };
1079
+ }
1080
+ function createOperatorSubscriber(destination, onNext, onComplete, onError, onFinalize) {
1081
+ return new OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize);
1082
+ }
1083
+ var OperatorSubscriber = function(_super) {
1084
+ __extends(OperatorSubscriber2, _super);
1085
+ function OperatorSubscriber2(destination, onNext, onComplete, onError, onFinalize, shouldUnsubscribe) {
1086
+ var _this = _super.call(this, destination) || this;
1087
+ _this.onFinalize = onFinalize;
1088
+ _this.shouldUnsubscribe = shouldUnsubscribe;
1089
+ _this._next = onNext ? function(value) {
1090
+ try {
1091
+ onNext(value);
1092
+ } catch (err) {
1093
+ destination.error(err);
1094
+ }
1095
+ } : _super.prototype._next;
1096
+ _this._error = onError ? function(err) {
1097
+ try {
1098
+ onError(err);
1099
+ } catch (err2) {
1100
+ destination.error(err2);
1101
+ } finally {
1102
+ this.unsubscribe();
1103
+ }
1104
+ } : _super.prototype._error;
1105
+ _this._complete = onComplete ? function() {
1106
+ try {
1107
+ onComplete();
1108
+ } catch (err) {
1109
+ destination.error(err);
1110
+ } finally {
1111
+ this.unsubscribe();
1112
+ }
1113
+ } : _super.prototype._complete;
1114
+ return _this;
1115
+ }
1116
+ OperatorSubscriber2.prototype.unsubscribe = function() {
1117
+ var _a;
1118
+ if (!this.shouldUnsubscribe || this.shouldUnsubscribe()) {
1119
+ var closed_1 = this.closed;
1120
+ _super.prototype.unsubscribe.call(this);
1121
+ !closed_1 && ((_a = this.onFinalize) === null || _a === void 0 ? void 0 : _a.call(this));
1122
+ }
1123
+ };
1124
+ return OperatorSubscriber2;
1125
+ }(Subscriber);
1126
+ var ObjectUnsubscribedError = createErrorClass(function(_super) {
1127
+ return function ObjectUnsubscribedErrorImpl() {
1128
+ _super(this);
1129
+ this.name = "ObjectUnsubscribedError";
1130
+ this.message = "object unsubscribed";
1131
+ };
1132
+ });
1133
+ var Subject = function(_super) {
1134
+ __extends(Subject2, _super);
1135
+ function Subject2() {
1136
+ var _this = _super.call(this) || this;
1137
+ _this.closed = false;
1138
+ _this.currentObservers = null;
1139
+ _this.observers = [];
1140
+ _this.isStopped = false;
1141
+ _this.hasError = false;
1142
+ _this.thrownError = null;
1143
+ return _this;
1144
+ }
1145
+ Subject2.prototype.lift = function(operator) {
1146
+ var subject = new AnonymousSubject(this, this);
1147
+ subject.operator = operator;
1148
+ return subject;
1149
+ };
1150
+ Subject2.prototype._throwIfClosed = function() {
1151
+ if (this.closed) {
1152
+ throw new ObjectUnsubscribedError();
1153
+ }
1154
+ };
1155
+ Subject2.prototype.next = function(value) {
1156
+ var _this = this;
1157
+ errorContext(function() {
1158
+ var e_1, _a;
1159
+ _this._throwIfClosed();
1160
+ if (!_this.isStopped) {
1161
+ if (!_this.currentObservers) {
1162
+ _this.currentObservers = Array.from(_this.observers);
1163
+ }
1164
+ try {
1165
+ for (var _b = __values(_this.currentObservers), _c = _b.next(); !_c.done; _c = _b.next()) {
1166
+ var observer = _c.value;
1167
+ observer.next(value);
1168
+ }
1169
+ } catch (e_1_1) {
1170
+ e_1 = { error: e_1_1 };
1171
+ } finally {
1172
+ try {
1173
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
1174
+ } finally {
1175
+ if (e_1) throw e_1.error;
1176
+ }
1177
+ }
1178
+ }
1179
+ });
1180
+ };
1181
+ Subject2.prototype.error = function(err) {
1182
+ var _this = this;
1183
+ errorContext(function() {
1184
+ _this._throwIfClosed();
1185
+ if (!_this.isStopped) {
1186
+ _this.hasError = _this.isStopped = true;
1187
+ _this.thrownError = err;
1188
+ var observers = _this.observers;
1189
+ while (observers.length) {
1190
+ observers.shift().error(err);
1191
+ }
1192
+ }
1193
+ });
1194
+ };
1195
+ Subject2.prototype.complete = function() {
1196
+ var _this = this;
1197
+ errorContext(function() {
1198
+ _this._throwIfClosed();
1199
+ if (!_this.isStopped) {
1200
+ _this.isStopped = true;
1201
+ var observers = _this.observers;
1202
+ while (observers.length) {
1203
+ observers.shift().complete();
1204
+ }
1205
+ }
1206
+ });
1207
+ };
1208
+ Subject2.prototype.unsubscribe = function() {
1209
+ this.isStopped = this.closed = true;
1210
+ this.observers = this.currentObservers = null;
1211
+ };
1212
+ Object.defineProperty(Subject2.prototype, "observed", {
1213
+ get: function() {
1214
+ var _a;
1215
+ return ((_a = this.observers) === null || _a === void 0 ? void 0 : _a.length) > 0;
1216
+ },
1217
+ enumerable: false,
1218
+ configurable: true
1219
+ });
1220
+ Subject2.prototype._trySubscribe = function(subscriber) {
1221
+ this._throwIfClosed();
1222
+ return _super.prototype._trySubscribe.call(this, subscriber);
1223
+ };
1224
+ Subject2.prototype._subscribe = function(subscriber) {
1225
+ this._throwIfClosed();
1226
+ this._checkFinalizedStatuses(subscriber);
1227
+ return this._innerSubscribe(subscriber);
1228
+ };
1229
+ Subject2.prototype._innerSubscribe = function(subscriber) {
1230
+ var _this = this;
1231
+ var _a = this, hasError = _a.hasError, isStopped = _a.isStopped, observers = _a.observers;
1232
+ if (hasError || isStopped) {
1233
+ return EMPTY_SUBSCRIPTION;
1234
+ }
1235
+ this.currentObservers = null;
1236
+ observers.push(subscriber);
1237
+ return new Subscription(function() {
1238
+ _this.currentObservers = null;
1239
+ arrRemove(observers, subscriber);
1240
+ });
1241
+ };
1242
+ Subject2.prototype._checkFinalizedStatuses = function(subscriber) {
1243
+ var _a = this, hasError = _a.hasError, thrownError = _a.thrownError, isStopped = _a.isStopped;
1244
+ if (hasError) {
1245
+ subscriber.error(thrownError);
1246
+ } else if (isStopped) {
1247
+ subscriber.complete();
1248
+ }
1249
+ };
1250
+ Subject2.prototype.asObservable = function() {
1251
+ var observable2 = new Observable();
1252
+ observable2.source = this;
1253
+ return observable2;
1254
+ };
1255
+ Subject2.create = function(destination, source) {
1256
+ return new AnonymousSubject(destination, source);
1257
+ };
1258
+ return Subject2;
1259
+ }(Observable);
1260
+ var AnonymousSubject = function(_super) {
1261
+ __extends(AnonymousSubject2, _super);
1262
+ function AnonymousSubject2(destination, source) {
1263
+ var _this = _super.call(this) || this;
1264
+ _this.destination = destination;
1265
+ _this.source = source;
1266
+ return _this;
1267
+ }
1268
+ AnonymousSubject2.prototype.next = function(value) {
1269
+ var _a, _b;
1270
+ (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.next) === null || _b === void 0 ? void 0 : _b.call(_a, value);
1271
+ };
1272
+ AnonymousSubject2.prototype.error = function(err) {
1273
+ var _a, _b;
1274
+ (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.error) === null || _b === void 0 ? void 0 : _b.call(_a, err);
1275
+ };
1276
+ AnonymousSubject2.prototype.complete = function() {
1277
+ var _a, _b;
1278
+ (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.complete) === null || _b === void 0 ? void 0 : _b.call(_a);
1279
+ };
1280
+ AnonymousSubject2.prototype._subscribe = function(subscriber) {
1281
+ var _a, _b;
1282
+ return (_b = (_a = this.source) === null || _a === void 0 ? void 0 : _a.subscribe(subscriber)) !== null && _b !== void 0 ? _b : EMPTY_SUBSCRIPTION;
1283
+ };
1284
+ return AnonymousSubject2;
1285
+ }(Subject);
1286
+ var BehaviorSubject = function(_super) {
1287
+ __extends(BehaviorSubject2, _super);
1288
+ function BehaviorSubject2(_value) {
1289
+ var _this = _super.call(this) || this;
1290
+ _this._value = _value;
1291
+ return _this;
1292
+ }
1293
+ Object.defineProperty(BehaviorSubject2.prototype, "value", {
1294
+ get: function() {
1295
+ return this.getValue();
1296
+ },
1297
+ enumerable: false,
1298
+ configurable: true
1299
+ });
1300
+ BehaviorSubject2.prototype._subscribe = function(subscriber) {
1301
+ var subscription = _super.prototype._subscribe.call(this, subscriber);
1302
+ !subscription.closed && subscriber.next(this._value);
1303
+ return subscription;
1304
+ };
1305
+ BehaviorSubject2.prototype.getValue = function() {
1306
+ var _a = this, hasError = _a.hasError, thrownError = _a.thrownError, _value = _a._value;
1307
+ if (hasError) {
1308
+ throw thrownError;
1309
+ }
1310
+ this._throwIfClosed();
1311
+ return _value;
1312
+ };
1313
+ BehaviorSubject2.prototype.next = function(value) {
1314
+ _super.prototype.next.call(this, this._value = value);
1315
+ };
1316
+ return BehaviorSubject2;
1317
+ }(Subject);
1318
+ function filter(predicate, thisArg) {
1319
+ return operate(function(source, subscriber) {
1320
+ var index = 0;
1321
+ source.subscribe(createOperatorSubscriber(subscriber, function(value) {
1322
+ return predicate.call(thisArg, value, index++) && subscriber.next(value);
1323
+ }));
1324
+ });
1325
+ }
1326
+ function distinctUntilChanged(comparator, keySelector) {
1327
+ if (keySelector === void 0) {
1328
+ keySelector = identity;
1329
+ }
1330
+ comparator = comparator !== null && comparator !== void 0 ? comparator : defaultCompare;
1331
+ return operate(function(source, subscriber) {
1332
+ var previousKey;
1333
+ var first = true;
1334
+ source.subscribe(createOperatorSubscriber(subscriber, function(value) {
1335
+ var currentKey = keySelector(value);
1336
+ if (first || !comparator(previousKey, currentKey)) {
1337
+ first = false;
1338
+ previousKey = currentKey;
1339
+ subscriber.next(value);
1340
+ }
1341
+ }));
1342
+ });
1343
+ }
1344
+ function defaultCompare(a, b) {
1345
+ return a === b;
1346
+ }
1347
+ const _LoginPrompt = class _LoginPrompt {
1348
+ constructor(api, spoke, options = {}) {
1349
+ __publicField(this, "alert");
1350
+ __publicField(this, "button");
1351
+ __publicField(this, "form");
1352
+ __publicField(this, "password");
1353
+ __publicField(this, "persist");
1354
+ __publicField(this, "username");
1355
+ __publicField(this, "options");
1356
+ __publicField(this, "_done");
1357
+ /** Promise which resolves once login is complete */
1358
+ __publicField(this, "done", new Promise((res) => {
1359
+ this._done = res;
1360
+ }));
1361
+ this.api = api;
1362
+ this.spoke = spoke;
1363
+ this.options = {
1364
+ title: this.spoke,
1365
+ background: "#ffffff",
1366
+ color: "#c83232",
1367
+ textColor: "#000000",
1368
+ ...clean(options, true)
1369
+ };
1370
+ this.close();
1371
+ document.head.innerHTML += _LoginPrompt.css(this.options);
1372
+ const div = document.createElement("div");
1373
+ div.innerHTML = _LoginPrompt.template(this.options);
1374
+ document.body.appendChild(div);
1375
+ this.alert = document.querySelector("#datalynk-login-alert");
1376
+ this.button = document.querySelector("#datalynk-login-form button");
1377
+ this.form = document.querySelector("#datalynk-login-form");
1378
+ this.password = document.querySelector('#datalynk-login-form input[name="password"]');
1379
+ this.persist = document.querySelector('#datalynk-login-form input[name="persist"]');
1380
+ this.username = document.querySelector('#datalynk-login-form input[name="username"]');
1381
+ if (options.persist === false) this.persist.parentElement.remove();
1382
+ this.form.onsubmit = (event) => this.login(event);
1383
+ }
1384
+ /** Close the login prompt */
1385
+ close() {
1386
+ var _a, _b;
1387
+ (_a = document.querySelector("#datalynk-login-css")) == null ? void 0 : _a.remove();
1388
+ (_b = document.querySelector("#datalynk-login")) == null ? void 0 : _b.remove();
1389
+ }
1390
+ /** Check if login prompt is still open */
1391
+ isOpen() {
1392
+ return !!document.querySelector("#datalynk-login");
1393
+ }
1394
+ /** Login form submit event */
1395
+ login(event) {
1396
+ event.preventDefault();
1397
+ const data = new FormData(event.target);
1398
+ this.alert.classList.add("hidden");
1399
+ this.username.disabled = true;
1400
+ this.password.disabled = true;
1401
+ this.persist.disabled = true;
1402
+ this.button.disabled = true;
1403
+ return this.api.auth.login(
1404
+ this.spoke,
1405
+ data.get("username"),
1406
+ data.get("password"),
1407
+ { expire: this.persist.checked ? null : void 0 }
1408
+ ).then((data2) => {
1409
+ this.close();
1410
+ this._done();
1411
+ return data2;
1412
+ }).catch((err) => {
1413
+ this.alert.classList.remove("hidden");
1414
+ this.alert.innerHTML = err.message;
1415
+ this.password.value = "";
1416
+ this.username.disabled = false;
1417
+ this.password.disabled = false;
1418
+ this.persist.disabled = false;
1419
+ this.button.disabled = false;
1420
+ });
1421
+ }
1422
+ };
1423
+ /** Dynamically create CSS style */
1424
+ __publicField(_LoginPrompt, "css", (options) => `
1425
+ <style id="datalynk-login-styles">
1426
+ @import url('https://fonts.cdnfonts.com/css/ar-blanca');
1427
+
1428
+ #datalynk-login {
1429
+ --theme-background: ${options.background};
1430
+ --theme-container: #000000cc;
1431
+ --theme-glow: ${options.glow || options.color};
1432
+ --theme-primary: ${options.color};
1433
+ --theme-text: ${options.textColor};;
1434
+
1435
+ position: fixed;
1436
+ left: 0;
1437
+ top: 0;
1438
+ right: 0;
1439
+ bottom: 0;
1440
+ background: var(--theme-background);
1441
+ background-repeat: no-repeat;
1442
+ background-size: cover;
1443
+ font-family: sans-serif;
1444
+ z-index: 1000;
1445
+ }
1446
+
1447
+ #datalynk-login .added-links {
1448
+ color: var(--theme-text);
1449
+ position: fixed;
1450
+ bottom: 0;
1451
+ right: 0;
1452
+ padding: 0.25rem;
1453
+ }
1454
+
1455
+ #datalynk-login .added-links a, #datalynk-login .added-links a:hover, #datalynk-login .added-links a:visited {
1456
+ color: var(--theme-text);
1457
+ text-shadow: 0 0 10px black;
1458
+ }
1459
+
1460
+ #datalynk-login-alert {
1461
+ padding: 0.75rem;
1462
+ background: rgba(0,0,0,0.5);
1463
+ color: white;
1464
+ border-radius: 5px;
1465
+ margin-bottom: 1rem;
1466
+ border: grey 1px solid;
1467
+ }
1468
+
1469
+ #datalynk-login label {
1470
+ color: white;
1471
+ font-size: 20px;
1472
+ }
1473
+
1474
+ #datalynk-login input {
1475
+ width: calc(100% - 20px);
1476
+ padding: 12px 9px 9px 9px;
1477
+ margin: 1px;
1478
+ border: 1px solid #ddd;
1479
+ border-radius: 5px;
1480
+ background-color: white;
1481
+ color: black;
1482
+ }
1483
+
1484
+ #datalynk-login .login-container {
1485
+ position: fixed;
1486
+ top: 50%;
1487
+ left: 0;
1488
+ right: 0;
1489
+ transform: translateY(-50%);
1490
+ }
1491
+
1492
+ #datalynk-login .login-header {
1493
+ display: flex;
1494
+ justify-content: center;
1495
+ align-items: center;
1496
+ color: var(--theme-text);
1497
+ text-align: center;
1498
+ font-size: 32px;
1499
+ margin-bottom: 2rem;
1500
+ }
1501
+
1502
+ #datalynk-login .login-content {
1503
+ display: flex;
1504
+ flex-direction: column;
1505
+ align-items: center;
1506
+ background: var(--theme-container);
1507
+ border-top: var(--theme-glow) 1px solid;
1508
+ box-shadow: 0 -10px 20px -10px var(--theme-glow);
1509
+ }
1510
+
1511
+ #datalynk-login .login-body {
1512
+ padding: ${options.hideApps ? "3.5rem 0" : "3.5rem 0 1.5rem 0"};
1513
+ width: 100%;
1514
+ max-width: 400px;;
1515
+ color: white;
1516
+ }
1517
+
1518
+ #datalynk-login input:disabled {
1519
+ color: #333;
1520
+ background-color: #ccc;
1521
+ }
1522
+
1523
+ #datalynk-login input[type="checkbox"] {
1524
+ height: 15px;
1525
+ margin: 0;
1526
+ padding: 0;
1527
+ accent-color: var(--theme-primary);
1528
+ }
1529
+
1530
+ #datalynk-login button {
1531
+ background-color: var(--theme-primary);
1532
+ background-image: none;
1533
+ border: 0;
1534
+ color: ${blackOrWhite(options.color)};
1535
+ padding: 8px 24px;
1536
+ border-radius: 5px;
1537
+ }
1538
+
1539
+ #datalynk-login button:disabled {
1540
+ cursor: pointer;
1541
+ filter: brightness(90%);
1542
+ }
1543
+
1544
+ #datalynk-login button:hover:not(:disabled) {
1545
+ cursor: pointer;
1546
+ filter: ${blackOrWhite(options.color) == "black" ? "brightness(105%)" : "brightness(80%)"};
1547
+ }
1548
+
1549
+ #datalynk-login .login-links{
1550
+ display: flex;
1551
+ padding: 0 0 1.5rem 0;
1552
+ }
1553
+
1554
+ #datalynk-login .login-links a {
1555
+ text-decoration: none;
1556
+ }
1557
+
1558
+ #datalynk-login .login-links img {
1559
+ width: 150px;
1560
+ height: auto;
1561
+ }
1562
+
1563
+ #datalynk-login .hidden {
1564
+ display: none;
1565
+ }
1566
+
1567
+ #datalynk-login .login-footer {
1568
+ transform: translateY(-18px);
1569
+ }
1570
+
1571
+ #datalynk-login .sloped-div {
1572
+ position: absolute;
1573
+ height: 45px;
1574
+ width: 200px;
1575
+ background: var(--theme-container);
1576
+ clip-path: polygon(0 20px, 100% 20px, 85% 60px, 15% 60px);
1577
+ }
1578
+ </style>`);
1579
+ /** Dynamically create HTML */
1580
+ __publicField(_LoginPrompt, "template", (options) => `
1581
+ <div id="datalynk-login">
1582
+ <div class="added-links">
1583
+ ${(options.addLinks || []).map((link) => `<a href="${link.url || "#"}" target="_blank">${link.text}</a>`).join(" | ")}
1584
+ </div>
1585
+ <div class="login-container">
1586
+ <div class="login-header">
1587
+ ${options.title}
1588
+ </div>
1589
+ <div class="login-content">
1590
+ <div class="login-body" style="max-width: 300px">
1591
+ <div id="datalynk-login-alert" class="hidden"></div>
1592
+ <form id="datalynk-login-form">
1593
+ <div>
1594
+ <label for="username">Email or Username</label>
1595
+ <input id="username" name="username" type="text" autocomplete="username">
1596
+ </div>
1597
+ <br>
1598
+ <div>
1599
+ <label for="password">Password</label>
1600
+ <input id="password" name="password" type="password" autocomplete="current-password">
1601
+ </div>
1602
+ <br>
1603
+ <label style="display: block; margin-bottom: 0.75rem;">
1604
+ <input type="checkbox" name="persist" style="width: 20px"> Stay Logged In
1605
+ </label>
1606
+ <button type="submit">Login</button>
1607
+ </form>
1608
+ </div>
1609
+ ${options.hideApps ? "" : `
1610
+ <div class="login-links" style="text-align: center">
1611
+ <a href="https://itunes.apple.com/ca/app/auxilium-mobile/id1166379280?mt=8" target="_blank">
1612
+ <img alt="App Store" src="https://datalynk.auxiliumgroup.com/api/js/auxilium/dijits/templates/login/_common/mobile_apple_transparent.png">
1613
+ </a>
1614
+ <a href="https://play.google.com/store/apps/details?id=com.auxilium.auxiliummobilesolutions&amp;hl=en" target="_blank">
1615
+ <img alt="Playstore" src="https://datalynk.auxiliumgroup.com/api/js/auxilium/dijits/templates/login/_common/mobile_google_transparent.png">
1616
+ </a>
1617
+ </div>
1618
+ `}
1619
+ </div>
1620
+ <div class="login-footer" style="position: relative; display: flex; align-items: center; justify-content: center;">
1621
+ <div class="sloped-div"></div>
1622
+ <a href="https://auxiliumgroup.com" target="_blank" style="position: relative; height: 40px; display: flex; align-items: center; text-decoration: none; font-family: 'AR BLANCA', serif; font-size: 26px; color: white;">
1623
+ Au<span style="font-size: 52px; color: #c83232; margin-bottom: 5px">x</span>ilium
1624
+ <span style="position: absolute; font-size: 10px; color: #c83232; top: 2px; right: 2px">Group</span>
1625
+ </a>
1626
+ </div>
1627
+ </div>
1628
+ </div>
1629
+ `);
1630
+ let LoginPrompt = _LoginPrompt;
1631
+ class Auth {
1632
+ constructor(api) {
1633
+ /** Current user as an observable */
1634
+ __publicField(this, "user$", new BehaviorSubject(void 0));
1635
+ this.api = api;
1636
+ this.api.token$.subscribe(async (token) => {
1637
+ if (token === void 0) return;
1638
+ this.user = await this.current(token);
1639
+ });
1640
+ }
1641
+ /** Current user */
1642
+ get user() {
1643
+ return this.user$.getValue();
1644
+ }
1645
+ /** Set current user info */
1646
+ set user(user) {
1647
+ this.user$.next(user);
1648
+ }
1649
+ get spoke() {
1650
+ var _a;
1651
+ return ((_a = this.api.jwtPayload) == null ? void 0 : _a.realm) || null;
1652
+ }
1653
+ /**
1654
+ * Get current user associated with API token
1655
+ *
1656
+ * @return {Promise<User | null>}
1657
+ */
1658
+ async current(token = this.api.token) {
1659
+ var _a;
1660
+ if (!token) return null;
1661
+ else if (token == ((_a = this.user) == null ? void 0 : _a.token)) return this.user;
1662
+ return this.api.request({ "$/auth/current": {} }, { token }).then((resp) => (resp == null ? void 0 : resp.login) ? resp : null);
1663
+ }
1664
+ /**
1665
+ * Automatically handle sessions by checking localStorage & URL parameters for a token & prompting
1666
+ * user with a login screen if required
1667
+ *
1668
+ * @param {string} spoke Desired spoke
1669
+ * @param {LoginPromptOptions} options Aesthetic options
1670
+ * @return {Promise<void>} Login complete
1671
+ */
1672
+ async handleLogin(spoke, options) {
1673
+ var _a;
1674
+ const urlToken = new URLSearchParams(location.search).get("datalynkToken");
1675
+ if (urlToken) {
1676
+ this.api.token = urlToken;
1677
+ location.href = location.href.replace(/datalynkToken=.*?(&|$)/gm, "");
1678
+ } else if (this.api.token) {
1679
+ if (((_a = this.api.jwtPayload) == null ? void 0 : _a.realm) != spoke) {
1680
+ this.api.token = null;
1681
+ location.reload();
1682
+ }
1683
+ } else {
1684
+ await this.loginPrompt(spoke, options).done;
1685
+ location.reload();
1686
+ }
1687
+ }
1688
+ /**
1689
+ * Check whether user has a token
1690
+ *
1691
+ * @return {boolean} True if session token authenticated
1692
+ */
1693
+ isAuthenticated() {
1694
+ return !!this.user && !this.user.guest;
1695
+ }
1696
+ /**
1697
+ * Check if the current user is a guest
1698
+ *
1699
+ * @return {boolean} True if guest
1700
+ */
1701
+ isGuest() {
1702
+ var _a;
1703
+ return !!((_a = this.user) == null ? void 0 : _a.guest);
1704
+ }
1705
+ /**
1706
+ * Check if user is a system administrator
1707
+ *
1708
+ * @return {Promise<boolean>} True if system administrator
1709
+ */
1710
+ async isSysAdmin() {
1711
+ return !!(await this.api.slice("sysadmin").select().where("auth_ref", "==", "$viewer").rows().exec()).length;
1712
+ }
1713
+ /**
1714
+ * Check if user is a table administrator
1715
+ *
1716
+ * @return {Promise<boolean>} True if table administrator
1717
+ */
1718
+ async isTableAdmin() {
1719
+ return !!(await this.api.slice("tableadmins").select().where("auth_ref", "==", "$viewer").rows().exec()).length;
1720
+ }
1721
+ /**
1722
+ * Check if user is a user administrator
1723
+ *
1724
+ * @return {Promise<boolean>} True if user administrator
1725
+ */
1726
+ async isUserAdmin() {
1727
+ return !!(await this.api.slice("useradmins").select().where("auth_ref", "==", "$viewer").rows().exec()).length;
1728
+ }
1729
+ /**
1730
+ * Perform login and save the session token
1731
+ *
1732
+ * @param {string} login Login username or email
1733
+ * @param {string} password Password for account
1734
+ * @param {string} spoke Override login spoke
1735
+ * @param {twoFactor?: string, expire?: string} opts 2FA code & expire date (YYYY-MM-DD)
1736
+ * @returns {Promise<User>} User account
1737
+ */
1738
+ login(spoke, login, password, opts) {
1739
+ const date = /* @__PURE__ */ new Date();
1740
+ date.setFullYear(date.getFullYear() + 1);
1741
+ return fetch(`${this.api.url}login`, {
1742
+ method: "POST",
1743
+ headers: { "Content-Type": "application/json" },
1744
+ body: JSON.stringify(clean({
1745
+ realm: spoke.trim(),
1746
+ login: login.trim(),
1747
+ password: password.trim(),
1748
+ secret: opts == null ? void 0 : opts.twoFactor,
1749
+ expireAt: (opts == null ? void 0 : opts.expire) == null ? formatDate("YYYY-MM-DD", date) : opts == null ? void 0 : opts.expire,
1750
+ dateFormat: "ISO8601"
1751
+ }))
1752
+ }).then(async (resp) => {
1753
+ const data = await resp.json().catch(() => ({}));
1754
+ if (!resp.ok || data["error"]) throw Object.assign(errorFromCode(resp.status, data.error) || {}, data);
1755
+ this.api.token = data["token"];
1756
+ return data;
1757
+ });
1758
+ }
1759
+ /**
1760
+ * Login as guest user
1761
+ *
1762
+ * @return {Promise<User>} Guest account
1763
+ */
1764
+ loginGuest() {
1765
+ return fetch(`${this.api.url}guest`).then(async (resp) => {
1766
+ const data = await resp.json().catch(() => ({}));
1767
+ if (!resp.ok || data["error"]) throw Object.assign(errorFromCode(resp.status, data.error) || {}, data);
1768
+ this.api.token = data["token"];
1769
+ return data;
1770
+ });
1771
+ }
1772
+ /**
1773
+ * Create Login UI
1774
+ *
1775
+ * @param {string} spoke Desired spoke
1776
+ * @param {LoginPromptOptions} options Aesthetic options
1777
+ * @return {LoginPrompt} Login prompt
1778
+ */
1779
+ loginPrompt(spoke, options) {
1780
+ return new LoginPrompt(this.api, spoke, options);
1781
+ }
1782
+ /**
1783
+ * Logout current user
1784
+ *
1785
+ * @return {Promise<{closed: string, new: string}>}
1786
+ */
1787
+ logout() {
1788
+ return this.api.request({ "$/auth/logout": {} }).then((resp) => {
1789
+ this.api.token = null;
1790
+ return resp;
1791
+ });
1792
+ }
1793
+ /**
1794
+ * Reset user account password
1795
+ *
1796
+ * @param {string} login User login
1797
+ * @param {string} newPassword New password
1798
+ * @param {string} code Reset code sent with `resetRequest`
1799
+ * @return {Promise<any>} New session
1800
+ */
1801
+ reset(login, newPassword, code) {
1802
+ return this.api.request({ "$/auth/mobile/rescue": {
1803
+ user: login,
1804
+ password: newPassword,
1805
+ pin: code
1806
+ } }).then((resp) => {
1807
+ if (resp.token) this.api.token = resp.token;
1808
+ return resp;
1809
+ });
1810
+ }
1811
+ /**
1812
+ * Request reset code for user
1813
+ *
1814
+ * @param {string} login User to reset
1815
+ * @param {"email" | "sms" | "voice"} mode Method of sending reset code
1816
+ * @return {Promise<any>} Unknown
1817
+ */
1818
+ resetRequest(login, mode) {
1819
+ if (mode == "email") return this.api.request({ "$/auth/rescue_email": { user: { $or: { login, email: login } } } });
1820
+ return this.api.request({ "$/auth/mobile/generate": { user: login, method: mode } });
1821
+ }
1822
+ }
1823
+ class Files {
1824
+ constructor(api) {
1825
+ __publicField(this, "url");
1826
+ this.api = api;
1827
+ this.url = `${this.api.url}file`;
1828
+ }
1829
+ associate(fileIds, slice, row, field, execute = true) {
1830
+ const req = { [`${execute ? "!" : "$"}/tools/file/update`]: { slice, row, field, ids: fileIds } };
1831
+ if (execute) return this.api.request(req);
1832
+ return req;
1833
+ }
1834
+ /**
1835
+ * Get an authenticated URL to fetch files from
1836
+ *
1837
+ * @param {number} id File ID
1838
+ * @param {boolean} ignoreToken Ignore authentication
1839
+ * @return {string} URL file can be viewed at
1840
+ */
1841
+ get(id, ignoreToken) {
1842
+ return `${this.url}?id=${id}${ignoreToken ? "" : `&token=${this.api.token}`}`;
1843
+ }
1844
+ /**
1845
+ * Upload file(s) to the API & optionally associate them with a row
1846
+ *
1847
+ * @param {FileList | File | File[]} files Files to be uploaded
1848
+ * @param {{slice: number, row: any, field: string, pk?: string}} associate Row to associate with
1849
+ */
1850
+ upload(files, associate) {
1851
+ let f = [];
1852
+ if (files instanceof FileList) f = Array.from(files);
1853
+ else f = Array.isArray(files) ? files : [files];
1854
+ return Promise.all(f.map((file) => {
1855
+ const data = new FormData();
1856
+ data.append("", file, file.name);
1857
+ return fetch(this.url, {
1858
+ method: "POST",
1859
+ headers: clean({ "Authorization": this.api.token ? `Bearer ${this.api.token}` : "" }),
1860
+ body: data
1861
+ }).then(async (resp) => {
1862
+ const data2 = await resp.json().catch(() => ({}));
1863
+ if (!resp.ok || data2["error"]) throw Object.assign(errorFromCode(resp.status, data2.error) || {}, data2);
1864
+ return resp;
1865
+ });
1866
+ })).then(async (files2) => {
1867
+ if (associate) {
1868
+ let id = typeof associate.row == "number" ? associate.row : associate.row[associate.pk || "id"];
1869
+ if (!id) id = await this.api.slice(associate.slice).insert(associate.row).id();
1870
+ 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);
1871
+ }
1872
+ return files2;
1873
+ });
1874
+ }
1875
+ }
1876
+ class Pdf {
1877
+ constructor(api) {
1878
+ this.api = api;
1879
+ }
1880
+ /**
1881
+ * Create a PDF from a public URL
1882
+ * @param {string} url Target URL address
1883
+ * @param {{slice: number, row: number, field: string} | null} associate Optionally associate PDF with a slice row
1884
+ * @param {PdfOptions} options PDF options for rendering & uploading
1885
+ * @return {Promise<any>} Either the PDF file number or the updated slice row response if associated
1886
+ */
1887
+ async fromUrl(url, associate, options = {}) {
1888
+ return this.api.request({ "$/slice/utils/urlToPdf": { url, ...options } }).then((file) => {
1889
+ if (associate) return this.api.files.associate(file, associate.slice, associate.row, associate.field);
1890
+ return file;
1891
+ });
1892
+ }
1893
+ }
1894
+ const Serializer = {
1895
+ /**
1896
+ * From Datalynk syntax to JS
1897
+ */
1898
+ deserialize: {
1899
+ /**
1900
+ * Convert date time string to javascript date object
1901
+ *
1902
+ * @param {string} datetime datetime string (YYYY/MM/DD hh:mm:ss)
1903
+ * @returns {Date} JS Date object
1904
+ */
1905
+ "$/tools/date": (datetime) => {
1906
+ let a = datetime.split(/[^0-9]+/).map((part) => Number(part));
1907
+ return new Date(a[0], a[1] - 1, a[2], a[3], a[4], a[5]);
1908
+ },
1909
+ /**
1910
+ * Convert date string to javascript date object
1911
+ *
1912
+ * @param {string} date date string (YYYY/MM/DD)
1913
+ * @returns {Date} JS Date object
1914
+ */
1915
+ "$/tools/date_strict": (date) => {
1916
+ let a = date.split(/[^0-9]+/).map((part) => Number(part));
1917
+ let d = new Date(a[0], a[1] - 1, a[2], 0, 0, 0);
1918
+ d["hint"] = "date";
1919
+ return d;
1920
+ },
1921
+ /**
1922
+ * Convert time string to javascript date object
1923
+ *
1924
+ * @param {string} time time string (YYYY/MM/DD)
1925
+ * @returns {Date} JS Date object
1926
+ */
1927
+ "$/tools/time_strict": (time) => {
1928
+ let a = time.split(/[^0-9]+/).map((part) => Number(part));
1929
+ let d = /* @__PURE__ */ new Date();
1930
+ d.setHours(a[0]);
1931
+ d.setMinutes(a[1]);
1932
+ d.setSeconds(a[2]);
1933
+ d["hint"] = "time";
1934
+ return d;
1935
+ },
1936
+ /**
1937
+ * Convert string to constant
1938
+ *
1939
+ * @param {string} constant string to be converted
1940
+ * @returns {any} the actual constant
1941
+ */
1942
+ "$/tools/const": (constant) => {
1943
+ let types = {
1944
+ "infinity": Infinity,
1945
+ "-infinity": -Infinity,
1946
+ "nan": NaN
1947
+ };
1948
+ try {
1949
+ return types[constant["$/tools/const"].toLowerCase()];
1950
+ } catch (ignored) {
1951
+ return void 0;
1952
+ }
1953
+ },
1954
+ /**
1955
+ * Large requests are formatted into parallel arrays
1956
+ *
1957
+ * @param {object} obj Object of metadata and data
1958
+ * @returns {Array} Actual object reconstructed
1959
+ */
1960
+ "$/tools/dltable": function(obj) {
1961
+ let meta = obj["meta"];
1962
+ let col;
1963
+ let fn = [];
1964
+ for (let i in meta) {
1965
+ col = meta[i];
1966
+ fn.push("this['" + col.name + "'] = ");
1967
+ if (col.cast == null) {
1968
+ fn.push("a[" + i + "];\n");
1969
+ } else if (col.cast === "num") {
1970
+ fn.push("a[" + i + "] && parseFloat(a[" + i + "]);\n");
1971
+ } else {
1972
+ if (col["native"] === "date") {
1973
+ fn.push("a[" + i + "] && dateParse(a[" + i + "]);\n");
1974
+ fn.push("a[" + i + "] && (this['" + col.name + "'].hint = 'date');\n");
1975
+ } else if (col["native"] === "time") {
1976
+ fn.push("a[" + i + "] && timeParse(a[" + i + "]);\n");
1977
+ fn.push("a[" + i + "] && (this['" + col.name + "'].hint = 'time');\n");
1978
+ } else {
1979
+ fn.push("a[" + i + "] && datetimeParse(a[" + i + "]);\n");
1980
+ }
1981
+ }
1982
+ }
1983
+ let dateTimeParse, dateParse, timeParse;
1984
+ let now = /* @__PURE__ */ new Date();
1985
+ let yyyy = now.getFullYear();
1986
+ let mm = now.getMonth();
1987
+ let dd = now.getDate();
1988
+ dateTimeParse = function(dt) {
1989
+ dt = dt.split(/[^0-9]+/);
1990
+ return new Date(dt[0], dt[1] - 1, dt[2], dt[3], dt[4], dt[5]);
1991
+ };
1992
+ dateParse = function(d) {
1993
+ d = d.split(/[- :]/);
1994
+ let res2 = new Date(d[0], d[1] - 1, d[2], 0, 0, 0);
1995
+ res2["hint"] = "date";
1996
+ return res2;
1997
+ };
1998
+ timeParse = function(t) {
1999
+ t = t.split(/[^0-9]+/, t);
2000
+ let res2 = new Date(yyyy, mm, dd, t[0], t[1], t[2]);
2001
+ res2["hint"] = "time";
2002
+ return res2;
2003
+ };
2004
+ let ctor = Function("datetimeParse", "dateParse", "timeParse", "a", fn.join(""));
2005
+ let res = [];
2006
+ let rows = obj["rows"];
2007
+ for (let i in rows) {
2008
+ res[i] = new ctor(dateTimeParse, dateParse, timeParse, rows[i]);
2009
+ }
2010
+ res["meta"] = meta;
2011
+ res["rowConstructor"] = ctor;
2012
+ return res;
2013
+ }
2014
+ },
2015
+ /**
2016
+ * From JS to Datalynk syntax
2017
+ */
2018
+ serialize: {
2019
+ /**
2020
+ * Convert JS date to datalynk datetime string
2021
+ */
2022
+ "Date": (date) => {
2023
+ return {
2024
+ "$/tools/date": [date.getFullYear(), date.getMonth() + 1, date.getDate()].join("/") + " " + [date.getHours(), date.getMinutes(), date.getSeconds()].join(":")
2025
+ };
2026
+ }
2027
+ }
2028
+ };
2029
+ const _Slice = class _Slice {
2030
+ /**
2031
+ * An object to aid in constructing requests
2032
+ *
2033
+ * @param {number} slice Slice ID to interact with
2034
+ * @param {Api} api Api to send the requests through
2035
+ */
2036
+ constructor(slice, api) {
2037
+ __publicField(this, "operation");
2038
+ __publicField(this, "popField");
2039
+ __publicField(this, "request", {});
2040
+ /** Log response automatically */
2041
+ __publicField(this, "debugging");
2042
+ /** Unsubscribe from changes, undefined if not subscribed */
2043
+ __publicField(this, "unsubscribe");
2044
+ /** Cached slice data as an observable */
2045
+ __publicField(this, "cache$", new BehaviorSubject([]));
2046
+ /**
2047
+ * Whitelist and alias fields. Alias of `fields()`
2048
+ * @example
2049
+ * ```ts
2050
+ * const id: {id: number, field2: any}[] = await new Slice<T>(12345)
2051
+ * .select().alias({id: 'id', field1: 'field2'}).exec().keys();
2052
+ * ```
2053
+ * @param {object} aliasKeyVals List of properties to whitelist and what to rename them to
2054
+ * @return {Slice<T>}
2055
+ */
2056
+ __publicField(this, "alias", this.fields);
2057
+ this.slice = slice;
2058
+ this.api = api;
2059
+ }
2060
+ /** Cached slice data */
2061
+ get cache() {
2062
+ return this.cache$.getValue();
2063
+ }
2064
+ /** Set cached data & alert subscribers */
2065
+ set cache(cache) {
2066
+ this.cache$.next(cache);
2067
+ }
2068
+ /** Get raw API request */
2069
+ get raw() {
2070
+ return clean({
2071
+ [this.operation]: {
2072
+ ...this.request,
2073
+ slice: this.slice
2074
+ },
2075
+ "$pop": this.popField ? this.popField : void 0
2076
+ });
2077
+ }
2078
+ /**
2079
+ * Add an 'AND' condition inside the where argument
2080
+ * @example
2081
+ * ```ts
2082
+ * const rows: T[] = await new Slice<T>(12345).select()
2083
+ * .where('field1', '>', 1)
2084
+ * .and()
2085
+ * .where({field2: 2, field3: 3})
2086
+ * .exec().rows();
2087
+ * ```
2088
+ * @return {Slice<T>}
2089
+ */
2090
+ and() {
2091
+ var _a;
2092
+ if (((_a = this.request.where) == null ? void 0 : _a[0]) == "$and") return this;
2093
+ if (this.request.where) this.request.where = ["$and", this.request.where];
2094
+ else this.request.where = ["$and"];
2095
+ return this;
2096
+ }
2097
+ /**
2098
+ * Count the returned rows
2099
+ * @example
2100
+ * ```ts
2101
+ * const count = await new Slice(12345).count()
2102
+ * .where({field1: 1})
2103
+ * .exec().count();
2104
+ * ```
2105
+ * @param {object | string} arg Count argument
2106
+ * @return {Slice<T>}
2107
+ */
2108
+ count(arg = "id") {
2109
+ this.operation = "$/slice/report";
2110
+ this.request.fields = { count: ["$count", typeof arg == "object" ? arg : ["$field", arg]] };
2111
+ return this.pop("rows:0:count");
2112
+ }
2113
+ /**
2114
+ * Output the formed request to the console for inspection
2115
+ * @param {boolean} enabled Enable/Disable console logging
2116
+ * @return {Slice<T>}
2117
+ */
2118
+ debug(enabled = true) {
2119
+ this.debugging = enabled;
2120
+ return this;
2121
+ }
2122
+ /**
2123
+ * Set the request type to delete
2124
+ * @example
2125
+ * ```ts
2126
+ * await new Slice(12345).delete(id).exec();
2127
+ * ```
2128
+ * @param {number | number[]} id ID(s) to delete
2129
+ * @return {Slice<T>}
2130
+ */
2131
+ delete(id) {
2132
+ this.operation = "$/slice/delete";
2133
+ if (id) {
2134
+ if (Array.isArray(id)) this.where("id", "$in", id);
2135
+ else this.where("id", "==", id);
2136
+ }
2137
+ return this;
2138
+ }
2139
+ /**
2140
+ * Filter rows from slice based on an excel expression
2141
+ * @example
2142
+ * ```ts
2143
+ * const rows: T[] = await new Slice<T>(12345).select()
2144
+ * .excel('contains({property}, foobar)')
2145
+ * .exec().rows();
2146
+ * ```
2147
+ * @param formula Excel formula to use as where clause
2148
+ * @return {Slice<T>}
2149
+ */
2150
+ excel(formula) {
2151
+ this.where(["$excel", formula]);
2152
+ return this;
2153
+ }
2154
+ /**
2155
+ * Compile the request and send it
2156
+ * @param {ApiRequestOptions} options API Request options
2157
+ * @return {Promise<T = any>} API response
2158
+ */
2159
+ exec(options) {
2160
+ if (!this.operation) throw new Error("No operation chosen");
2161
+ return this.api.request(this.raw, options).then((resp) => {
2162
+ if (this.debugging) console.log(resp);
2163
+ return resp;
2164
+ });
2165
+ }
2166
+ fields(keys) {
2167
+ this.request.fields = Array.isArray(keys) ? keys.reduce((acc, key) => ({ ...acc, [key]: key }), {}) : keys;
2168
+ return this;
2169
+ }
2170
+ /**
2171
+ * Unwrap response returning the first ID
2172
+ * @return {Slice<T>}
2173
+ */
2174
+ id() {
2175
+ return this.pop("rows:0:id");
2176
+ }
2177
+ /**
2178
+ * Set the request type to insert
2179
+ * @example
2180
+ * ```ts
2181
+ * const id: number = await new Slice<T>(12345).insert([
2182
+ * {field1: 1},
2183
+ * {field1: 2}
2184
+ * ]).exec().keys();
2185
+ * ```
2186
+ * @param {T | T[]} rows Rows to be inserted into the slice
2187
+ * @return {Slice<T>}
2188
+ */
2189
+ insert(rows) {
2190
+ this.operation = "$/slice/xinsert";
2191
+ if (!this.request.rows) this.request.rows = [];
2192
+ if (Array.isArray(rows)) this.request.rows = this.request.rows.concat(rows);
2193
+ else this.request.rows.push(rows);
2194
+ return this;
2195
+ }
2196
+ /**
2197
+ * Limit number of rows returned
2198
+ * @example
2199
+ * ```ts
2200
+ * const rows: T[] = await new Slice<T>(12345).select().limit(10)
2201
+ * .exec().rows();
2202
+ * ```
2203
+ * @param {number} num Number of rows to return
2204
+ * @return {Slice<T>}
2205
+ */
2206
+ limit(num) {
2207
+ this.request.limit = num;
2208
+ return this;
2209
+ }
2210
+ /**
2211
+ * Add an 'OR' condition inside the where argument
2212
+ * @example
2213
+ * ```ts
2214
+ * const rows: T[] = await new Slice<T>(12345).select()
2215
+ * .where('field1', '>', 1)
2216
+ * .or()
2217
+ * .where({field2: 2, field3: 3})
2218
+ * .or()
2219
+ * .where(['$gt', ['$field', field4], 4)
2220
+ * .exec().rows();
2221
+ * ```
2222
+ * @return {Slice<T>}
2223
+ */
2224
+ or() {
2225
+ var _a;
2226
+ if (((_a = this.request.where) == null ? void 0 : _a[0]) == "$or") {
2227
+ this.request.where.push(null);
2228
+ return this;
2229
+ }
2230
+ if (this.request.where) this.request.where = ["$or", this.request.where, null];
2231
+ else this.request.where = ["$or", null];
2232
+ return this;
2233
+ }
2234
+ /**
2235
+ * Order rows by a field
2236
+ * @example
2237
+ * ```ts
2238
+ * const rows: T[] = new Slice<T>(12345).select().order('field1', true) // true = ascending
2239
+ * .exec().rows();
2240
+ * ```
2241
+ * @param {string} field property name
2242
+ * @param {boolean} ascending Sort in ascending or descending order
2243
+ * @return {Slice<T>}
2244
+ */
2245
+ order(field, ascending = true) {
2246
+ if (!this.request.order) this.request.order = [];
2247
+ this.request.order.push([ascending ? "$asc" : "$desc", ["$field", field]]);
2248
+ return this;
2249
+ }
2250
+ /**
2251
+ * Unwrap response, returning the field
2252
+ * @param {string} field Colon seperated path: `rows:0`
2253
+ * @return {Slice<T>}
2254
+ */
2255
+ pop(field) {
2256
+ this.popField = field;
2257
+ return this;
2258
+ }
2259
+ /**
2260
+ * Unwrap response returning the first row
2261
+ * @return {Slice<T>}
2262
+ */
2263
+ row() {
2264
+ return this.pop("rows:0");
2265
+ }
2266
+ /**
2267
+ * Unwrap response returning the rows
2268
+ * @return {Slice<T>}
2269
+ */
2270
+ rows() {
2271
+ return this.pop("rows");
2272
+ }
2273
+ /**
2274
+ * Set the request type to select
2275
+ * @example
2276
+ * ```ts
2277
+ * const rows: T[] = new Slice<T>(12345).select().exec().rows();
2278
+ * const row: T = new Slice<T>(12345).select(id).exec().row();
2279
+ * ```
2280
+ * @param {number | number[]} id ID(s) to select, leaving blank will return all rows
2281
+ * @return {Slice<T>}
2282
+ */
2283
+ select(id) {
2284
+ this.operation = "$/slice/report";
2285
+ if (id) {
2286
+ if (Array.isArray(id)) this.where("id", "$in", id);
2287
+ else this.where("id", "==", id);
2288
+ }
2289
+ return this;
2290
+ }
2291
+ /**
2292
+ * Synchronize cache with server
2293
+ * @example
2294
+ * ```ts
2295
+ * const slice: Slice = new Slice<T>(Slices.Contact);
2296
+ * slice.sync().subscribe((rows: T[]) => {});
2297
+ * ```
2298
+ * @param {boolean} on Enable/disable events
2299
+ * @return {BehaviorSubject<T[]>} Cache which can be subscribed to
2300
+ */
2301
+ sync(on = true) {
2302
+ if (on) {
2303
+ new _Slice(this.slice, this.api).select().rows().exec().then((rows) => this.cache = rows);
2304
+ if (!this.unsubscribe) this.unsubscribe = this.api.socket.sliceEvents(this.slice, (event) => {
2305
+ const ids = [...event.data.new, ...event.data.changed];
2306
+ 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]);
2307
+ this.cache = this.cache.filter((v) => v.id && !event.data.lost.includes(v.id));
2308
+ });
2309
+ return this.cache$;
2310
+ } else if (this.unsubscribe) {
2311
+ this.unsubscribe();
2312
+ this.unsubscribe = null;
2313
+ }
2314
+ }
2315
+ /**
2316
+ * Set the request type to update
2317
+ * @example
2318
+ * ```ts
2319
+ * const ids: number[] = await new Slice<Type>(12345).update([
2320
+ * {id: 1, field1: 1},
2321
+ * {id: 2, field1: 1}
2322
+ * ]).exec().keys();
2323
+ * ```
2324
+ * @param {T | T[]} rows Rows to be updated, each row must have an ID
2325
+ * @return {Slice<T>}
2326
+ */
2327
+ update(rows) {
2328
+ this.operation = "$/slice/xupdate";
2329
+ if (!this.request.rows) this.request.rows = [];
2330
+ if (Array.isArray(rows)) this.request.rows = this.request.rows.concat(rows);
2331
+ else this.request.rows.push(rows);
2332
+ return this;
2333
+ }
2334
+ /**
2335
+ * Add where condition to request
2336
+ * @example
2337
+ * ```ts
2338
+ * const rows: T[] = await new Slice<T>(12345).select()
2339
+ * .where('field1', '>', 1)
2340
+ * .where({field2: 2, field3: 3}) // Automatic AND
2341
+ * .or()
2342
+ * .where(['$gt', ['$field', field4], 4)
2343
+ * .exec().rows();
2344
+ * ```
2345
+ * @param {string | object} field property to compare or a map of equality comparisons
2346
+ * @param {string} operator Operation to compare with. Accepts JS operators (>=, ==, !=, ...) as well as datalynk styax ($gte, $eq, $is, $not, ...)
2347
+ * @param {any} value value to compare against
2348
+ * @return {Slice<T>}
2349
+ */
2350
+ where(field, operator, value) {
2351
+ if (this.request.where && this.request.where[0] != "$or") this.and();
2352
+ const raw = Array.isArray(field);
2353
+ if (typeof field == "object" && !raw) {
2354
+ Object.entries(field).forEach(([key, value2]) => this.where(key, "==", value2));
2355
+ } else {
2356
+ const w = raw ? field : [(() => {
2357
+ if (operator == "==") return "$eq";
2358
+ if (operator == "!=") return "$neq";
2359
+ if (operator == ">") return "$gt";
2360
+ if (operator == ">=") return "$gte";
2361
+ if (operator == "<") return "$lt";
2362
+ if (operator == "<=") return "$lte";
2363
+ if (operator == "!") return "$not";
2364
+ if (operator == "%") return "$mod";
2365
+ if (operator == null ? void 0 : operator.startsWith("$")) return operator;
2366
+ throw new Error(`Unknown operator: ${operator}`);
2367
+ })(), ["$field", field], value];
2368
+ if (!this.request.where) this.request.where = w;
2369
+ else {
2370
+ if (this.request.where[0] == "$or") {
2371
+ const i = this.request.where.length - 1;
2372
+ if (this.request.where[i] == null) this.request.where[i] = w;
2373
+ else {
2374
+ if (this.request.where[i][0] == "$and") this.request.where[i].push(w);
2375
+ else this.request.where[i] = ["$and", this.request.where[i], w];
2376
+ }
2377
+ } else this.request.where.push(w);
2378
+ }
2379
+ }
2380
+ return this;
2381
+ }
2382
+ };
2383
+ __publicField(_Slice, "api");
2384
+ let Slice = _Slice;
2385
+ class Socket {
2386
+ constructor(api, options = {}) {
2387
+ __publicField(this, "listeners", []);
2388
+ // [ Callback, Re-subscribe ]
2389
+ __publicField(this, "retry");
2390
+ __publicField(this, "socket");
2391
+ __publicField(this, "open", false);
2392
+ this.api = api;
2393
+ this.options = options;
2394
+ if (!options.url && options.url !== false) {
2395
+ const url = new URL(this.api.url.replace("http", "ws"));
2396
+ url.port = "9390";
2397
+ this.options.url = url.origin;
2398
+ }
2399
+ if (this.options.url !== false)
2400
+ api.token$.pipe(filter((u) => u !== void 0), distinctUntilChanged()).subscribe(() => this.connect());
2401
+ }
2402
+ /**
2403
+ * Add listener for all socket events
2404
+ *
2405
+ * @param {SocketListener} fn Callback function
2406
+ * @return {Unsubscribe} Function to unsubscribe callback
2407
+ */
2408
+ addListener(fn, reconnect) {
2409
+ this.listeners.push([fn, reconnect]);
2410
+ return () => this.listeners = this.listeners.filter((l) => l[0] != fn);
2411
+ }
2412
+ /**
2413
+ * Close socket connection
2414
+ */
2415
+ close() {
2416
+ var _a;
2417
+ if (this.open) console.debug("Datalynk socket: disconnected");
2418
+ this.open = false;
2419
+ (_a = this.socket) == null ? void 0 : _a.close();
2420
+ this.socket = void 0;
2421
+ if (this.retry) clearTimeout(this.retry);
2422
+ this.retry = null;
2423
+ }
2424
+ /**
2425
+ * Connect socket client to socket server
2426
+ * @param {number} timeout Retry to connect every x seconds
2427
+ */
2428
+ connect(timeout = 30) {
2429
+ if (this.options.url === false) return console.warn("Datalynk socket disabled");
2430
+ if (this.open) this.close();
2431
+ this.retry = setTimeout(() => {
2432
+ if (this.open) return;
2433
+ this.close();
2434
+ this.connect();
2435
+ }, timeout * 1e3);
2436
+ if (navigator.onLine) {
2437
+ this.socket = new WebSocket(this.options.url + (this.api.token ? `?token=${this.api.token}` : ""));
2438
+ this.socket.onopen = () => clearTimeout(this.retry);
2439
+ this.socket.onclose = () => {
2440
+ if (this.open) this.connect(timeout);
2441
+ };
2442
+ this.socket.onmessage = (message) => {
2443
+ const payload = JSON.parse(message.data);
2444
+ if (payload.connected != void 0) {
2445
+ if (payload.connected) {
2446
+ this.open = true;
2447
+ console.debug("Datalynk socket: connected");
2448
+ this.listeners.forEach((l) => l[1]());
2449
+ } else {
2450
+ throw new Error(`Datalynk socket failed: ${payload.error}`);
2451
+ }
2452
+ } else {
2453
+ this.listeners.forEach((l) => l[0](payload));
2454
+ }
2455
+ };
2456
+ }
2457
+ }
2458
+ /**
2459
+ * Send data to socket server
2460
+ *
2461
+ * @param payload Data that will be serialized
2462
+ */
2463
+ send(payload) {
2464
+ var _a;
2465
+ if (!this.open) throw new Error("Datalynk socket not connected");
2466
+ (_a = this.socket) == null ? void 0 : _a.send(JSON.stringify(payload));
2467
+ }
2468
+ /**
2469
+ * Run callback whenever the server notifies us of slice changes
2470
+ *
2471
+ * @param {number | number[]} slice Slice to subscribe to
2472
+ * @param {SocketListener<SocketEventSlice>} callback Function to run on changes
2473
+ * @return {Unsubscribe} Run returned function to unsubscribe callback
2474
+ */
2475
+ sliceEvents(slice, callback) {
2476
+ const listen = () => this.send({ onSliceEvents: slice });
2477
+ if (this.open) listen();
2478
+ const unsubscribe = this.addListener((event) => {
2479
+ if (event.type == "sliceEvents" && event.data.slice == slice) callback(event);
2480
+ }, () => listen());
2481
+ return () => {
2482
+ this.send({ offSliceEvents: slice });
2483
+ unsubscribe();
2484
+ };
2485
+ }
2486
+ }
2487
+ class Superuser {
2488
+ constructor(api) {
2489
+ this.api = api;
2490
+ }
2491
+ /**
2492
+ * Switch to another user by ID
2493
+ *
2494
+ * @param {number} userId User ID
2495
+ * @return {Promise<any>} New session
2496
+ */
2497
+ assume(userId) {
2498
+ return this.api.request({ "$/report/users/become": { id: userId } }).then((resp) => {
2499
+ if (resp.token) this.api.token = resp.token;
2500
+ return resp;
2501
+ });
2502
+ }
2503
+ /**
2504
+ * Enable the superuser flag, required to make any of the requests in this helper
2505
+ *
2506
+ * @param {string} username Superuser account
2507
+ * @param {string} password Superuser password
2508
+ * @return {Promise<any>} Unknown
2509
+ */
2510
+ enable(username, password) {
2511
+ return this.api.request({ "$/superuser/validate": {
2512
+ name: username,
2513
+ password
2514
+ } });
2515
+ }
2516
+ }
2517
+ const version = "1.0.16";
2518
+ class Api {
2519
+ /**
2520
+ * Connect to Datalynk & send requests
2521
+ *
2522
+ * @example
2523
+ * ```ts
2524
+ * const api = new Api('https://spoke.auxiliumgroup.com');
2525
+ * ```
2526
+ *
2527
+ * @param {string} url API URL
2528
+ * @param {ApiOptions} options
2529
+ */
2530
+ constructor(url, options = {}) {
2531
+ /** Current requests bundle */
2532
+ __publicField(this, "bundle", []);
2533
+ /** Bundle lifecycle tracking */
2534
+ __publicField(this, "bundleOngoing", false);
2535
+ /** LocalStorage key for persisting logins */
2536
+ __publicField(this, "localStorageKey", "datalynk-token");
2537
+ /** Pending requests cache */
2538
+ __publicField(this, "pending", {});
2539
+ /** API URL */
2540
+ __publicField(this, "url");
2541
+ /** Package version */
2542
+ __publicField(this, "version", version);
2543
+ /** API Session token */
2544
+ __publicField(this, "token$", new BehaviorSubject(void 0));
2545
+ /** Helpers */
2546
+ /** Authentication */
2547
+ __publicField(this, "auth", new Auth(this));
2548
+ /** File */
2549
+ __publicField(this, "files", new Files(this));
2550
+ /** PDF */
2551
+ __publicField(this, "pdf", new Pdf(this));
2552
+ /** Socket */
2553
+ __publicField(this, "socket");
2554
+ /** Superuser */
2555
+ __publicField(this, "superuser", new Superuser(this));
2556
+ this.options = options;
2557
+ this.url = `${new URL(url).origin}/api/`;
2558
+ this.options = {
2559
+ bundleTime: 100,
2560
+ origin: typeof location !== "undefined" ? location.host : "Unknown",
2561
+ saveSession: true,
2562
+ ...options
2563
+ };
2564
+ if (this.options.saveSession) {
2565
+ if (localStorage == void 0) return;
2566
+ this.token = localStorage.getItem(this.localStorageKey) || null;
2567
+ this.token$.pipe(distinctUntilChanged()).subscribe((token) => {
2568
+ if (token) localStorage.setItem(this.localStorageKey, token);
2569
+ else localStorage.removeItem(this.localStorageKey);
2570
+ });
2571
+ }
2572
+ Slice.api = this;
2573
+ this.socket = new Socket(this, { url: options.socket });
2574
+ }
2575
+ get token() {
2576
+ return this.token$.getValue();
2577
+ }
2578
+ set token(token) {
2579
+ this.token$.next(token);
2580
+ }
2581
+ /** Get session info from JWT payload */
2582
+ get jwtPayload() {
2583
+ if (!this.token) return null;
2584
+ return jwtDecode(this.token);
2585
+ }
2586
+ _request(req, options = {}) {
2587
+ const token = options.token || this.token;
2588
+ return fetch(this.url, {
2589
+ method: "POST",
2590
+ headers: clean({
2591
+ Authorization: token ? `Bearer ${token}` : void 0,
2592
+ "Content-Type": "application/json",
2593
+ "X-Date-Return-Format": this.options.legacyDates ? void 0 : "ISO8601"
2594
+ }),
2595
+ body: JSON.stringify(Api.translateTokens(req))
2596
+ }).then(async (resp) => {
2597
+ let data = JSONAttemptParse(await resp.text());
2598
+ if (!resp.ok || (data == null ? void 0 : data.error)) throw Object.assign(errorFromCode(resp.status, data.error), data);
2599
+ if (!options.raw) data = Api.translateTokens(data);
2600
+ return data;
2601
+ });
2602
+ }
2603
+ /**
2604
+ * Parses API request/response object for special Datalynk tokens & converts them to native JS objects
2605
+ *
2606
+ * @param obj An API request or response
2607
+ * @return {Object} Api request or response with translated tokens
2608
+ * @private
2609
+ */
2610
+ static translateTokens(obj) {
2611
+ let dot = (obj2, param) => param.split(".").reduce((acc, index) => acc[index], obj2);
2612
+ let queue = Object.keys(obj);
2613
+ queue.forEach((key) => {
2614
+ let val = dot(obj, key);
2615
+ if (val !== null && typeof val == "object") {
2616
+ Object.keys(val).forEach((index) => {
2617
+ if (index in Serializer.deserialize) {
2618
+ val = Serializer.deserialize[index](val[index]);
2619
+ } else if (index in Serializer.serialize) {
2620
+ val = Serializer.serialize[index](val[index]);
2621
+ } else {
2622
+ queue.push(`${key}.${index}`);
2623
+ }
2624
+ });
2625
+ }
2626
+ });
2627
+ return obj;
2628
+ }
2629
+ /**
2630
+ * Chain multiple requests to execute together
2631
+ * @param {Slice<any>} requests List of requests to chain
2632
+ * @return {Promise<any>} API Response
2633
+ */
2634
+ chain(...requests) {
2635
+ const arr = requests.length == 1 && Array.isArray(requests[0]) ? requests[0] : requests;
2636
+ return this.request({ "$/tools/action_chain": arr.map((r) => {
2637
+ if (!(r instanceof Slice)) return r;
2638
+ const req = r.raw;
2639
+ Object.keys(req).forEach((key) => {
2640
+ if (key.startsWith("$/")) {
2641
+ req[key.replace("$", "!")] = req[key];
2642
+ delete req[key];
2643
+ }
2644
+ });
2645
+ return req;
2646
+ }) });
2647
+ }
2648
+ /**
2649
+ * Organize multiple requests into a single mapped request
2650
+ * @param {{[p: string]: any}} request Map of requests
2651
+ * @return {Promise<any>} Map of API Responses
2652
+ */
2653
+ chainMap(request) {
2654
+ return this.request({ "$/tools/do": [
2655
+ ...Object.entries(request).flatMap(([key, r]) => {
2656
+ if (!(r instanceof Slice)) return [key, r];
2657
+ const req = r.raw;
2658
+ Object.keys(req).forEach((key2) => {
2659
+ if (key2.startsWith("$/")) {
2660
+ req[key2.replace("$", "!")] = req[key2];
2661
+ delete req[key2];
2662
+ }
2663
+ });
2664
+ return [key, req];
2665
+ }),
2666
+ "returnAllBoilerplate",
2667
+ { "$_": "*" }
2668
+ ] }, {});
2669
+ }
2670
+ /**
2671
+ * Exact same as `request` method, but logs the response in the console automatically
2672
+ *
2673
+ * @param {object | string} data Datalynk request as object or string
2674
+ * @param {ApiRequestOptions} options
2675
+ * @returns {Promise<any>} Datalynk response
2676
+ */
2677
+ debug(data, options = {}) {
2678
+ return this.request(data, options).then((data2) => {
2679
+ console.log(data2);
2680
+ return data2;
2681
+ }).catch((err) => {
2682
+ console.error(err);
2683
+ return err;
2684
+ });
2685
+ }
2686
+ /**
2687
+ * Send a request to Datalynk
2688
+ *
2689
+ * @example
2690
+ * ```ts
2691
+ * const response = await api.request('$/auth/current');
2692
+ * ```
2693
+ *
2694
+ * @param {object} data Request using Datalynk API syntax. Strings will be converted: '$/auth/current' -> {'$/auth/current': {}}
2695
+ * @param {ApiRequestOptions} options
2696
+ * @returns {Promise<any>} Datalynk response or error
2697
+ */
2698
+ request(data, options = {}) {
2699
+ data = typeof data == "string" ? { [data]: {} } : data;
2700
+ if (options.noOptimize) {
2701
+ return new Promise((res, rej) => {
2702
+ this._request(data, options).then((resp) => {
2703
+ (resp == null ? void 0 : resp.error) ? rej(resp) : res(resp);
2704
+ }).catch((err) => rej(err));
2705
+ });
2706
+ }
2707
+ let key = JSON.stringify(data);
2708
+ if (!this.pending[key]) {
2709
+ this.pending[key] = new Promise((res, rej) => this.bundle.push({ data, res, rej }));
2710
+ this.pending[key].catch().then(() => delete this.pending[key]);
2711
+ if (!this.bundleOngoing) {
2712
+ this.bundleOngoing = true;
2713
+ setTimeout(() => {
2714
+ let originalBundle = this.bundle;
2715
+ this.bundle = [];
2716
+ this.bundleOngoing = false;
2717
+ data = originalBundle.map((row) => row.data);
2718
+ this._request(data, options).then((resp) => {
2719
+ if (!(resp instanceof Array)) resp = [resp];
2720
+ resp.forEach((row, i) => (row == null ? void 0 : row.error) ? originalBundle[i].rej(row.error) : originalBundle[i].res(row));
2721
+ }).catch((err) => originalBundle.forEach((req) => req.rej(err)));
2722
+ }, this.options.bundleTime);
2723
+ }
2724
+ }
2725
+ return this.pending[key];
2726
+ }
2727
+ /**
2728
+ * Create a slice object using the API
2729
+ *
2730
+ * @example
2731
+ * ```ts
2732
+ * const contactsSlice = api.slice<Contacts>(12345);
2733
+ * const allContacts = await contactsSlice.select().exec().rows();
2734
+ * const unsubscribe = contactsSlice.sync().subscribe(rows => console.log(rows));
2735
+ * ```
2736
+ *
2737
+ * @param {number} slice Slice number the object will target
2738
+ * @returns {Slice<T = any>} Object for making requests & caching rows
2739
+ */
2740
+ slice(slice) {
2741
+ return new Slice(slice, this);
2742
+ }
2743
+ }
2744
+ exports2.Api = Api;
2745
+ exports2.Auth = Auth;
2746
+ exports2.Files = Files;
2747
+ exports2.LoginPrompt = LoginPrompt;
2748
+ exports2.Pdf = Pdf;
2749
+ exports2.Serializer = Serializer;
2750
+ exports2.Slice = Slice;
2751
+ exports2.Socket = Socket;
2752
+ exports2.Superuser = Superuser;
2753
+ Object.defineProperty(exports2, Symbol.toStringTag, { value: "Module" });
2754
+ });