@auxilium/datalynk-client 1.0.13 → 1.0.15

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