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