@auxilium/datalynk-client 1.3.3 → 1.3.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,3990 @@
1
+ (function(global2, factory) {
2
+ typeof exports === "object" && typeof module !== "undefined" ? factory(exports) : typeof define === "function" && define.amd ? define(["exports"], factory) : (global2 = typeof globalThis !== "undefined" ? globalThis : global2 || self, factory(global2.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, value) => key in obj ? __defProp2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
10
+ var __publicField2 = (obj, key, value) => __defNormalProp2(obj, typeof key !== "symbol" ? key + "" : key, value);
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) => undefinedOnly ? o !== void 0 : o != null);
15
+ } else {
16
+ Object.entries(obj).forEach(([key, value]) => {
17
+ if (undefinedOnly && value === void 0 || !undefinedOnly && value == null) delete obj[key];
18
+ });
19
+ }
20
+ return obj;
21
+ }
22
+ function deepCopy(value) {
23
+ try {
24
+ return structuredClone(value);
25
+ } catch {
26
+ return JSON.parse(JSONSanitize(value));
27
+ }
28
+ }
29
+ function dotNotation(obj, prop, set) {
30
+ if (obj == null || !prop) return void 0;
31
+ return prop.split(/[.[\]]/g).filter((prop2) => prop2.length).reduce((obj2, prop2, i, arr) => {
32
+ if (prop2[0] == '"' || prop2[0] == "'") prop2 = prop2.slice(1, -1);
33
+ if (!(obj2 == null ? void 0 : obj2.hasOwnProperty(prop2))) {
34
+ return void 0;
35
+ }
36
+ return obj2[prop2];
37
+ }, obj);
38
+ }
39
+ function isEqual(a, b) {
40
+ const ta = typeof a, tb = typeof b;
41
+ if (ta != "object" || a == null || (tb != "object" || b == null))
42
+ return ta == "function" && tb == "function" ? a.toString() == b.toString() : a === b;
43
+ const keys = Object.keys(a);
44
+ if (keys.length != Object.keys(b).length) return false;
45
+ return Object.keys(a).every((key) => isEqual(a[key], b[key]));
46
+ }
47
+ function JSONAttemptParse(json) {
48
+ try {
49
+ return JSON.parse(json);
50
+ } catch {
51
+ return json;
52
+ }
53
+ }
54
+ function JSONSanitize(obj, space) {
55
+ const cache = [];
56
+ return JSON.stringify(obj, (key, value) => {
57
+ if (typeof value === "object" && value !== null) {
58
+ if (cache.includes(value)) return "[Circular]";
59
+ cache.push(value);
60
+ }
61
+ return value;
62
+ }, space);
63
+ }
64
+ class ASet extends Array {
65
+ /** Number of elements in set */
66
+ get size() {
67
+ return this.length;
68
+ }
69
+ /**
70
+ * Array to create set from, duplicate values will be removed
71
+ * @param {T[]} elements Elements which will be added to set
72
+ */
73
+ constructor(elements = []) {
74
+ super();
75
+ if (!!(elements == null ? void 0 : elements["forEach"]))
76
+ elements.forEach((el) => this.add(el));
77
+ }
78
+ /**
79
+ * Add elements to set if unique
80
+ * @param items
81
+ */
82
+ add(...items) {
83
+ items.filter((el) => !this.has(el)).forEach((el) => this.push(el));
84
+ return this;
85
+ }
86
+ /**
87
+ * Remove all elements
88
+ */
89
+ clear() {
90
+ this.splice(0, this.length);
91
+ return this;
92
+ }
93
+ /**
94
+ * Delete elements from set
95
+ * @param items Elements that will be deleted
96
+ */
97
+ delete(...items) {
98
+ items.forEach((el) => {
99
+ const index = this.indexOf(el);
100
+ if (index != -1) this.splice(index, 1);
101
+ });
102
+ return this;
103
+ }
104
+ /**
105
+ * Create list of elements this set has which the comparison set does not
106
+ * @param {ASet<T>} set Set to compare against
107
+ * @return {ASet<T>} Different elements
108
+ */
109
+ difference(set) {
110
+ return new ASet(this.filter((el) => !set.has(el)));
111
+ }
112
+ /**
113
+ * Check if set includes element
114
+ * @param {T} el Element to look for
115
+ * @return {boolean} True if element was found, false otherwise
116
+ */
117
+ has(el) {
118
+ return this.indexOf(el) != -1;
119
+ }
120
+ /**
121
+ * Find index number of element, or -1 if it doesn't exist. Matches by equality not reference
122
+ *
123
+ * @param {T} search Element to find
124
+ * @param {number} fromIndex Starting index position
125
+ * @return {number} Element index number or -1 if missing
126
+ */
127
+ indexOf(search2, fromIndex) {
128
+ return super.findIndex((el) => isEqual(el, search2), fromIndex);
129
+ }
130
+ /**
131
+ * Create list of elements this set has in common with the comparison set
132
+ * @param {ASet<T>} set Set to compare against
133
+ * @return {boolean} Set of common elements
134
+ */
135
+ intersection(set) {
136
+ return new ASet(this.filter((el) => set.has(el)));
137
+ }
138
+ /**
139
+ * Check if this set has no elements in common with the comparison set
140
+ * @param {ASet<T>} set Set to compare against
141
+ * @return {boolean} True if nothing in common, false otherwise
142
+ */
143
+ isDisjointFrom(set) {
144
+ return this.intersection(set).size == 0;
145
+ }
146
+ /**
147
+ * Check if all elements in this set are included in the comparison set
148
+ * @param {ASet<T>} set Set to compare against
149
+ * @return {boolean} True if all elements are included, false otherwise
150
+ */
151
+ isSubsetOf(set) {
152
+ return this.findIndex((el) => !set.has(el)) == -1;
153
+ }
154
+ /**
155
+ * Check if all elements from comparison set are included in this set
156
+ * @param {ASet<T>} set Set to compare against
157
+ * @return {boolean} True if all elements are included, false otherwise
158
+ */
159
+ isSuperset(set) {
160
+ return set.findIndex((el) => !this.has(el)) == -1;
161
+ }
162
+ /**
163
+ * Create list of elements that are only in one set but not both (XOR)
164
+ * @param {ASet<T>} set Set to compare against
165
+ * @return {ASet<T>} New set of unique elements
166
+ */
167
+ symmetricDifference(set) {
168
+ return new ASet([...this.difference(set), ...set.difference(this)]);
169
+ }
170
+ /**
171
+ * Create joined list of elements included in this & the comparison set
172
+ * @param {ASet<T>} set Set join
173
+ * @return {ASet<T>} New set of both previous sets combined
174
+ */
175
+ union(set) {
176
+ return new ASet([...this, ...set]);
177
+ }
178
+ }
179
+ function sortByProp(prop, reverse = false) {
180
+ return function(a, b) {
181
+ const aVal = dotNotation(a, prop);
182
+ const bVal = dotNotation(b, prop);
183
+ if (typeof aVal == "number" && typeof bVal == "number")
184
+ return (reverse ? -1 : 1) * (aVal - bVal);
185
+ if (aVal > bVal) return reverse ? -1 : 1;
186
+ if (aVal < bVal) return reverse ? 1 : -1;
187
+ return 0;
188
+ };
189
+ }
190
+ function makeArray(value) {
191
+ return Array.isArray(value) ? value : [value];
192
+ }
193
+ class Database {
194
+ constructor(database, tables, version2) {
195
+ __publicField2(this, "connection");
196
+ __publicField2(this, "tables");
197
+ this.database = database;
198
+ this.version = version2;
199
+ this.connection = new Promise((resolve, reject) => {
200
+ const req = indexedDB.open(this.database, this.version);
201
+ this.tables = tables.map((t) => {
202
+ t = typeof t == "object" ? t : { name: t };
203
+ return { ...t, name: t.name.toString() };
204
+ });
205
+ const tableNames = new ASet(this.tables.map((t) => t.name));
206
+ req.onerror = () => reject(req.error);
207
+ req.onsuccess = () => {
208
+ const db = req.result;
209
+ if (tableNames.symmetricDifference(new ASet(Array.from(db.objectStoreNames))).length) {
210
+ db.close();
211
+ Object.assign(this, new Database(this.database, this.tables, db.version + 1));
212
+ } else {
213
+ this.version = db.version;
214
+ resolve(db);
215
+ }
216
+ };
217
+ req.onupgradeneeded = () => {
218
+ const db = req.result;
219
+ const existingTables = new ASet(Array.from(db.objectStoreNames));
220
+ existingTables.difference(tableNames).forEach((name) => db.deleteObjectStore(name));
221
+ tableNames.difference(existingTables).forEach((name) => db.createObjectStore(name));
222
+ };
223
+ });
224
+ }
225
+ includes(name) {
226
+ return !!this.tables.find((t) => t.name == name.toString());
227
+ }
228
+ table(name) {
229
+ return new Table(this, name.toString());
230
+ }
231
+ }
232
+ class Table {
233
+ constructor(database, name) {
234
+ this.database = database;
235
+ this.name = name;
236
+ }
237
+ async tx(table, fn2, readonly = false) {
238
+ const db = await this.database.connection;
239
+ const tx = db.transaction(table, readonly ? "readonly" : "readwrite");
240
+ const store = tx.objectStore(table);
241
+ return new Promise((resolve, reject) => {
242
+ const request = fn2(store);
243
+ request.onsuccess = () => resolve(request.result);
244
+ request.onerror = () => reject(request.error);
245
+ });
246
+ }
247
+ add(value, key) {
248
+ return this.tx(this.name, (store) => store.add(value, key));
249
+ }
250
+ count() {
251
+ return this.tx(this.name, (store) => store.count(), true);
252
+ }
253
+ put(key, value) {
254
+ return this.tx(this.name, (store) => store.put(value, key));
255
+ }
256
+ getAll() {
257
+ return this.tx(this.name, (store) => store.getAll(), true);
258
+ }
259
+ getAllKeys() {
260
+ return this.tx(this.name, (store) => store.getAllKeys(), true);
261
+ }
262
+ get(key) {
263
+ return this.tx(this.name, (store) => store.get(key), true);
264
+ }
265
+ delete(key) {
266
+ return this.tx(this.name, (store) => store.delete(key));
267
+ }
268
+ clear() {
269
+ return this.tx(this.name, (store) => store.clear());
270
+ }
271
+ }
272
+ function contrast(background) {
273
+ const exploded = background == null ? void 0 : background.match(background.length >= 6 ? /[0-9a-fA-F]{2}/g : /[0-9a-fA-F]/g);
274
+ if (!exploded || (exploded == null ? void 0 : exploded.length) < 3) return "black";
275
+ const [r, g, b] = exploded.map((hex) => parseInt(hex.length == 1 ? `${hex}${hex}` : hex, 16));
276
+ const luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255;
277
+ return luminance > 0.5 ? "black" : "white";
278
+ }
279
+ const LETTER_LIST = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
280
+ const NUMBER_LIST = "0123456789";
281
+ const SYMBOL_LIST = "~`!@#$%^&*()_-+={[}]|\\:;\"'<,>.?/";
282
+ function randomStringBuilder(length, letters = false, numbers = false, symbols = false) {
283
+ if (!letters && !numbers && !symbols) throw new Error("Must enable at least one: letters, numbers, symbols");
284
+ return Array(length).fill(null).map(() => {
285
+ let c;
286
+ do {
287
+ const type = ~~(Math.random() * 3);
288
+ if (letters && type == 0) {
289
+ c = LETTER_LIST[~~(Math.random() * LETTER_LIST.length)];
290
+ } else if (numbers && type == 1) {
291
+ c = NUMBER_LIST[~~(Math.random() * NUMBER_LIST.length)];
292
+ } else if (symbols && type == 2) {
293
+ c = SYMBOL_LIST[~~(Math.random() * SYMBOL_LIST.length)];
294
+ }
295
+ } while (!c);
296
+ return c;
297
+ }).join("");
298
+ }
299
+ class PromiseProgress extends Promise {
300
+ constructor(executor) {
301
+ super((resolve, reject) => executor(
302
+ (value) => resolve(value),
303
+ (reason) => reject(reason),
304
+ (progress) => this.progress = progress
305
+ ));
306
+ __publicField2(this, "listeners", []);
307
+ __publicField2(this, "_progress", 0);
308
+ }
309
+ get progress() {
310
+ return this._progress;
311
+ }
312
+ set progress(p) {
313
+ if (p == this._progress) return;
314
+ this._progress = p;
315
+ this.listeners.forEach((l) => l(p));
316
+ }
317
+ static from(promise) {
318
+ if (promise instanceof PromiseProgress) return promise;
319
+ return new PromiseProgress((res, rej) => promise.then((...args) => res(...args)).catch((...args) => rej(...args)));
320
+ }
321
+ from(promise) {
322
+ const newPromise = PromiseProgress.from(promise);
323
+ this.onProgress((p) => newPromise.progress = p);
324
+ return newPromise;
325
+ }
326
+ onProgress(callback) {
327
+ this.listeners.push(callback);
328
+ return this;
329
+ }
330
+ then(res, rej) {
331
+ const resp = super.then(res, rej);
332
+ return this.from(resp);
333
+ }
334
+ catch(rej) {
335
+ return this.from(super.catch(rej));
336
+ }
337
+ finally(res) {
338
+ return this.from(super.finally(res));
339
+ }
340
+ }
341
+ function sleep(ms) {
342
+ return new Promise((res) => setTimeout(res, ms));
343
+ }
344
+ async function sleepWhile(fn2, checkInterval = 100) {
345
+ while (await fn2()) await sleep(checkInterval);
346
+ }
347
+ class TypedEmitter {
348
+ constructor() {
349
+ __publicField2(this, "listeners", {});
350
+ }
351
+ static emit(event, ...args) {
352
+ (this.listeners["*"] || []).forEach((l) => l(event, ...args));
353
+ (this.listeners[event.toString()] || []).forEach((l) => l(...args));
354
+ }
355
+ static off(event, listener) {
356
+ const e = event.toString();
357
+ this.listeners[e] = (this.listeners[e] || []).filter((l) => l != listener);
358
+ }
359
+ static on(event, listener) {
360
+ var _a;
361
+ const e = event.toString();
362
+ if (!this.listeners[e]) this.listeners[e] = [];
363
+ (_a = this.listeners[e]) == null ? void 0 : _a.push(listener);
364
+ return () => this.off(event, listener);
365
+ }
366
+ static once(event, listener) {
367
+ return new Promise((res) => {
368
+ const unsubscribe = this.on(event, (...args) => {
369
+ res(args.length == 1 ? args[0] : args);
370
+ if (listener) listener(...args);
371
+ unsubscribe();
372
+ });
373
+ });
374
+ }
375
+ emit(event, ...args) {
376
+ (this.listeners["*"] || []).forEach((l) => l(event, ...args));
377
+ (this.listeners[event] || []).forEach((l) => l(...args));
378
+ }
379
+ off(event, listener) {
380
+ this.listeners[event] = (this.listeners[event] || []).filter((l) => l != listener);
381
+ }
382
+ on(event, listener) {
383
+ var _a;
384
+ if (!this.listeners[event]) this.listeners[event] = [];
385
+ (_a = this.listeners[event]) == null ? void 0 : _a.push(listener);
386
+ return () => this.off(event, listener);
387
+ }
388
+ once(event, listener) {
389
+ return new Promise((res) => {
390
+ const unsubscribe = this.on(event, (...args) => {
391
+ res(args.length == 1 ? args[0] : args);
392
+ if (listener) listener(...args);
393
+ unsubscribe();
394
+ });
395
+ });
396
+ }
397
+ }
398
+ __publicField2(TypedEmitter, "listeners", {});
399
+ class CustomError extends Error {
400
+ constructor(message, code) {
401
+ super(message);
402
+ __publicField2(this, "_code");
403
+ if (code != null) this._code = code;
404
+ }
405
+ get code() {
406
+ return this._code || this.constructor.code;
407
+ }
408
+ set code(c) {
409
+ this._code = c;
410
+ }
411
+ static from(err) {
412
+ const code = Number(err.statusCode) ?? Number(err.code);
413
+ const newErr = new this(err.message || err.toString());
414
+ return Object.assign(newErr, {
415
+ stack: err.stack,
416
+ ...err,
417
+ code: code ?? void 0
418
+ });
419
+ }
420
+ static instanceof(err) {
421
+ return err.constructor.code != void 0;
422
+ }
423
+ toString() {
424
+ return this.message || super.toString();
425
+ }
426
+ }
427
+ __publicField2(CustomError, "code", 500);
428
+ class BadRequestError extends CustomError {
429
+ constructor(message = "Bad Request") {
430
+ super(message);
431
+ }
432
+ static instanceof(err) {
433
+ return err.constructor.code == this.code;
434
+ }
435
+ }
436
+ __publicField2(BadRequestError, "code", 400);
437
+ class UnauthorizedError extends CustomError {
438
+ constructor(message = "Unauthorized") {
439
+ super(message);
440
+ }
441
+ static instanceof(err) {
442
+ return err.constructor.code == this.code;
443
+ }
444
+ }
445
+ __publicField2(UnauthorizedError, "code", 401);
446
+ class PaymentRequiredError extends CustomError {
447
+ constructor(message = "Payment Required") {
448
+ super(message);
449
+ }
450
+ static instanceof(err) {
451
+ return err.constructor.code == this.code;
452
+ }
453
+ }
454
+ __publicField2(PaymentRequiredError, "code", 402);
455
+ class ForbiddenError extends CustomError {
456
+ constructor(message = "Forbidden") {
457
+ super(message);
458
+ }
459
+ static instanceof(err) {
460
+ return err.constructor.code == this.code;
461
+ }
462
+ }
463
+ __publicField2(ForbiddenError, "code", 403);
464
+ class NotFoundError extends CustomError {
465
+ constructor(message = "Not Found") {
466
+ super(message);
467
+ }
468
+ static instanceof(err) {
469
+ return err.constructor.code == this.code;
470
+ }
471
+ }
472
+ __publicField2(NotFoundError, "code", 404);
473
+ class MethodNotAllowedError extends CustomError {
474
+ constructor(message = "Method Not Allowed") {
475
+ super(message);
476
+ }
477
+ static instanceof(err) {
478
+ return err.constructor.code == this.code;
479
+ }
480
+ }
481
+ __publicField2(MethodNotAllowedError, "code", 405);
482
+ class NotAcceptableError extends CustomError {
483
+ constructor(message = "Not Acceptable") {
484
+ super(message);
485
+ }
486
+ static instanceof(err) {
487
+ return err.constructor.code == this.code;
488
+ }
489
+ }
490
+ __publicField2(NotAcceptableError, "code", 406);
491
+ class InternalServerError extends CustomError {
492
+ constructor(message = "Internal Server Error") {
493
+ super(message);
494
+ }
495
+ static instanceof(err) {
496
+ return err.constructor.code == this.code;
497
+ }
498
+ }
499
+ __publicField2(InternalServerError, "code", 500);
500
+ class NotImplementedError extends CustomError {
501
+ constructor(message = "Not Implemented") {
502
+ super(message);
503
+ }
504
+ static instanceof(err) {
505
+ return err.constructor.code == this.code;
506
+ }
507
+ }
508
+ __publicField2(NotImplementedError, "code", 501);
509
+ class BadGatewayError extends CustomError {
510
+ constructor(message = "Bad Gateway") {
511
+ super(message);
512
+ }
513
+ static instanceof(err) {
514
+ return err.constructor.code == this.code;
515
+ }
516
+ }
517
+ __publicField2(BadGatewayError, "code", 502);
518
+ class ServiceUnavailableError extends CustomError {
519
+ constructor(message = "Service Unavailable") {
520
+ super(message);
521
+ }
522
+ static instanceof(err) {
523
+ return err.constructor.code == this.code;
524
+ }
525
+ }
526
+ __publicField2(ServiceUnavailableError, "code", 503);
527
+ class GatewayTimeoutError extends CustomError {
528
+ constructor(message = "Gateway Timeout") {
529
+ super(message);
530
+ }
531
+ static instanceof(err) {
532
+ return err.constructor.code == this.code;
533
+ }
534
+ }
535
+ __publicField2(GatewayTimeoutError, "code", 504);
536
+ function errorFromCode(code, message) {
537
+ switch (code) {
538
+ case 400:
539
+ return new BadRequestError(message);
540
+ case 401:
541
+ return new UnauthorizedError(message);
542
+ case 402:
543
+ return new PaymentRequiredError(message);
544
+ case 403:
545
+ return new ForbiddenError(message);
546
+ case 404:
547
+ return new NotFoundError(message);
548
+ case 405:
549
+ return new MethodNotAllowedError(message);
550
+ case 406:
551
+ return new NotAcceptableError(message);
552
+ case 500:
553
+ return new InternalServerError(message);
554
+ case 501:
555
+ return new NotImplementedError(message);
556
+ case 502:
557
+ return new BadGatewayError(message);
558
+ case 503:
559
+ return new ServiceUnavailableError(message);
560
+ case 504:
561
+ return new GatewayTimeoutError(message);
562
+ default:
563
+ return new CustomError(message, code);
564
+ }
565
+ }
566
+ class HttpResponse extends Response {
567
+ constructor(resp, stream) {
568
+ const body = [204, 205, 304].includes(resp.status) ? null : stream;
569
+ super(body, {
570
+ headers: resp.headers,
571
+ status: resp.status,
572
+ statusText: resp.statusText
573
+ });
574
+ __publicField2(this, "data");
575
+ __publicField2(this, "ok");
576
+ __publicField2(this, "redirected");
577
+ __publicField2(this, "type");
578
+ __publicField2(this, "url");
579
+ this.ok = resp.ok;
580
+ this.redirected = resp.redirected;
581
+ this.type = resp.type;
582
+ this.url = resp.url;
583
+ }
584
+ }
585
+ const _Http = class _Http2 {
586
+ constructor(defaults = {}) {
587
+ __publicField2(this, "interceptors", {});
588
+ __publicField2(this, "headers", {});
589
+ __publicField2(this, "url");
590
+ this.url = defaults.url ?? null;
591
+ this.headers = defaults.headers || {};
592
+ if (defaults.interceptors) {
593
+ defaults.interceptors.forEach((i) => _Http2.addInterceptor(i));
594
+ }
595
+ }
596
+ static addInterceptor(fn2) {
597
+ const key = Object.keys(_Http2.interceptors).length.toString();
598
+ _Http2.interceptors[key] = fn2;
599
+ return () => {
600
+ _Http2.interceptors[key] = null;
601
+ };
602
+ }
603
+ addInterceptor(fn2) {
604
+ const key = Object.keys(this.interceptors).length.toString();
605
+ this.interceptors[key] = fn2;
606
+ return () => {
607
+ this.interceptors[key] = null;
608
+ };
609
+ }
610
+ request(opts = {}) {
611
+ var _a;
612
+ if (!this.url && !opts.url) throw new Error("URL needs to be set");
613
+ let url = ((_a = opts.url) == null ? void 0 : _a.startsWith("http")) ? opts.url : (this.url || "") + (opts.url || "");
614
+ url = url.replaceAll(/([^:]\/)\/+/g, "$1");
615
+ if (opts.fragment) url.includes("#") ? url.replace(/#.*(\?|\n)/g, (match, arg1) => `#${opts.fragment}${arg1}`) : `${url}#${opts.fragment}`;
616
+ if (opts.query) {
617
+ const q = Array.isArray(opts.query) ? opts.query : Object.keys(opts.query).map((k) => ({ key: k, value: opts.query[k] }));
618
+ url += (url.includes("?") ? "&" : "?") + q.map((q2) => `${q2.key}=${q2.value}`).join("&");
619
+ }
620
+ const headers = clean({
621
+ "Content-Type": !opts.body ? void 0 : opts.body instanceof FormData ? "multipart/form-data" : "application/json",
622
+ ..._Http2.headers,
623
+ ...this.headers,
624
+ ...opts.headers
625
+ });
626
+ if (typeof opts.body == "object" && opts.body != null && headers["Content-Type"] == "application/json")
627
+ opts.body = JSON.stringify(opts.body);
628
+ return new PromiseProgress((res, rej, prog) => {
629
+ try {
630
+ fetch(url, {
631
+ headers,
632
+ method: opts.method || (opts.body ? "POST" : "GET"),
633
+ body: opts.body
634
+ }).then(async (resp) => {
635
+ var _a2, _b;
636
+ for (let fn2 of [...Object.values(_Http2.interceptors), ...Object.values(this.interceptors)]) {
637
+ await new Promise((res2) => fn2(resp, () => res2()));
638
+ }
639
+ const contentLength = resp.headers.get("Content-Length");
640
+ const total = contentLength ? parseInt(contentLength, 10) : 0;
641
+ let loaded = 0;
642
+ const reader = (_a2 = resp.body) == null ? void 0 : _a2.getReader();
643
+ const stream = new ReadableStream({
644
+ start(controller) {
645
+ function push() {
646
+ reader == null ? void 0 : reader.read().then((event) => {
647
+ if (event.done) return controller.close();
648
+ loaded += event.value.byteLength;
649
+ prog(loaded / total);
650
+ controller.enqueue(event.value);
651
+ push();
652
+ }).catch((error) => controller.error(error));
653
+ }
654
+ push();
655
+ }
656
+ });
657
+ resp = new HttpResponse(resp, stream);
658
+ if (opts.decode !== false) {
659
+ const content = (_b = resp.headers.get("Content-Type")) == null ? void 0 : _b.toLowerCase();
660
+ if (content == null ? void 0 : content.includes("form")) resp.data = await resp.formData();
661
+ else if (content == null ? void 0 : content.includes("json")) resp.data = await resp.json();
662
+ else if (content == null ? void 0 : content.includes("text")) resp.data = await resp.text();
663
+ else if (content == null ? void 0 : content.includes("application")) resp.data = await resp.blob();
664
+ }
665
+ if (resp.ok) res(resp);
666
+ else rej(resp);
667
+ }).catch((err) => rej(err));
668
+ } catch (err) {
669
+ rej(err);
670
+ }
671
+ });
672
+ }
673
+ };
674
+ __publicField2(_Http, "interceptors", {});
675
+ __publicField2(_Http, "headers", {});
676
+ function decodeJwt(token) {
677
+ const base64 = token.split(".")[1].replace(/-/g, "+").replace(/_/g, "/");
678
+ return JSONAttemptParse(decodeURIComponent(atob(base64).split("").map(function(c) {
679
+ return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2);
680
+ }).join("")));
681
+ }
682
+ const CliEffects = {
683
+ CLEAR: "\x1B[0m"
684
+ };
685
+ const CliForeground = {
686
+ RED: "\x1B[31m",
687
+ YELLOW: "\x1B[33m",
688
+ BLUE: "\x1B[34m",
689
+ LIGHT_GREY: "\x1B[37m"
690
+ };
691
+ const _Logger = class _Logger2 extends TypedEmitter {
692
+ constructor(namespace) {
693
+ super();
694
+ this.namespace = namespace;
695
+ }
696
+ format(...text) {
697
+ const now = /* @__PURE__ */ new Date();
698
+ 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")}`;
699
+ return `${timestamp}${this.namespace ? ` [${this.namespace}]` : ""} ${text.map((t) => typeof t == "string" ? t : JSONSanitize(t, 2)).join(" ")}`;
700
+ }
701
+ debug(...args) {
702
+ if (_Logger2.LOG_LEVEL < 4) return;
703
+ const str = this.format(...args);
704
+ _Logger2.emit(4, str);
705
+ console.debug(CliForeground.LIGHT_GREY + str + CliEffects.CLEAR);
706
+ }
707
+ log(...args) {
708
+ if (_Logger2.LOG_LEVEL < 3) return;
709
+ const str = this.format(...args);
710
+ _Logger2.emit(3, str);
711
+ console.log(CliEffects.CLEAR + str);
712
+ }
713
+ info(...args) {
714
+ if (_Logger2.LOG_LEVEL < 2) return;
715
+ const str = this.format(...args);
716
+ _Logger2.emit(2, str);
717
+ console.info(CliForeground.BLUE + str + CliEffects.CLEAR);
718
+ }
719
+ warn(...args) {
720
+ if (_Logger2.LOG_LEVEL < 1) return;
721
+ const str = this.format(...args);
722
+ _Logger2.emit(1, str);
723
+ console.warn(CliForeground.YELLOW + str + CliEffects.CLEAR);
724
+ }
725
+ error(...args) {
726
+ if (_Logger2.LOG_LEVEL < 0) return;
727
+ const str = this.format(...args);
728
+ _Logger2.emit(0, str);
729
+ console.error(CliForeground.RED + str + CliEffects.CLEAR);
730
+ }
731
+ };
732
+ __publicField2(_Logger, "LOG_LEVEL", 4);
733
+ var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {};
734
+ var dist = {};
735
+ var persist$1 = {};
736
+ Object.defineProperty(persist$1, "__esModule", { value: true });
737
+ persist$1.persist = persist$1.Persist = void 0;
738
+ class Persist {
739
+ /**
740
+ * @param {string} key Primary key value will be stored under
741
+ * @param {PersistOptions<T>} options Configure using {@link PersistOptions}
742
+ */
743
+ constructor(key, options = {}) {
744
+ __publicField2(this, "key");
745
+ __publicField2(this, "options");
746
+ __publicField2(this, "storage");
747
+ __publicField2(this, "watches", {});
748
+ __publicField2(this, "_value");
749
+ this.key = key;
750
+ this.options = options;
751
+ this.storage = options.storage || localStorage;
752
+ this.load();
753
+ }
754
+ /** Current value or default if undefined */
755
+ get value() {
756
+ var _a;
757
+ return this._value !== void 0 ? this._value : (_a = this.options) == null ? void 0 : _a.default;
758
+ }
759
+ /** Set value with proxy object wrapper to sync future changes */
760
+ set value(v) {
761
+ if (v == null || typeof v != "object")
762
+ this._value = v;
763
+ else
764
+ this._value = new Proxy(v, {
765
+ get: (target, p) => {
766
+ const f = typeof target[p] == "function";
767
+ if (!f)
768
+ return target[p];
769
+ return (...args) => {
770
+ const value = target[p](...args);
771
+ this.save();
772
+ return value;
773
+ };
774
+ },
775
+ set: (target, p, newValue) => {
776
+ target[p] = newValue;
777
+ this.save();
778
+ return true;
779
+ }
780
+ });
781
+ this.save();
782
+ }
783
+ /** Notify listeners of change */
784
+ notify(value) {
785
+ Object.values(this.watches).forEach((watch) => watch(value));
786
+ }
787
+ /** Delete value from storage */
788
+ clear() {
789
+ this.storage.removeItem(this.key);
790
+ }
791
+ /** Save current value to storage */
792
+ save() {
793
+ if (this._value === void 0)
794
+ this.clear();
795
+ else
796
+ this.storage.setItem(this.key, JSON.stringify(this._value));
797
+ this.notify(this.value);
798
+ }
799
+ /** Load value from storage */
800
+ load() {
801
+ if (this.storage[this.key] != void 0) {
802
+ let value = JSON.parse(this.storage.getItem(this.key));
803
+ if (value != null && typeof value == "object" && this.options.type)
804
+ value.__proto__ = this.options.type.prototype;
805
+ this.value = value;
806
+ } else
807
+ this.value = this.options.default || void 0;
808
+ }
809
+ /**
810
+ * Callback function which is run when there are changes
811
+ *
812
+ * @param {(value: T) => any} fn Callback will run on each change; it's passed the next value & it's return is ignored
813
+ * @returns {() => void} Function which will unsubscribe the watch/callback when called
814
+ */
815
+ watch(fn2) {
816
+ const index = Object.keys(this.watches).length;
817
+ this.watches[index] = fn2;
818
+ return () => {
819
+ delete this.watches[index];
820
+ };
821
+ }
822
+ /**
823
+ * Return value as JSON string
824
+ *
825
+ * @returns {string} Stringified object as JSON
826
+ */
827
+ toString() {
828
+ return JSON.stringify(this.value);
829
+ }
830
+ /**
831
+ * Return current value
832
+ *
833
+ * @returns {T} Current value
834
+ */
835
+ valueOf() {
836
+ return this.value;
837
+ }
838
+ }
839
+ persist$1.Persist = Persist;
840
+ function persist(options) {
841
+ return (target, prop) => {
842
+ const key = (options == null ? void 0 : options.key) || `${target.constructor.name}.${prop.toString()}`;
843
+ const wrapper = new Persist(key, options);
844
+ Object.defineProperty(target, prop, {
845
+ get: function() {
846
+ return wrapper.value;
847
+ },
848
+ set: function(v) {
849
+ wrapper.value = v;
850
+ }
851
+ });
852
+ };
853
+ }
854
+ persist$1.persist = persist;
855
+ var memoryStorage = {};
856
+ Object.defineProperty(memoryStorage, "__esModule", { value: true });
857
+ memoryStorage.MemoryStorage = void 0;
858
+ class MemoryStorage {
859
+ get length() {
860
+ return Object.keys(this).length;
861
+ }
862
+ clear() {
863
+ Object.keys(this).forEach((k) => this.removeItem(k));
864
+ }
865
+ getItem(key) {
866
+ return this[key];
867
+ }
868
+ key(index) {
869
+ return Object.keys(this)[index];
870
+ }
871
+ removeItem(key) {
872
+ delete this[key];
873
+ }
874
+ setItem(key, value) {
875
+ this[key] = value;
876
+ }
877
+ }
878
+ memoryStorage.MemoryStorage = MemoryStorage;
879
+ (function(exports3) {
880
+ var __createBinding = commonjsGlobal && commonjsGlobal.__createBinding || (Object.create ? function(o, m, k, k2) {
881
+ if (k2 === void 0) k2 = k;
882
+ var desc = Object.getOwnPropertyDescriptor(m, k);
883
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
884
+ desc = { enumerable: true, get: function() {
885
+ return m[k];
886
+ } };
887
+ }
888
+ Object.defineProperty(o, k2, desc);
889
+ } : function(o, m, k, k2) {
890
+ if (k2 === void 0) k2 = k;
891
+ o[k2] = m[k];
892
+ });
893
+ var __exportStar = commonjsGlobal && commonjsGlobal.__exportStar || function(m, exports22) {
894
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports22, p)) __createBinding(exports22, m, p);
895
+ };
896
+ Object.defineProperty(exports3, "__esModule", { value: true });
897
+ __exportStar(persist$1, exports3);
898
+ __exportStar(memoryStorage, exports3);
899
+ })(dist);
900
+ var extendStatics = function(d, b) {
901
+ extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
902
+ d2.__proto__ = b2;
903
+ } || function(d2, b2) {
904
+ for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p];
905
+ };
906
+ return extendStatics(d, b);
907
+ };
908
+ function __extends(d, b) {
909
+ if (typeof b !== "function" && b !== null)
910
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
911
+ extendStatics(d, b);
912
+ function __() {
913
+ this.constructor = d;
914
+ }
915
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
916
+ }
917
+ function __values(o) {
918
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
919
+ if (m) return m.call(o);
920
+ if (o && typeof o.length === "number") return {
921
+ next: function() {
922
+ if (o && i >= o.length) o = void 0;
923
+ return { value: o && o[i++], done: !o };
924
+ }
925
+ };
926
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
927
+ }
928
+ function __read(o, n) {
929
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
930
+ if (!m) return o;
931
+ var i = m.call(o), r, ar = [], e;
932
+ try {
933
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
934
+ } catch (error) {
935
+ e = { error };
936
+ } finally {
937
+ try {
938
+ if (r && !r.done && (m = i["return"])) m.call(i);
939
+ } finally {
940
+ if (e) throw e.error;
941
+ }
942
+ }
943
+ return ar;
944
+ }
945
+ function __spreadArray(to, from, pack) {
946
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
947
+ if (ar || !(i in from)) {
948
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
949
+ ar[i] = from[i];
950
+ }
951
+ }
952
+ return to.concat(ar || Array.prototype.slice.call(from));
953
+ }
954
+ typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
955
+ var e = new Error(message);
956
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
957
+ };
958
+ function isFunction(value) {
959
+ return typeof value === "function";
960
+ }
961
+ function createErrorClass(createImpl) {
962
+ var _super = function(instance) {
963
+ Error.call(instance);
964
+ instance.stack = new Error().stack;
965
+ };
966
+ var ctorFunc = createImpl(_super);
967
+ ctorFunc.prototype = Object.create(Error.prototype);
968
+ ctorFunc.prototype.constructor = ctorFunc;
969
+ return ctorFunc;
970
+ }
971
+ var UnsubscriptionError = createErrorClass(function(_super) {
972
+ return function UnsubscriptionErrorImpl(errors) {
973
+ _super(this);
974
+ this.message = errors ? errors.length + " errors occurred during unsubscription:\n" + errors.map(function(err, i) {
975
+ return i + 1 + ") " + err.toString();
976
+ }).join("\n ") : "";
977
+ this.name = "UnsubscriptionError";
978
+ this.errors = errors;
979
+ };
980
+ });
981
+ function arrRemove(arr, item) {
982
+ if (arr) {
983
+ var index = arr.indexOf(item);
984
+ 0 <= index && arr.splice(index, 1);
985
+ }
986
+ }
987
+ var Subscription = function() {
988
+ function Subscription2(initialTeardown) {
989
+ this.initialTeardown = initialTeardown;
990
+ this.closed = false;
991
+ this._parentage = null;
992
+ this._finalizers = null;
993
+ }
994
+ Subscription2.prototype.unsubscribe = function() {
995
+ var e_1, _a, e_2, _b;
996
+ var errors;
997
+ if (!this.closed) {
998
+ this.closed = true;
999
+ var _parentage = this._parentage;
1000
+ if (_parentage) {
1001
+ this._parentage = null;
1002
+ if (Array.isArray(_parentage)) {
1003
+ try {
1004
+ for (var _parentage_1 = __values(_parentage), _parentage_1_1 = _parentage_1.next(); !_parentage_1_1.done; _parentage_1_1 = _parentage_1.next()) {
1005
+ var parent_1 = _parentage_1_1.value;
1006
+ parent_1.remove(this);
1007
+ }
1008
+ } catch (e_1_1) {
1009
+ e_1 = { error: e_1_1 };
1010
+ } finally {
1011
+ try {
1012
+ if (_parentage_1_1 && !_parentage_1_1.done && (_a = _parentage_1.return)) _a.call(_parentage_1);
1013
+ } finally {
1014
+ if (e_1) throw e_1.error;
1015
+ }
1016
+ }
1017
+ } else {
1018
+ _parentage.remove(this);
1019
+ }
1020
+ }
1021
+ var initialFinalizer = this.initialTeardown;
1022
+ if (isFunction(initialFinalizer)) {
1023
+ try {
1024
+ initialFinalizer();
1025
+ } catch (e) {
1026
+ errors = e instanceof UnsubscriptionError ? e.errors : [e];
1027
+ }
1028
+ }
1029
+ var _finalizers = this._finalizers;
1030
+ if (_finalizers) {
1031
+ this._finalizers = null;
1032
+ try {
1033
+ for (var _finalizers_1 = __values(_finalizers), _finalizers_1_1 = _finalizers_1.next(); !_finalizers_1_1.done; _finalizers_1_1 = _finalizers_1.next()) {
1034
+ var finalizer = _finalizers_1_1.value;
1035
+ try {
1036
+ execFinalizer(finalizer);
1037
+ } catch (err) {
1038
+ errors = errors !== null && errors !== void 0 ? errors : [];
1039
+ if (err instanceof UnsubscriptionError) {
1040
+ errors = __spreadArray(__spreadArray([], __read(errors)), __read(err.errors));
1041
+ } else {
1042
+ errors.push(err);
1043
+ }
1044
+ }
1045
+ }
1046
+ } catch (e_2_1) {
1047
+ e_2 = { error: e_2_1 };
1048
+ } finally {
1049
+ try {
1050
+ if (_finalizers_1_1 && !_finalizers_1_1.done && (_b = _finalizers_1.return)) _b.call(_finalizers_1);
1051
+ } finally {
1052
+ if (e_2) throw e_2.error;
1053
+ }
1054
+ }
1055
+ }
1056
+ if (errors) {
1057
+ throw new UnsubscriptionError(errors);
1058
+ }
1059
+ }
1060
+ };
1061
+ Subscription2.prototype.add = function(teardown) {
1062
+ var _a;
1063
+ if (teardown && teardown !== this) {
1064
+ if (this.closed) {
1065
+ execFinalizer(teardown);
1066
+ } else {
1067
+ if (teardown instanceof Subscription2) {
1068
+ if (teardown.closed || teardown._hasParent(this)) {
1069
+ return;
1070
+ }
1071
+ teardown._addParent(this);
1072
+ }
1073
+ (this._finalizers = (_a = this._finalizers) !== null && _a !== void 0 ? _a : []).push(teardown);
1074
+ }
1075
+ }
1076
+ };
1077
+ Subscription2.prototype._hasParent = function(parent2) {
1078
+ var _parentage = this._parentage;
1079
+ return _parentage === parent2 || Array.isArray(_parentage) && _parentage.includes(parent2);
1080
+ };
1081
+ Subscription2.prototype._addParent = function(parent2) {
1082
+ var _parentage = this._parentage;
1083
+ this._parentage = Array.isArray(_parentage) ? (_parentage.push(parent2), _parentage) : _parentage ? [_parentage, parent2] : parent2;
1084
+ };
1085
+ Subscription2.prototype._removeParent = function(parent2) {
1086
+ var _parentage = this._parentage;
1087
+ if (_parentage === parent2) {
1088
+ this._parentage = null;
1089
+ } else if (Array.isArray(_parentage)) {
1090
+ arrRemove(_parentage, parent2);
1091
+ }
1092
+ };
1093
+ Subscription2.prototype.remove = function(teardown) {
1094
+ var _finalizers = this._finalizers;
1095
+ _finalizers && arrRemove(_finalizers, teardown);
1096
+ if (teardown instanceof Subscription2) {
1097
+ teardown._removeParent(this);
1098
+ }
1099
+ };
1100
+ Subscription2.EMPTY = function() {
1101
+ var empty = new Subscription2();
1102
+ empty.closed = true;
1103
+ return empty;
1104
+ }();
1105
+ return Subscription2;
1106
+ }();
1107
+ var EMPTY_SUBSCRIPTION = Subscription.EMPTY;
1108
+ function isSubscription(value) {
1109
+ return value instanceof Subscription || value && "closed" in value && isFunction(value.remove) && isFunction(value.add) && isFunction(value.unsubscribe);
1110
+ }
1111
+ function execFinalizer(finalizer) {
1112
+ if (isFunction(finalizer)) {
1113
+ finalizer();
1114
+ } else {
1115
+ finalizer.unsubscribe();
1116
+ }
1117
+ }
1118
+ var config = {
1119
+ Promise: void 0
1120
+ };
1121
+ var timeoutProvider = {
1122
+ setTimeout: function(handler, timeout) {
1123
+ var args = [];
1124
+ for (var _i = 2; _i < arguments.length; _i++) {
1125
+ args[_i - 2] = arguments[_i];
1126
+ }
1127
+ return setTimeout.apply(void 0, __spreadArray([handler, timeout], __read(args)));
1128
+ },
1129
+ clearTimeout: function(handle) {
1130
+ return clearTimeout(handle);
1131
+ },
1132
+ delegate: void 0
1133
+ };
1134
+ function reportUnhandledError(err) {
1135
+ timeoutProvider.setTimeout(function() {
1136
+ {
1137
+ throw err;
1138
+ }
1139
+ });
1140
+ }
1141
+ function noop() {
1142
+ }
1143
+ function errorContext(cb) {
1144
+ {
1145
+ cb();
1146
+ }
1147
+ }
1148
+ var Subscriber = function(_super) {
1149
+ __extends(Subscriber2, _super);
1150
+ function Subscriber2(destination) {
1151
+ var _this = _super.call(this) || this;
1152
+ _this.isStopped = false;
1153
+ if (destination) {
1154
+ _this.destination = destination;
1155
+ if (isSubscription(destination)) {
1156
+ destination.add(_this);
1157
+ }
1158
+ } else {
1159
+ _this.destination = EMPTY_OBSERVER;
1160
+ }
1161
+ return _this;
1162
+ }
1163
+ Subscriber2.create = function(next, error, complete) {
1164
+ return new SafeSubscriber(next, error, complete);
1165
+ };
1166
+ Subscriber2.prototype.next = function(value) {
1167
+ if (this.isStopped) ;
1168
+ else {
1169
+ this._next(value);
1170
+ }
1171
+ };
1172
+ Subscriber2.prototype.error = function(err) {
1173
+ if (this.isStopped) ;
1174
+ else {
1175
+ this.isStopped = true;
1176
+ this._error(err);
1177
+ }
1178
+ };
1179
+ Subscriber2.prototype.complete = function() {
1180
+ if (this.isStopped) ;
1181
+ else {
1182
+ this.isStopped = true;
1183
+ this._complete();
1184
+ }
1185
+ };
1186
+ Subscriber2.prototype.unsubscribe = function() {
1187
+ if (!this.closed) {
1188
+ this.isStopped = true;
1189
+ _super.prototype.unsubscribe.call(this);
1190
+ this.destination = null;
1191
+ }
1192
+ };
1193
+ Subscriber2.prototype._next = function(value) {
1194
+ this.destination.next(value);
1195
+ };
1196
+ Subscriber2.prototype._error = function(err) {
1197
+ try {
1198
+ this.destination.error(err);
1199
+ } finally {
1200
+ this.unsubscribe();
1201
+ }
1202
+ };
1203
+ Subscriber2.prototype._complete = function() {
1204
+ try {
1205
+ this.destination.complete();
1206
+ } finally {
1207
+ this.unsubscribe();
1208
+ }
1209
+ };
1210
+ return Subscriber2;
1211
+ }(Subscription);
1212
+ var ConsumerObserver = function() {
1213
+ function ConsumerObserver2(partialObserver) {
1214
+ this.partialObserver = partialObserver;
1215
+ }
1216
+ ConsumerObserver2.prototype.next = function(value) {
1217
+ var partialObserver = this.partialObserver;
1218
+ if (partialObserver.next) {
1219
+ try {
1220
+ partialObserver.next(value);
1221
+ } catch (error) {
1222
+ handleUnhandledError(error);
1223
+ }
1224
+ }
1225
+ };
1226
+ ConsumerObserver2.prototype.error = function(err) {
1227
+ var partialObserver = this.partialObserver;
1228
+ if (partialObserver.error) {
1229
+ try {
1230
+ partialObserver.error(err);
1231
+ } catch (error) {
1232
+ handleUnhandledError(error);
1233
+ }
1234
+ } else {
1235
+ handleUnhandledError(err);
1236
+ }
1237
+ };
1238
+ ConsumerObserver2.prototype.complete = function() {
1239
+ var partialObserver = this.partialObserver;
1240
+ if (partialObserver.complete) {
1241
+ try {
1242
+ partialObserver.complete();
1243
+ } catch (error) {
1244
+ handleUnhandledError(error);
1245
+ }
1246
+ }
1247
+ };
1248
+ return ConsumerObserver2;
1249
+ }();
1250
+ var SafeSubscriber = function(_super) {
1251
+ __extends(SafeSubscriber2, _super);
1252
+ function SafeSubscriber2(observerOrNext, error, complete) {
1253
+ var _this = _super.call(this) || this;
1254
+ var partialObserver;
1255
+ if (isFunction(observerOrNext) || !observerOrNext) {
1256
+ partialObserver = {
1257
+ next: observerOrNext !== null && observerOrNext !== void 0 ? observerOrNext : void 0,
1258
+ error: error !== null && error !== void 0 ? error : void 0,
1259
+ complete: complete !== null && complete !== void 0 ? complete : void 0
1260
+ };
1261
+ } else {
1262
+ {
1263
+ partialObserver = observerOrNext;
1264
+ }
1265
+ }
1266
+ _this.destination = new ConsumerObserver(partialObserver);
1267
+ return _this;
1268
+ }
1269
+ return SafeSubscriber2;
1270
+ }(Subscriber);
1271
+ function handleUnhandledError(error) {
1272
+ {
1273
+ reportUnhandledError(error);
1274
+ }
1275
+ }
1276
+ function defaultErrorHandler(err) {
1277
+ throw err;
1278
+ }
1279
+ var EMPTY_OBSERVER = {
1280
+ closed: true,
1281
+ next: noop,
1282
+ error: defaultErrorHandler,
1283
+ complete: noop
1284
+ };
1285
+ var observable = function() {
1286
+ return typeof Symbol === "function" && Symbol.observable || "@@observable";
1287
+ }();
1288
+ function identity(x) {
1289
+ return x;
1290
+ }
1291
+ function pipeFromArray(fns) {
1292
+ if (fns.length === 0) {
1293
+ return identity;
1294
+ }
1295
+ if (fns.length === 1) {
1296
+ return fns[0];
1297
+ }
1298
+ return function piped(input) {
1299
+ return fns.reduce(function(prev, fn) {
1300
+ return fn(prev);
1301
+ }, input);
1302
+ };
1303
+ }
1304
+ var Observable = function() {
1305
+ function Observable2(subscribe) {
1306
+ if (subscribe) {
1307
+ this._subscribe = subscribe;
1308
+ }
1309
+ }
1310
+ Observable2.prototype.lift = function(operator) {
1311
+ var observable2 = new Observable2();
1312
+ observable2.source = this;
1313
+ observable2.operator = operator;
1314
+ return observable2;
1315
+ };
1316
+ Observable2.prototype.subscribe = function(observerOrNext, error, complete) {
1317
+ var _this = this;
1318
+ var subscriber = isSubscriber(observerOrNext) ? observerOrNext : new SafeSubscriber(observerOrNext, error, complete);
1319
+ errorContext(function() {
1320
+ var _a = _this, operator = _a.operator, source = _a.source;
1321
+ subscriber.add(operator ? operator.call(subscriber, source) : source ? _this._subscribe(subscriber) : _this._trySubscribe(subscriber));
1322
+ });
1323
+ return subscriber;
1324
+ };
1325
+ Observable2.prototype._trySubscribe = function(sink) {
1326
+ try {
1327
+ return this._subscribe(sink);
1328
+ } catch (err) {
1329
+ sink.error(err);
1330
+ }
1331
+ };
1332
+ Observable2.prototype.forEach = function(next, promiseCtor) {
1333
+ var _this = this;
1334
+ promiseCtor = getPromiseCtor(promiseCtor);
1335
+ return new promiseCtor(function(resolve, reject) {
1336
+ var subscriber = new SafeSubscriber({
1337
+ next: function(value) {
1338
+ try {
1339
+ next(value);
1340
+ } catch (err) {
1341
+ reject(err);
1342
+ subscriber.unsubscribe();
1343
+ }
1344
+ },
1345
+ error: reject,
1346
+ complete: resolve
1347
+ });
1348
+ _this.subscribe(subscriber);
1349
+ });
1350
+ };
1351
+ Observable2.prototype._subscribe = function(subscriber) {
1352
+ var _a;
1353
+ return (_a = this.source) === null || _a === void 0 ? void 0 : _a.subscribe(subscriber);
1354
+ };
1355
+ Observable2.prototype[observable] = function() {
1356
+ return this;
1357
+ };
1358
+ Observable2.prototype.pipe = function() {
1359
+ var operations = [];
1360
+ for (var _i = 0; _i < arguments.length; _i++) {
1361
+ operations[_i] = arguments[_i];
1362
+ }
1363
+ return pipeFromArray(operations)(this);
1364
+ };
1365
+ Observable2.prototype.toPromise = function(promiseCtor) {
1366
+ var _this = this;
1367
+ promiseCtor = getPromiseCtor(promiseCtor);
1368
+ return new promiseCtor(function(resolve, reject) {
1369
+ var value;
1370
+ _this.subscribe(function(x) {
1371
+ return value = x;
1372
+ }, function(err) {
1373
+ return reject(err);
1374
+ }, function() {
1375
+ return resolve(value);
1376
+ });
1377
+ });
1378
+ };
1379
+ Observable2.create = function(subscribe) {
1380
+ return new Observable2(subscribe);
1381
+ };
1382
+ return Observable2;
1383
+ }();
1384
+ function getPromiseCtor(promiseCtor) {
1385
+ var _a;
1386
+ return (_a = promiseCtor !== null && promiseCtor !== void 0 ? promiseCtor : config.Promise) !== null && _a !== void 0 ? _a : Promise;
1387
+ }
1388
+ function isObserver(value) {
1389
+ return value && isFunction(value.next) && isFunction(value.error) && isFunction(value.complete);
1390
+ }
1391
+ function isSubscriber(value) {
1392
+ return value && value instanceof Subscriber || isObserver(value) && isSubscription(value);
1393
+ }
1394
+ function hasLift(source) {
1395
+ return isFunction(source === null || source === void 0 ? void 0 : source.lift);
1396
+ }
1397
+ function operate(init) {
1398
+ return function(source) {
1399
+ if (hasLift(source)) {
1400
+ return source.lift(function(liftedSource) {
1401
+ try {
1402
+ return init(liftedSource, this);
1403
+ } catch (err) {
1404
+ this.error(err);
1405
+ }
1406
+ });
1407
+ }
1408
+ throw new TypeError("Unable to lift unknown Observable type");
1409
+ };
1410
+ }
1411
+ function createOperatorSubscriber(destination, onNext, onComplete, onError, onFinalize) {
1412
+ return new OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize);
1413
+ }
1414
+ var OperatorSubscriber = function(_super) {
1415
+ __extends(OperatorSubscriber2, _super);
1416
+ function OperatorSubscriber2(destination, onNext, onComplete, onError, onFinalize, shouldUnsubscribe) {
1417
+ var _this = _super.call(this, destination) || this;
1418
+ _this.onFinalize = onFinalize;
1419
+ _this.shouldUnsubscribe = shouldUnsubscribe;
1420
+ _this._next = onNext ? function(value) {
1421
+ try {
1422
+ onNext(value);
1423
+ } catch (err) {
1424
+ destination.error(err);
1425
+ }
1426
+ } : _super.prototype._next;
1427
+ _this._error = onError ? function(err) {
1428
+ try {
1429
+ onError(err);
1430
+ } catch (err2) {
1431
+ destination.error(err2);
1432
+ } finally {
1433
+ this.unsubscribe();
1434
+ }
1435
+ } : _super.prototype._error;
1436
+ _this._complete = onComplete ? function() {
1437
+ try {
1438
+ onComplete();
1439
+ } catch (err) {
1440
+ destination.error(err);
1441
+ } finally {
1442
+ this.unsubscribe();
1443
+ }
1444
+ } : _super.prototype._complete;
1445
+ return _this;
1446
+ }
1447
+ OperatorSubscriber2.prototype.unsubscribe = function() {
1448
+ var _a;
1449
+ if (!this.shouldUnsubscribe || this.shouldUnsubscribe()) {
1450
+ var closed_1 = this.closed;
1451
+ _super.prototype.unsubscribe.call(this);
1452
+ !closed_1 && ((_a = this.onFinalize) === null || _a === void 0 ? void 0 : _a.call(this));
1453
+ }
1454
+ };
1455
+ return OperatorSubscriber2;
1456
+ }(Subscriber);
1457
+ var ObjectUnsubscribedError = createErrorClass(function(_super) {
1458
+ return function ObjectUnsubscribedErrorImpl() {
1459
+ _super(this);
1460
+ this.name = "ObjectUnsubscribedError";
1461
+ this.message = "object unsubscribed";
1462
+ };
1463
+ });
1464
+ var Subject = function(_super) {
1465
+ __extends(Subject2, _super);
1466
+ function Subject2() {
1467
+ var _this = _super.call(this) || this;
1468
+ _this.closed = false;
1469
+ _this.currentObservers = null;
1470
+ _this.observers = [];
1471
+ _this.isStopped = false;
1472
+ _this.hasError = false;
1473
+ _this.thrownError = null;
1474
+ return _this;
1475
+ }
1476
+ Subject2.prototype.lift = function(operator) {
1477
+ var subject = new AnonymousSubject(this, this);
1478
+ subject.operator = operator;
1479
+ return subject;
1480
+ };
1481
+ Subject2.prototype._throwIfClosed = function() {
1482
+ if (this.closed) {
1483
+ throw new ObjectUnsubscribedError();
1484
+ }
1485
+ };
1486
+ Subject2.prototype.next = function(value) {
1487
+ var _this = this;
1488
+ errorContext(function() {
1489
+ var e_1, _a;
1490
+ _this._throwIfClosed();
1491
+ if (!_this.isStopped) {
1492
+ if (!_this.currentObservers) {
1493
+ _this.currentObservers = Array.from(_this.observers);
1494
+ }
1495
+ try {
1496
+ for (var _b = __values(_this.currentObservers), _c = _b.next(); !_c.done; _c = _b.next()) {
1497
+ var observer = _c.value;
1498
+ observer.next(value);
1499
+ }
1500
+ } catch (e_1_1) {
1501
+ e_1 = { error: e_1_1 };
1502
+ } finally {
1503
+ try {
1504
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
1505
+ } finally {
1506
+ if (e_1) throw e_1.error;
1507
+ }
1508
+ }
1509
+ }
1510
+ });
1511
+ };
1512
+ Subject2.prototype.error = function(err) {
1513
+ var _this = this;
1514
+ errorContext(function() {
1515
+ _this._throwIfClosed();
1516
+ if (!_this.isStopped) {
1517
+ _this.hasError = _this.isStopped = true;
1518
+ _this.thrownError = err;
1519
+ var observers = _this.observers;
1520
+ while (observers.length) {
1521
+ observers.shift().error(err);
1522
+ }
1523
+ }
1524
+ });
1525
+ };
1526
+ Subject2.prototype.complete = function() {
1527
+ var _this = this;
1528
+ errorContext(function() {
1529
+ _this._throwIfClosed();
1530
+ if (!_this.isStopped) {
1531
+ _this.isStopped = true;
1532
+ var observers = _this.observers;
1533
+ while (observers.length) {
1534
+ observers.shift().complete();
1535
+ }
1536
+ }
1537
+ });
1538
+ };
1539
+ Subject2.prototype.unsubscribe = function() {
1540
+ this.isStopped = this.closed = true;
1541
+ this.observers = this.currentObservers = null;
1542
+ };
1543
+ Object.defineProperty(Subject2.prototype, "observed", {
1544
+ get: function() {
1545
+ var _a;
1546
+ return ((_a = this.observers) === null || _a === void 0 ? void 0 : _a.length) > 0;
1547
+ },
1548
+ enumerable: false,
1549
+ configurable: true
1550
+ });
1551
+ Subject2.prototype._trySubscribe = function(subscriber) {
1552
+ this._throwIfClosed();
1553
+ return _super.prototype._trySubscribe.call(this, subscriber);
1554
+ };
1555
+ Subject2.prototype._subscribe = function(subscriber) {
1556
+ this._throwIfClosed();
1557
+ this._checkFinalizedStatuses(subscriber);
1558
+ return this._innerSubscribe(subscriber);
1559
+ };
1560
+ Subject2.prototype._innerSubscribe = function(subscriber) {
1561
+ var _this = this;
1562
+ var _a = this, hasError = _a.hasError, isStopped = _a.isStopped, observers = _a.observers;
1563
+ if (hasError || isStopped) {
1564
+ return EMPTY_SUBSCRIPTION;
1565
+ }
1566
+ this.currentObservers = null;
1567
+ observers.push(subscriber);
1568
+ return new Subscription(function() {
1569
+ _this.currentObservers = null;
1570
+ arrRemove(observers, subscriber);
1571
+ });
1572
+ };
1573
+ Subject2.prototype._checkFinalizedStatuses = function(subscriber) {
1574
+ var _a = this, hasError = _a.hasError, thrownError = _a.thrownError, isStopped = _a.isStopped;
1575
+ if (hasError) {
1576
+ subscriber.error(thrownError);
1577
+ } else if (isStopped) {
1578
+ subscriber.complete();
1579
+ }
1580
+ };
1581
+ Subject2.prototype.asObservable = function() {
1582
+ var observable2 = new Observable();
1583
+ observable2.source = this;
1584
+ return observable2;
1585
+ };
1586
+ Subject2.create = function(destination, source) {
1587
+ return new AnonymousSubject(destination, source);
1588
+ };
1589
+ return Subject2;
1590
+ }(Observable);
1591
+ var AnonymousSubject = function(_super) {
1592
+ __extends(AnonymousSubject2, _super);
1593
+ function AnonymousSubject2(destination, source) {
1594
+ var _this = _super.call(this) || this;
1595
+ _this.destination = destination;
1596
+ _this.source = source;
1597
+ return _this;
1598
+ }
1599
+ AnonymousSubject2.prototype.next = function(value) {
1600
+ var _a, _b;
1601
+ (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.next) === null || _b === void 0 ? void 0 : _b.call(_a, value);
1602
+ };
1603
+ AnonymousSubject2.prototype.error = function(err) {
1604
+ var _a, _b;
1605
+ (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.error) === null || _b === void 0 ? void 0 : _b.call(_a, err);
1606
+ };
1607
+ AnonymousSubject2.prototype.complete = function() {
1608
+ var _a, _b;
1609
+ (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.complete) === null || _b === void 0 ? void 0 : _b.call(_a);
1610
+ };
1611
+ AnonymousSubject2.prototype._subscribe = function(subscriber) {
1612
+ var _a, _b;
1613
+ return (_b = (_a = this.source) === null || _a === void 0 ? void 0 : _a.subscribe(subscriber)) !== null && _b !== void 0 ? _b : EMPTY_SUBSCRIPTION;
1614
+ };
1615
+ return AnonymousSubject2;
1616
+ }(Subject);
1617
+ var BehaviorSubject = function(_super) {
1618
+ __extends(BehaviorSubject2, _super);
1619
+ function BehaviorSubject2(_value) {
1620
+ var _this = _super.call(this) || this;
1621
+ _this._value = _value;
1622
+ return _this;
1623
+ }
1624
+ Object.defineProperty(BehaviorSubject2.prototype, "value", {
1625
+ get: function() {
1626
+ return this.getValue();
1627
+ },
1628
+ enumerable: false,
1629
+ configurable: true
1630
+ });
1631
+ BehaviorSubject2.prototype._subscribe = function(subscriber) {
1632
+ var subscription = _super.prototype._subscribe.call(this, subscriber);
1633
+ !subscription.closed && subscriber.next(this._value);
1634
+ return subscription;
1635
+ };
1636
+ BehaviorSubject2.prototype.getValue = function() {
1637
+ var _a = this, hasError = _a.hasError, thrownError = _a.thrownError, _value = _a._value;
1638
+ if (hasError) {
1639
+ throw thrownError;
1640
+ }
1641
+ this._throwIfClosed();
1642
+ return _value;
1643
+ };
1644
+ BehaviorSubject2.prototype.next = function(value) {
1645
+ _super.prototype.next.call(this, this._value = value);
1646
+ };
1647
+ return BehaviorSubject2;
1648
+ }(Subject);
1649
+ var EmptyError = createErrorClass(function(_super) {
1650
+ return function EmptyErrorImpl() {
1651
+ _super(this);
1652
+ this.name = "EmptyError";
1653
+ this.message = "no elements in sequence";
1654
+ };
1655
+ });
1656
+ function lastValueFrom(source, config2) {
1657
+ return new Promise(function(resolve, reject) {
1658
+ var _hasValue = false;
1659
+ var _value;
1660
+ source.subscribe({
1661
+ next: function(value) {
1662
+ _value = value;
1663
+ _hasValue = true;
1664
+ },
1665
+ error: reject,
1666
+ complete: function() {
1667
+ if (_hasValue) {
1668
+ resolve(_value);
1669
+ } else {
1670
+ reject(new EmptyError());
1671
+ }
1672
+ }
1673
+ });
1674
+ });
1675
+ }
1676
+ function filter(predicate, thisArg) {
1677
+ return operate(function(source, subscriber) {
1678
+ var index = 0;
1679
+ source.subscribe(createOperatorSubscriber(subscriber, function(value) {
1680
+ return predicate.call(thisArg, value, index++) && subscriber.next(value);
1681
+ }));
1682
+ });
1683
+ }
1684
+ function distinctUntilChanged(comparator, keySelector) {
1685
+ if (keySelector === void 0) {
1686
+ keySelector = identity;
1687
+ }
1688
+ comparator = comparator !== null && comparator !== void 0 ? comparator : defaultCompare;
1689
+ return operate(function(source, subscriber) {
1690
+ var previousKey;
1691
+ var first = true;
1692
+ source.subscribe(createOperatorSubscriber(subscriber, function(value) {
1693
+ var currentKey = keySelector(value);
1694
+ if (first || !comparator(previousKey, currentKey)) {
1695
+ first = false;
1696
+ previousKey = currentKey;
1697
+ subscriber.next(value);
1698
+ }
1699
+ }));
1700
+ });
1701
+ }
1702
+ function defaultCompare(a, b) {
1703
+ return a === b;
1704
+ }
1705
+ function skip(count) {
1706
+ return filter(function(_, index) {
1707
+ return count <= index;
1708
+ });
1709
+ }
1710
+ function takeWhile(predicate, inclusive) {
1711
+ return operate(function(source, subscriber) {
1712
+ var index = 0;
1713
+ source.subscribe(createOperatorSubscriber(subscriber, function(value) {
1714
+ var result = predicate(value, index++);
1715
+ (result || inclusive) && subscriber.next(value);
1716
+ !result && subscriber.complete();
1717
+ }));
1718
+ });
1719
+ }
1720
+ async function getTheme(spoke, scope) {
1721
+ let theme = await fetch(`https://${spoke}.auxiliumgroup.com/static/js/auxilium/dijits/templates/login/${spoke}/theme.json`).then((res) => res.json()).catch(() => null);
1722
+ if (scope && theme != null && theme[scope]) theme = { ...theme, ...theme[scope] };
1723
+ return {
1724
+ found: !!theme,
1725
+ background: `https://${spoke}.auxiliumgroup.com/static/js/auxilium/dijits/templates/login/${spoke}/background.jpg`,
1726
+ backgroundColor: void 0,
1727
+ color: "#c83232",
1728
+ glow: "#c83232",
1729
+ logo: `https://${spoke}.auxiliumgroup.com/static/js/auxilium/dijits/templates/login/${spoke}/logo.png`,
1730
+ logoPosition: "left",
1731
+ hideLogo: false,
1732
+ hideApps: false,
1733
+ persist: true,
1734
+ title: spoke.toUpperCase(),
1735
+ textColor: "white",
1736
+ titleFontFamily: "sans-serif",
1737
+ titleFontUrl: "https://fonts.cdnfonts.com/css/ar-blanca",
1738
+ titleFontSize: "45px",
1739
+ titleTextShadow: "0 0 3px black",
1740
+ subtitle: "",
1741
+ subtitleFontFamily: "sans-serif",
1742
+ subtitleFontUrl: "",
1743
+ subtitleFontSize: "36px",
1744
+ subtitleTextColor: "white",
1745
+ subtitleTextShadow: "0 0 3px black",
1746
+ ...theme || {}
1747
+ };
1748
+ }
1749
+ const _LoginPrompt = class _LoginPrompt {
1750
+ constructor(api, spoke, options = {}) {
1751
+ __publicField(this, "alert");
1752
+ __publicField(this, "button");
1753
+ __publicField(this, "form");
1754
+ __publicField(this, "password");
1755
+ __publicField(this, "persist");
1756
+ __publicField(this, "username");
1757
+ __publicField(this, "_done");
1758
+ /** Promise which resolves once login is complete */
1759
+ __publicField(this, "done", new Promise((res) => {
1760
+ this._done = res;
1761
+ }));
1762
+ this.api = api;
1763
+ this.spoke = spoke;
1764
+ this.options = options;
1765
+ this.themeDefaults().then(() => this.render());
1766
+ }
1767
+ async render() {
1768
+ this.close();
1769
+ document.head.innerHTML += _LoginPrompt.css(this.options);
1770
+ const div = document.createElement("div");
1771
+ div.innerHTML = _LoginPrompt.template(this.options);
1772
+ document.body.appendChild(div);
1773
+ this.alert = document.querySelector("#datalynk-login-alert");
1774
+ this.button = document.querySelector("#datalynk-login-form button");
1775
+ this.form = document.querySelector("#datalynk-login-form");
1776
+ this.password = document.querySelector('#datalynk-login-form input[name="password"]');
1777
+ this.persist = document.querySelector('#datalynk-login-form input[name="persist"]');
1778
+ this.username = document.querySelector('#datalynk-login-form input[name="username"]');
1779
+ if (this.options.persist === false) this.persist.parentElement.remove();
1780
+ this.form.onsubmit = (event) => this.login(event);
1781
+ const pwaLink = document.querySelector("#pwa-install-link");
1782
+ if (pwaLink) {
1783
+ pwaLink.addEventListener("click", async (e) => {
1784
+ var _a;
1785
+ e.preventDefault();
1786
+ if ((_a = this.api.pwa) == null ? void 0 : _a.deferredPrompt) {
1787
+ this.api.pwa.deferredPrompt.prompt();
1788
+ const choice = await this.api.pwa.deferredPrompt.userChoice;
1789
+ if (choice.outcome === "accepted") {
1790
+ console.log("PWA installed via login link");
1791
+ }
1792
+ this.api.pwa.deferredPrompt = null;
1793
+ } else {
1794
+ this.api.pwa.prompt();
1795
+ }
1796
+ });
1797
+ }
1798
+ }
1799
+ async themeDefaults() {
1800
+ const theme = await getTheme(this.spoke, "login");
1801
+ const cleaned = clean(this.options, true);
1802
+ this.options = {
1803
+ ...theme,
1804
+ ...cleaned,
1805
+ logoOnly: !this.options.title && !theme.found,
1806
+ logoPosition: cleaned.logoPosition ?? theme.logoPosition ?? "left",
1807
+ hideLogo: cleaned.hideLogo ?? theme.hideLogo ?? false,
1808
+ platform: this.api.pwa.platform,
1809
+ ...Object.prototype.hasOwnProperty.call(this.api.options, "pwaSettings") && {
1810
+ pwaSettings: this.api.options.pwaSettings
1811
+ }
1812
+ };
1813
+ }
1814
+ /** Close the login prompt */
1815
+ close() {
1816
+ var _a, _b;
1817
+ (_a = document.querySelector("#datalynk-login-styles")) == null ? void 0 : _a.remove();
1818
+ (_b = document.querySelector("#datalynk-login")) == null ? void 0 : _b.remove();
1819
+ }
1820
+ /** Check if login prompt is still open */
1821
+ isOpen() {
1822
+ return !!document.querySelector("#datalynk-login");
1823
+ }
1824
+ /** Login form submit event */
1825
+ login(event) {
1826
+ event.preventDefault();
1827
+ const data = new FormData(event.target);
1828
+ this.alert.classList.add("hidden");
1829
+ this.username.disabled = true;
1830
+ this.password.disabled = true;
1831
+ this.persist.disabled = true;
1832
+ this.button.disabled = true;
1833
+ return this.api.auth.login(
1834
+ this.spoke,
1835
+ data.get("username"),
1836
+ data.get("password"),
1837
+ { expire: this.persist.checked ? null : void 0 }
1838
+ ).then((data2) => {
1839
+ this.close();
1840
+ this._done();
1841
+ return data2;
1842
+ }).catch((err) => {
1843
+ this.alert.classList.remove("hidden");
1844
+ this.alert.innerHTML = err.message;
1845
+ this.password.value = "";
1846
+ this.username.disabled = false;
1847
+ this.password.disabled = false;
1848
+ this.persist.disabled = false;
1849
+ this.button.disabled = false;
1850
+ });
1851
+ }
1852
+ };
1853
+ /** Dynamically create CSS style */
1854
+ __publicField(_LoginPrompt, "css", (options) => `
1855
+ <style id="datalynk-login-styles">
1856
+ @import url('https://fonts.cdnfonts.com/css/ar-blanca');
1857
+ ${options.titleFontUrl ? `@import url('${options.titleFontUrl}');` : ""}
1858
+ ${options.subtitleFontUrl ? `@import url('${options.subtitleFontUrl}');` : ""}
1859
+
1860
+ #datalynk-login {
1861
+ --theme-background: ${options.backgroundColor ? options.backgroundColor : `url(${options.background})`};
1862
+ --theme-container: #000000cc;
1863
+ --theme-glow: ${options.glow || options.color};
1864
+ --theme-primary: ${options.color};
1865
+ --theme-text: ${options.textColor};
1866
+
1867
+ position: fixed;
1868
+ left: 0;
1869
+ top: 0;
1870
+ right: 0;
1871
+ bottom: 0;
1872
+ background: var(--theme-background);
1873
+ background-repeat: no-repeat;
1874
+ background-size: cover;
1875
+ font-family: sans-serif;
1876
+ z-index: 1000;
1877
+ }
1878
+
1879
+ #datalynk-login .added-links {
1880
+ color: var(--theme-text);
1881
+ position: fixed;
1882
+ bottom: 0;
1883
+ right: 0;
1884
+ padding: 0.25rem;
1885
+ }
1886
+
1887
+ #datalynk-login .added-links a, #datalynk-login .added-links a:hover, #datalynk-login .added-links a:visited {
1888
+ color: var(--theme-text);
1889
+ text-shadow: 0 0 10px black;
1890
+ }
1891
+
1892
+ #datalynk-login-alert {
1893
+ padding: 0.75rem;
1894
+ background: rgba(0,0,0,0.5);
1895
+ color: white;
1896
+ border-radius: 5px;
1897
+ margin-bottom: 1rem;
1898
+ border: grey 1px solid;
1899
+ }
1900
+
1901
+ #datalynk-login label {
1902
+ color: white;
1903
+ font-size: 20px;
1904
+ }
1905
+
1906
+ #datalynk-login input {
1907
+ width: calc(100% - 20px);
1908
+ padding: 12px 9px 9px 9px;
1909
+ margin: 1px;
1910
+ border: 1px solid #ddd;
1911
+ border-radius: 5px;
1912
+ background-color: white;
1913
+ color: black;
1914
+ }
1915
+
1916
+ #datalynk-login .login-container {
1917
+ position: fixed;
1918
+ top: 50%;
1919
+ left: 0;
1920
+ right: 0;
1921
+ transform: translateY(-50%);
1922
+ }
1923
+
1924
+ #datalynk-login .login-header {
1925
+ display: flex;
1926
+ justify-content: center;
1927
+ align-items: center;
1928
+ color: var(--theme-text);
1929
+ text-align: center;
1930
+ font-size: 32px;
1931
+ margin-bottom: 2rem;
1932
+ }
1933
+
1934
+ #datalynk-login .login-title {
1935
+ font-family: ${options.titleFontFamily || "sans-serif"};
1936
+ font-size: ${options.titleFontSize || "32px"};
1937
+ ${options.titleTextShadow ? `text-shadow: ${options.titleTextShadow};` : ""}
1938
+ }
1939
+
1940
+ #datalynk-login .login-subtitle {
1941
+ font-family: ${options.subtitleFontFamily || "sans-serif"};
1942
+ font-size: ${options.subtitleFontSize || "20px"};
1943
+ color: ${options.subtitleTextColor || "white"};
1944
+ ${options.subtitleTextShadow ? `text-shadow: ${options.subtitleTextShadow};` : ""}
1945
+ margin-top: 0.5rem;
1946
+ }
1947
+
1948
+ #datalynk-login .login-content {
1949
+ display: flex;
1950
+ flex-direction: column;
1951
+ align-items: center;
1952
+ background: var(--theme-container);
1953
+ border-top: var(--theme-glow) 1px solid;
1954
+ box-shadow: 0 -10px 20px -10px var(--theme-glow);
1955
+ }
1956
+
1957
+ #datalynk-login .login-body {
1958
+ padding: ${options.hideApps ? "3.5rem 0" : "3.5rem 0 1.5rem 0"};
1959
+ width: 100%;
1960
+ max-width: 400px;;
1961
+ color: white;
1962
+ }
1963
+
1964
+ #datalynk-login input:disabled {
1965
+ color: #333;
1966
+ background-color: #ccc;
1967
+ }
1968
+
1969
+ #datalynk-login input[type="checkbox"] {
1970
+ height: 15px;
1971
+ margin: 0;
1972
+ padding: 0;
1973
+ accent-color: var(--theme-primary);
1974
+ }
1975
+
1976
+ #datalynk-login button {
1977
+ background-color: var(--theme-primary);
1978
+ background-image: none;
1979
+ border: 0;
1980
+ color: ${contrast(options.color)};
1981
+ padding: 8px 24px;
1982
+ border-radius: 5px;
1983
+ }
1984
+
1985
+ #datalynk-login button:disabled {
1986
+ cursor: pointer;
1987
+ filter: brightness(90%);
1988
+ }
1989
+
1990
+ #datalynk-login button:hover:not(:disabled) {
1991
+ cursor: pointer;
1992
+ filter: ${contrast(options.color) == "black" ? "brightness(105%)" : "brightness(80%)"};
1993
+ }
1994
+
1995
+ #datalynk-login .login-links{
1996
+ display: flex;
1997
+ padding: 0 0 1.5rem 0;
1998
+ }
1999
+
2000
+ #datalynk-login .login-links a {
2001
+ text-decoration: none;
2002
+ }
2003
+
2004
+ #datalynk-login #pwa-install-link {
2005
+ display: inline-flex;
2006
+ align-items: center;
2007
+ gap: 0.4rem; /* space between icon and text */
2008
+ font-size: 16px;
2009
+ text-decoration: none;
2010
+ color: var(--theme-text);
2011
+ text-shadow: 0 0 10px black;
2012
+ }
2013
+
2014
+ #datalynk-login .login-links img {
2015
+ width: 150px;
2016
+ height: auto;
2017
+ }
2018
+
2019
+ #datalynk-login .hidden {
2020
+ display: none;
2021
+ }
2022
+
2023
+ #datalynk-login .login-footer {
2024
+ transform: translateY(-18px);
2025
+ }
2026
+
2027
+ #datalynk-login .sloped-div {
2028
+ position: absolute;
2029
+ height: 45px;
2030
+ width: 200px;
2031
+ background: var(--theme-container);
2032
+ clip-path: polygon(0 20px, 100% 20px, 85% 60px, 15% 60px);
2033
+ }
2034
+ </style>`);
2035
+ /** Dynamically create HTML */
2036
+ __publicField(_LoginPrompt, "template", (options) => {
2037
+ var _a;
2038
+ return `
2039
+ <div id="datalynk-login">
2040
+ ${!options.backgroundColor ? `<img src="${options.background}" onerror="document.querySelector('#datalynk-login').style.backgroundImage = 'url(https://datalynk.auxiliumgroup.com/static/js/auxilium/dijits/templates/login/datalynk/background.jpg)'" style="width: 0; height: 0;"/>` : ""}
2041
+ <div class="added-links">
2042
+ ${(options.addLinks || []).map((link) => `<a href="${link.url || "#"}" target="_blank">${link.text}</a>`).join(" | ")}
2043
+ </div>
2044
+ <div class="login-container">
2045
+ <div class="login-header" style="flex-direction: ${["aboveTitle", "belowTitle", "belowSubtitle"].includes(options.logoPosition || "") ? "column" : "row"};">
2046
+ ${!options.hideLogo && options.logo && options.logoPosition === "aboveTitle" ? `<img alt="Logo" src="${options.logo}" class="login-logo" style="height: 100px; width: auto; margin-bottom: 0.5rem;" onerror="this.style.display='none'">` : ""}
2047
+
2048
+ ${!options.hideLogo && options.logo && options.logoPosition === "left" ? `<img alt="Logo" src="${options.logo}" class="login-logo" style="height: 100px; width: auto; margin-right: 0.5rem;" onerror="this.style.display='none'">` : ""}
2049
+
2050
+ <div style="display: flex; flex-direction: column; align-items: center;">
2051
+ <span class="login-title">${options.title || ""}</span>
2052
+ ${options.logo && !options.hideLogo && options.logoPosition === "belowTitle" ? `<img alt="Logo" src="${options.logo}" class="login-logo" style="height: 100px; width: auto; margin-top: 0.5rem;" onerror="this.style.display='none'">` : ""}
2053
+ ${options.subtitle ? `<span class="login-subtitle">${options.subtitle}</span>` : ""}
2054
+ ${options.logo && !options.hideLogo && options.logoPosition === "belowSubtitle" ? `<img alt="Logo" src="${options.logo}" class="login-logo" style="height: 100px; width: auto; margin-top: 0.5rem;" onerror="this.style.display='none'">` : ""}
2055
+ </div>
2056
+
2057
+ ${!options.hideLogo && options.logo && options.logoPosition === "right" ? `<img alt="Logo" src="${options.logo}" class="login-logo" style="height: 100px; width: auto; margin-left: 0.5rem;" onerror="this.style.display='none'">` : ""}
2058
+ </div>
2059
+ <div class="login-content">
2060
+ <div class="login-body" style="max-width: 300px">
2061
+ <div id="datalynk-login-alert" class="hidden"></div>
2062
+ <form id="datalynk-login-form">
2063
+ <div>
2064
+ <label for="username">Email or Username</label>
2065
+ <input id="username" name="username" type="text" autocomplete="username">
2066
+ </div>
2067
+ <br>
2068
+ <div>
2069
+ <label for="password">Password</label>
2070
+ <input id="password" name="password" type="password" autocomplete="current-password">
2071
+ </div>
2072
+ <br>
2073
+ <label style="display: block; margin-bottom: 0.75rem;">
2074
+ <input type="checkbox" name="persist" style="width: 20px"> Stay Logged In
2075
+ </label>
2076
+ <button type="submit">Login</button>
2077
+ </form>
2078
+ </div>
2079
+ <div class="login-links" style="text-align: center">
2080
+ ${((_a = options == null ? void 0 : options.pwaSettings) == null ? void 0 : _a.loginLink) === true && !["ios", "mac"].includes(options.platform) ? `
2081
+ <a href="#" id="pwa-install-link" style="margin-right: 1rem;" title="Install App">
2082
+ <svg xmlns="http://www.w3.org/2000/svg" height="40px" viewBox="0 0 24 24" width="40px" fill="${options.color || "#0B76FC"}">
2083
+ <path d="M12 16l4-5h-3V4h-2v7H8z"/><path d="M20 18H4v-2h16v2z"/>
2084
+ </svg> Download App
2085
+ </a>` : ""}
2086
+ ${options.hideApps ? "" : `
2087
+ <a href="https://itunes.apple.com/ca/app/auxilium-mobile/id1166379280?mt=8" target="_blank">
2088
+ <img alt="App Store" src="https://datalynk.auxiliumgroup.com/api/js/auxilium/dijits/templates/login/_common/mobile_apple_transparent.png">
2089
+ </a>
2090
+ <a href="https://play.google.com/store/apps/details?id=com.auxilium.auxiliummobilesolutions&amp;hl=en" target="_blank">
2091
+ <img alt="Playstore" src="https://datalynk.auxiliumgroup.com/api/js/auxilium/dijits/templates/login/_common/mobile_google_transparent.png">
2092
+ </a>`}
2093
+ </div>
2094
+ </div>
2095
+ <div class="login-footer" style="position: relative; display: flex; align-items: center; justify-content: center;">
2096
+ <div class="sloped-div"></div>
2097
+ <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;">
2098
+ Au<span style="font-size: 52px; color: #c83232; margin-bottom: 5px; font-family: 'AR BLANCA', serif;">x</span>ilium
2099
+ <span style="position: absolute; font-size: 10px; color: #c83232; top: 2px; right: 2px; font-family: 'AR BLANCA', serif;">Group</span>
2100
+ </a>
2101
+ </div>
2102
+ </div>
2103
+ </div>
2104
+ `;
2105
+ });
2106
+ let LoginPrompt = _LoginPrompt;
2107
+ class Auth {
2108
+ constructor(api) {
2109
+ __publicField(this, "onlinePrompt");
2110
+ /** Current user as an observable */
2111
+ __publicField(this, "user$", new BehaviorSubject(void 0));
2112
+ var _a;
2113
+ this.api = api;
2114
+ this.api.token$.subscribe(async (token) => {
2115
+ if (token === void 0) return;
2116
+ this.user = await this.current(token);
2117
+ });
2118
+ if ((_a = this.api.options.offline) == null ? void 0 : _a.length)
2119
+ this.user$.pipe(filter((u) => u !== void 0)).subscribe((u) => localStorage.setItem("datalynk-user", JSON.stringify(u)));
2120
+ }
2121
+ /** Current user */
2122
+ get user() {
2123
+ return this.user$.getValue();
2124
+ }
2125
+ /** Set current user info */
2126
+ set user(user) {
2127
+ this.user$.next(user);
2128
+ }
2129
+ get spoke() {
2130
+ var _a;
2131
+ return ((_a = this.api.jwtPayload) == null ? void 0 : _a.realm) || null;
2132
+ }
2133
+ /**
2134
+ * Get current user associated with API token
2135
+ *
2136
+ * @return {Promise<User | null>}
2137
+ */
2138
+ async current(token = this.api.token) {
2139
+ var _a;
2140
+ if (!token) return null;
2141
+ else if (token == ((_a = this.user) == null ? void 0 : _a.token)) return this.user;
2142
+ else if (!this.api.online && typeof localStorage != "undefined" && localStorage.getItem("datalynk-user"))
2143
+ return JSON.parse(localStorage.getItem("datalynk-user"));
2144
+ return this.api.request([{ "$/auth/current": {} }, { "$/env/me": {} }], { token }).then((resp) => resp[0] || resp[1] ? { ...resp[0], ...resp[1] } : null);
2145
+ }
2146
+ /**
2147
+ * Automatically handle sessions by checking localStorage & URL parameters for a token & prompting
2148
+ * user with a login screen if required
2149
+ *
2150
+ * @param {string} spoke Desired spoke
2151
+ * @param {LoginPromptOptions} options Aesthetic options
2152
+ * @return {Promise<void>} Login complete
2153
+ */
2154
+ async handleLogin(spoke, options) {
2155
+ var _a, _b;
2156
+ if (this.onlinePrompt) window.removeEventListener("online", this.onlinePrompt);
2157
+ if ((_a = this.api.options.offline) == null ? void 0 : _a.length) window.removeEventListener("online", this.onlinePrompt = () => this.handleLogin(spoke, options));
2158
+ const urlToken = new URLSearchParams(location.search).get("datalynkToken");
2159
+ if (urlToken) {
2160
+ this.api.token = urlToken;
2161
+ location.href = location.href.replace(/datalynkToken=.*?(&|$)/gm, "");
2162
+ } else if (this.api.token && !this.api.expired) {
2163
+ if (((_b = this.api.jwtPayload) == null ? void 0 : _b.realm) != spoke) {
2164
+ this.api.token = null;
2165
+ location.reload();
2166
+ }
2167
+ } else {
2168
+ this.api.token = null;
2169
+ await this.loginPrompt(spoke, options).done;
2170
+ location.reload();
2171
+ }
2172
+ }
2173
+ /**
2174
+ * Check whether user has a token
2175
+ *
2176
+ * @return {boolean} True if session token authenticated
2177
+ */
2178
+ isAuthenticated() {
2179
+ return !!this.user && !this.user.guest;
2180
+ }
2181
+ /**
2182
+ * Check if the current user is a guest
2183
+ *
2184
+ * @return {boolean} True if guest
2185
+ */
2186
+ isGuest() {
2187
+ var _a;
2188
+ return !!((_a = this.user) == null ? void 0 : _a.guest);
2189
+ }
2190
+ /**
2191
+ * Check if user is a system administrator
2192
+ *
2193
+ * @return {Promise<boolean>} True if system administrator
2194
+ */
2195
+ async isSysAdmin() {
2196
+ return !!(await this.api.slice("sysadmin").select().where("auth_ref", "==", "$viewer").rows().exec()).length;
2197
+ }
2198
+ /**
2199
+ * Check if user is a table administrator
2200
+ *
2201
+ * @return {Promise<boolean>} True if table administrator
2202
+ */
2203
+ async isTableAdmin() {
2204
+ return !!(await this.api.slice("tableadmins").select().where("auth_ref", "==", "$viewer").rows().exec()).length;
2205
+ }
2206
+ /**
2207
+ * Check if user is a user administrator
2208
+ *
2209
+ * @return {Promise<boolean>} True if user administrator
2210
+ */
2211
+ async isUserAdmin() {
2212
+ return !!(await this.api.slice("useradmins").select().where("auth_ref", "==", "$viewer").rows().exec()).length;
2213
+ }
2214
+ /**
2215
+ * Perform login and save the session token
2216
+ *
2217
+ * @param {string} login Login username or email
2218
+ * @param {string} password Password for account
2219
+ * @param {string} spoke Override login spoke
2220
+ * @param {twoFactor?: string, expire?: string} opts 2FA code & expire date (YYYY-MM-DD)
2221
+ * @returns {Promise<User>} User account
2222
+ */
2223
+ login(spoke, login, password, opts) {
2224
+ const date = /* @__PURE__ */ new Date();
2225
+ date.setFullYear(date.getFullYear() + 1);
2226
+ return fetch(`${this.api.url}login`, {
2227
+ method: "POST",
2228
+ headers: { "Content-Type": "application/json" },
2229
+ body: JSON.stringify(clean({
2230
+ realm: spoke.trim(),
2231
+ login: login.trim(),
2232
+ password: password.trim(),
2233
+ secret: opts == null ? void 0 : opts.twoFactor,
2234
+ expireAt: (opts == null ? void 0 : opts.expire) == null ? `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, "0")}-${date.getDate().toString().padStart(2, "0")}` : opts == null ? void 0 : opts.expire,
2235
+ dateFormat: "ISO8601"
2236
+ }))
2237
+ }).then(async (resp) => {
2238
+ const data = await resp.json().catch(() => ({}));
2239
+ if (!resp.ok || data["error"]) throw Object.assign(errorFromCode(resp.status, data.error) || {}, data);
2240
+ this.api.token = data["token"];
2241
+ return data;
2242
+ });
2243
+ }
2244
+ /**
2245
+ * Login as guest user
2246
+ *
2247
+ * @return {Promise<User>} Guest account
2248
+ */
2249
+ loginGuest() {
2250
+ return fetch(`${this.api.url}guest`).then(async (resp) => {
2251
+ const data = await resp.json().catch(() => ({}));
2252
+ if (!resp.ok || data["error"]) throw Object.assign(errorFromCode(resp.status, data.error) || {}, data);
2253
+ this.api.token = data["token"];
2254
+ return data;
2255
+ });
2256
+ }
2257
+ /**
2258
+ * Create Login UI
2259
+ *
2260
+ * @param {string} spoke Desired spoke
2261
+ * @param {LoginPromptOptions} options Aesthetic options
2262
+ * @return {LoginPrompt} Login prompt
2263
+ */
2264
+ loginPrompt(spoke, options) {
2265
+ return new LoginPrompt(this.api, spoke, options);
2266
+ }
2267
+ /**
2268
+ * Logout current user
2269
+ *
2270
+ * @return {Promise<{closed: string, new: string}>}
2271
+ */
2272
+ logout(reload = true) {
2273
+ localStorage.removeItem("datalynk-user");
2274
+ return this.api.request({ "$/auth/logout": {} }).then((resp) => {
2275
+ if (reload) location.reload();
2276
+ this.api.token = null;
2277
+ return resp;
2278
+ });
2279
+ }
2280
+ /**
2281
+ * Reset user account password
2282
+ *
2283
+ * @param {string} login User login
2284
+ * @param {string} newPassword New password
2285
+ * @param {string} code Reset code sent with `resetRequest`
2286
+ * @return {Promise<any>} New session
2287
+ */
2288
+ reset(login, newPassword, code) {
2289
+ return this.api.request({
2290
+ "$/auth/mobile/rescue": {
2291
+ user: login,
2292
+ password: newPassword,
2293
+ pin: code
2294
+ }
2295
+ }).then((resp) => {
2296
+ if (resp.token) this.api.token = resp.token;
2297
+ return resp;
2298
+ });
2299
+ }
2300
+ /**
2301
+ * Request reset code for user
2302
+ *
2303
+ * @param {string} login User to reset
2304
+ * @param {"email" | "sms" | "voice"} mode Method of sending reset code
2305
+ * @return {Promise<any>} Unknown
2306
+ */
2307
+ resetRequest(login, mode) {
2308
+ if (mode == "email") return this.api.request({ "$/auth/rescue_email": { user: { $or: { login, email: login } } } });
2309
+ return this.api.request({ "$/auth/mobile/generate": { user: login, method: mode } });
2310
+ }
2311
+ }
2312
+ class PWA {
2313
+ constructor(api) {
2314
+ __publicField(this, "deferredPrompt", null);
2315
+ this.api = api;
2316
+ }
2317
+ // Holds the beforeinstallprompt event
2318
+ get headless() {
2319
+ return typeof window == "undefined";
2320
+ }
2321
+ get iframe() {
2322
+ return (parent == null ? void 0 : parent.location) != location;
2323
+ }
2324
+ get mobile() {
2325
+ return ["android", "ios"].includes(this.platform);
2326
+ }
2327
+ get platform() {
2328
+ const userAgent = navigator.userAgent || navigator.vendor;
2329
+ if (/windows/i.test(userAgent)) return "windows";
2330
+ else if (/android/i.test(userAgent)) return "android";
2331
+ else if (/iPad|iPhone|iPod/.test(userAgent)) return "ios";
2332
+ else if (/macintosh|mac os x/i.test(userAgent)) return "mac";
2333
+ else if (/linux/i.test(userAgent)) return "linux";
2334
+ else return "unknown";
2335
+ }
2336
+ get pwa() {
2337
+ return matchMedia("(display-mode: standalone)").matches || (navigator == null ? void 0 : navigator.standalone) || document.referrer.includes("android-app://");
2338
+ }
2339
+ bindInstallButton() {
2340
+ const installBtn = document.querySelector("#installPwaBtn");
2341
+ if (!installBtn) return;
2342
+ installBtn.onclick = async () => {
2343
+ var _a;
2344
+ this.deferredPrompt.prompt();
2345
+ const choice = await this.deferredPrompt.userChoice;
2346
+ if (choice.outcome === "accepted") {
2347
+ console.log("PWA installed");
2348
+ localStorage.removeItem(`${this.api.options.name}:pwa`);
2349
+ }
2350
+ this.deferredPrompt = null;
2351
+ (_a = document.querySelector(".pwa-prompt")) == null ? void 0 : _a.remove();
2352
+ };
2353
+ }
2354
+ /** Setup the PWA */
2355
+ async setup(manifest = {}) {
2356
+ var _a, _b, _c;
2357
+ window.addEventListener("beforeinstallprompt", (e) => {
2358
+ e.preventDefault();
2359
+ this.deferredPrompt = e;
2360
+ const actions = document.querySelector(".pwa-prompt-actions");
2361
+ if (actions && !actions.querySelector("#installPwaBtn")) {
2362
+ actions.innerHTML = `<button id="installPwaBtn">Install App</button>`;
2363
+ this.bindInstallButton();
2364
+ }
2365
+ });
2366
+ const settings = {
2367
+ timeout: (((_a = this.api.options.pwaSettings) == null ? void 0 : _a.timeout) ?? 30) * 1e3,
2368
+ // default 30s
2369
+ dismissExpiry: ((_b = this.api.options.pwaSettings) == null ? void 0 : _b.dismissExpiry) ?? 7,
2370
+ // default 7 days
2371
+ loginLink: ((_c = this.api.options.pwaSettings) == null ? void 0 : _c.loginLink) ?? false
2372
+ };
2373
+ const meta = (key, name, value) => {
2374
+ const exists = document.querySelector(`meta[${key}="${name}"]`);
2375
+ if (value === void 0 || exists) return exists;
2376
+ const meta2 = document.createElement("meta");
2377
+ meta2.setAttribute(key, name);
2378
+ meta2.content = value;
2379
+ document.head.append(meta2);
2380
+ };
2381
+ meta("name", "mobile-web-app-capable", "yes");
2382
+ meta("name", "apple-mobile-web-app-status-bar-style", "default");
2383
+ meta("name", "apple-mobile-web-app-title", this.api.options.name);
2384
+ meta("name", "apple-touch-icon", `https://datalynk-client.scarborough.auxilium.world/logo.png`);
2385
+ meta("name", "apple-touch-startup-image", `https://datalynk-client.scarborough.auxilium.world/logo.png`);
2386
+ if (!document.querySelector('link[rel="manifest"]')) {
2387
+ const link = document.createElement("link");
2388
+ link.rel = "manifest";
2389
+ const base = String(this.api.url).replace(/\/+$/, "");
2390
+ const startUrl = location.pathname;
2391
+ const scopePath = startUrl.endsWith("/") ? startUrl : startUrl.replace(/[^/]+$/, "");
2392
+ const manifestObj = {
2393
+ name: this.api.options.name,
2394
+ short_name: this.api.options.name,
2395
+ start_url: startUrl,
2396
+ scope: scopePath || "/",
2397
+ display: "standalone",
2398
+ ...this.api.options.manifest || {},
2399
+ ...manifest || {}
2400
+ };
2401
+ link.href = `${base}/manifest?json=${encodeURIComponent(JSON.stringify(manifestObj))}`;
2402
+ document.head.append(link);
2403
+ }
2404
+ if (!this.headless && !this.iframe && !this.pwa && this.platform != "mac") setTimeout(() => {
2405
+ const dismissedDate = localStorage.getItem(`${this.api.options.name}:pwa`);
2406
+ if (settings.dismissExpiry > 0 && dismissedDate) {
2407
+ const diffDays = (Date.now() - new Date(dismissedDate).getTime()) / (1e3 * 60 * 60 * 24);
2408
+ if (diffDays < settings.dismissExpiry) return;
2409
+ } else if (settings.dismissExpiry === 0) {
2410
+ localStorage.removeItem(`${this.api.options.name}:pwa`);
2411
+ }
2412
+ this.prompt();
2413
+ }, settings.timeout);
2414
+ }
2415
+ /** Prompt user to install the app */
2416
+ async prompt(platform) {
2417
+ var _a;
2418
+ if (document.querySelector(".pwa-prompt")) return;
2419
+ const android = (platform || this.platform) == "android";
2420
+ let style = document.querySelector("style.pwa");
2421
+ if (!style) {
2422
+ style = document.createElement("style");
2423
+ style.classList.add("pwa");
2424
+ style.innerHTML = `
2425
+ .pwa-prompt {
2426
+ position: fixed;
2427
+ bottom: 0;
2428
+ left: 50%;
2429
+ transform: translateX(-50%);
2430
+ background: #fff;
2431
+ color: #222;
2432
+ width: min(100vw, 450px);
2433
+ border-radius: 8px 8px 0 0;
2434
+ box-shadow: 0 -4px 12px rgba(0,0,0,0.2);
2435
+ font-family: system-ui, sans-serif;
2436
+ animation: slideUp 0.35s ease forwards;
2437
+ z-index: 10000;
2438
+ box-shadow: 0px 10px 5px 3px #0000007d;
2439
+ }
2440
+ .pwa-prompt-header {
2441
+ display: flex;
2442
+ align-items: center;
2443
+ background: linear-gradient(140deg, #080808, #454242bf);
2444
+ color: #fff;
2445
+ padding: 0.75rem 1rem;
2446
+ position: relative;
2447
+ border-radius: 10px 10px 0px 0px;
2448
+ }
2449
+ .pwa-prompt-header img {
2450
+ height: 28px;
2451
+ margin-right: 0.5rem;
2452
+ }
2453
+ .pwa-prompt-header h1 {
2454
+ font-size: 1rem;
2455
+ margin: 0;
2456
+ flex-grow: 1;
2457
+ }
2458
+ .pwa-prompt-close {
2459
+ position: absolute;
2460
+ right: 12px;
2461
+ top: 10px;
2462
+ background: transparent;
2463
+ border: none;
2464
+ color: #fff;
2465
+ font-size: 18px;
2466
+ cursor: pointer;
2467
+ }
2468
+ .pwa-prompt-body {
2469
+ padding: 1rem;
2470
+ font-size: 0.9rem;
2471
+ text-align: center;
2472
+ }
2473
+ .pwa-prompt-actions {
2474
+ text-align: center;
2475
+ padding: 0.75rem 1rem 1rem;
2476
+ }
2477
+ .pwa-prompt-actions button {
2478
+ background: #c33031;
2479
+ color: #fff;
2480
+ border: none;
2481
+ padding: 0.6rem 1.2rem;
2482
+ border-radius: 6px;
2483
+ cursor: pointer;
2484
+ font-size: 0.9rem;
2485
+ }
2486
+ .pwa-steps ol {
2487
+ padding-left: 1.25rem;
2488
+ text-align: left;
2489
+ }
2490
+ .pwa-prompt-actions table {
2491
+ width: 100%;
2492
+ margin: 0;
2493
+ }
2494
+ .pwa-prompt-actions td {
2495
+ padding: 0.5rem;
2496
+ }
2497
+ @keyframes slideUp {
2498
+ from { transform: translate(-50%, 100%); opacity: 0; }
2499
+ to { transform: translate(-50%, 0); opacity: 1; }
2500
+ }`;
2501
+ document.head.append(style);
2502
+ }
2503
+ const prompt = document.createElement("div");
2504
+ prompt.classList.add("pwa-prompt");
2505
+ prompt.innerHTML = `
2506
+ <div class="pwa-prompt-header">
2507
+ <img src="https://datalynk-client.scarborough.auxilium.world/logo.png" alt="Logo" />
2508
+ <h1>Install ${this.api.options.name}</h1>
2509
+ <button class="pwa-prompt-close">&times;</button>
2510
+ </div>
2511
+ <div class="pwa-prompt-body">
2512
+ ${this.deferredPrompt ? "Click below to install the app directly to your device." : "Add this app to your home screen for a faster, fullscreen experience."}
2513
+ </div>
2514
+ <div class="pwa-prompt-actions">
2515
+ ${this.deferredPrompt ? `<button id="installPwaBtn">Install App</button>` : `
2516
+ <table>
2517
+ <tr>
2518
+ <td style="width:40px;text-align:center">
2519
+ ${android ? '<svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960" width="24px" fill="black" style="transform: scale(1.5)"><path d="M480-160q-33 0-56.5-23.5T400-240q0-33 23.5-56.5T480-320q33 0 56.5 23.5T560-240q0 33-23.5 56.5T480-160Zm0-240q-33 0-56.5-23.5T400-480q0-33 23.5-56.5T480-560q33 0 56.5 23.5T560-480q0 33-23.5 56.5T480-400Zm0-240q-33 0-56.5-23.5T400-720q0-33 23.5-56.5T480-800q33 0 56.5 23.5T560-720q0 33-23.5 56.5T480-640Z"/></svg>' : '<svg viewBox="0 0 566 670" xmlns="http://www.w3.org/2000/svg" fill="#c33031" height="40px"><path d="M255 12c4-4 10-8 16-8s12 3 16 8l94 89c3 4 6 7 8 12 2 6 0 14-5 19-7 8-20 9-28 2l-7-7-57-60 2 54v276c0 12-10 22-22 22-12 1-24-10-23-22V110l1-43-60 65c-5 5-13 8-21 6a19 19 0 0 1-16-17c-1-7 2-13 7-18l95-91z" /><path d="M43 207c16-17 40-23 63-23h83v46h-79c-12 0-25 3-33 13-8 9-10 21-10 33v260c0 13 0 27 6 38 5 12 18 18 30 19l14 1h302c14 0 28 0 40-8 11-7 16-21 16-34V276c0-11-2-24-9-33-8-10-22-13-34-13h-78v-46h75c13 0 25 1 37 4 16 4 31 13 41 27 11 17 14 37 14 57v280c0 20-3 41-15 58a71 71 0 0 1-45 27c-11 2-23 3-34 3H109c-19-1-40-4-56-15-14-9-23-23-27-38-4-12-5-25-5-38V270c1-22 6-47 22-63z" /></svg>'}
2520
+ </td>
2521
+ <td>1) ${android ? "Open the dropdown menu" : 'Tap the "Share" button'}</td>
2522
+ </tr>
2523
+ <tr>
2524
+ <td style="width:40px;text-align:center">
2525
+ ${android ? '<svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960" width="24px" fill="black" style="transform: scale(-1.5, 1.5)"><path d="M280-40q-33 0-56.5-23.5T200-120v-720q0-33 23.5-56.5T280-920h280v80H280v40h280v80H280v480h400v-80h80v200q0 33-23.5 56.5T680-40H280Zm0-120v40h400v-40H280Zm440-240L520-600l56-56 104 104v-288h80v288l104-104 56 56-200 200ZM280-800v-40 40Zm0 640v40-40Z"/></svg>' : '<svg viewBox="0 0 578 584" xmlns="http://www.w3.org/2000/svg" fill="black" height="34px"><path d="M101 35l19-1h333c12 0 23 0 35 3 17 3 34 12 44 27 13 16 16 38 16 58v329c0 19 0 39-8 57a65 65 0 0 1-37 37c-18 7-38 7-57 7H130c-21 1-44 0-63-10-14-7-25-20-30-34-6-15-8-30-8-45V121c1-21 5-44 19-61 13-16 33-23 53-25m7 46c-10 1-19 6-24 14-7 8-9 20-9 31v334c0 12 2 25 10 34 9 10 23 12 35 12h336c14 1 30-3 38-15 6-9 8-20 8-31V125c0-12-2-24-10-33-9-9-22-12-35-12H121l-13 1z" /><path d="M271 161c9-11 31-10 38 4 3 5 3 11 3 17v87h88c7 0 16 1 21 7 6 6 7 14 6 22a21 21 0 0 1-10 14c-5 4-11 5-17 5h-88v82c0 7-1 15-6 20-10 10-29 10-37-2-3-6-4-13-4-19v-81h-87c-8-1-17-3-23-9-5-6-6-15-4-22a21 21 0 0 1 11-14c6-3 13-3 19-3h84v-88c0-7 1-14 6-20z" /></svg>'}
2526
+ </td>
2527
+ <td>2) Select "Add to Home Screen"</td>
2528
+ </tr>
2529
+ </table>
2530
+ `}
2531
+ </div>
2532
+ `;
2533
+ const closeBtn = prompt.querySelector(".pwa-prompt-close");
2534
+ const dismissExpiry = ((_a = this.api.options.pwaSettings) == null ? void 0 : _a.dismissExpiry) ?? 7;
2535
+ closeBtn.onclick = () => {
2536
+ dismissExpiry > 0 ? localStorage.setItem(`${this.api.options.name}:pwa`, (/* @__PURE__ */ new Date()).toISOString()) : localStorage.removeItem(`${this.api.options.name}:pwa`);
2537
+ prompt.remove();
2538
+ };
2539
+ document.body.append(prompt);
2540
+ if (this.deferredPrompt) this.bindInstallButton();
2541
+ }
2542
+ }
2543
+ class Files {
2544
+ constructor(api) {
2545
+ this.api = api;
2546
+ }
2547
+ associate(fileIds, slice, row, field, execute = true) {
2548
+ const req = { [`${execute ? "!" : "$"}/tools/file/update`]: { slice, row, field, ids: fileIds } };
2549
+ if (execute) return this.api.request(req);
2550
+ return req;
2551
+ }
2552
+ /**
2553
+ * Get an authenticated URL to fetch files from
2554
+ *
2555
+ * @param {number} id File ID
2556
+ * @param {boolean} ignoreToken Ignore authentication
2557
+ * @return {string} URL file can be viewed at
2558
+ */
2559
+ get(id, ignoreToken) {
2560
+ return `${this.api.url}file?id=${id}${ignoreToken ? "" : `&token=${this.api.token}`}`;
2561
+ }
2562
+ /**
2563
+ * Upload file(s) to the API & optionally associate them with a row
2564
+ *
2565
+ * @param {FileList | File | File[]} files Files to be uploaded
2566
+ * @param {{slice: number, row: any, field: string, pk?: string}} associate Row to associate with
2567
+ */
2568
+ upload(files, associate) {
2569
+ let f = files instanceof FileList ? Array.from(files) : makeArray(files);
2570
+ return Promise.all(f.map((file) => {
2571
+ const data = new FormData();
2572
+ data.append("uploadedfiles[]", file, file.name);
2573
+ return fetch(`${this.api.url}upload.php`, {
2574
+ method: "POST",
2575
+ headers: clean({ "Authorization": this.api.token ? `Bearer ${this.api.token}` : "" }),
2576
+ body: data
2577
+ }).then(async (resp) => {
2578
+ const data2 = await resp.json().catch(() => ({}));
2579
+ if (!resp.ok || data2["error"]) throw Object.assign(errorFromCode(resp.status, data2.error) || {}, data2);
2580
+ return data2.files.uploadedfiles[0];
2581
+ });
2582
+ })).then(async (files2) => {
2583
+ if (associate) {
2584
+ let id = typeof associate.row == "number" ? associate.row : associate.row[associate.pk || "id"];
2585
+ if (!id) id = await this.api.slice(associate.slice).insert(associate.row).id().exec();
2586
+ 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);
2587
+ }
2588
+ return files2;
2589
+ });
2590
+ }
2591
+ }
2592
+ class Pdf {
2593
+ constructor(api) {
2594
+ this.api = api;
2595
+ }
2596
+ /**
2597
+ * Create a PDF from a public URL
2598
+ * @param {string} url Target URL address
2599
+ * @param {{slice: number, row: number, field: string} | null} associate Optionally associate PDF with a slice row
2600
+ * @param {PdfOptions} options PDF options for rendering & uploading
2601
+ * @return {Promise<any>} Either the PDF file number or the updated slice row response if associated
2602
+ */
2603
+ async fromUrl(url, associate, options = {}) {
2604
+ return this.api.request({ "$/slice/utils/urlToPdf": { url, ...options } }).then((file) => {
2605
+ if (associate) return this.api.files.associate(file, associate.slice, associate.row, associate.field);
2606
+ return file;
2607
+ });
2608
+ }
2609
+ }
2610
+ const Serializer = {
2611
+ /**
2612
+ * From Datalynk syntax to JS
2613
+ */
2614
+ deserialize: {
2615
+ /**
2616
+ * Convert date time string to javascript date object
2617
+ *
2618
+ * @param {string} datetime datetime string (YYYY/MM/DD hh:mm:ss)
2619
+ * @returns {Date} JS Date object
2620
+ */
2621
+ "$/tools/date": (datetime) => {
2622
+ let a = datetime.split(/[^0-9]+/).map((part) => Number(part));
2623
+ return new Date(a[0], a[1] - 1, a[2], a[3], a[4], a[5]);
2624
+ },
2625
+ /**
2626
+ * Convert date string to javascript date object
2627
+ *
2628
+ * @param {string} date date string (YYYY/MM/DD)
2629
+ * @returns {Date} JS Date object
2630
+ */
2631
+ "$/tools/date_strict": (date) => {
2632
+ let a = date.split(/[^0-9]+/).map((part) => Number(part));
2633
+ let d = new Date(a[0], a[1] - 1, a[2], 0, 0, 0);
2634
+ d["hint"] = "date";
2635
+ return d;
2636
+ },
2637
+ /**
2638
+ * Convert time string to javascript date object
2639
+ *
2640
+ * @param {string} time time string (YYYY/MM/DD)
2641
+ * @returns {Date} JS Date object
2642
+ */
2643
+ "$/tools/time_strict": (time) => {
2644
+ let a = time.split(/[^0-9]+/).map((part) => Number(part));
2645
+ let d = /* @__PURE__ */ new Date();
2646
+ d.setHours(a[0]);
2647
+ d.setMinutes(a[1]);
2648
+ d.setSeconds(a[2]);
2649
+ d["hint"] = "time";
2650
+ return d;
2651
+ },
2652
+ /**
2653
+ * Convert string to constant
2654
+ *
2655
+ * @param {string} constant string to be converted
2656
+ * @returns {any} the actual constant
2657
+ */
2658
+ "$/tools/const": (constant) => {
2659
+ let types = {
2660
+ "infinity": Infinity,
2661
+ "-infinity": -Infinity,
2662
+ "nan": NaN
2663
+ };
2664
+ try {
2665
+ return types[constant["$/tools/const"].toLowerCase()];
2666
+ } catch (ignored) {
2667
+ return void 0;
2668
+ }
2669
+ },
2670
+ /**
2671
+ * Large requests are formatted into parallel arrays
2672
+ *
2673
+ * @param {object} obj Object of metadata and data
2674
+ * @returns {Array} Actual object reconstructed
2675
+ */
2676
+ "$/tools/dltable": function(obj) {
2677
+ let meta = obj["meta"];
2678
+ let col;
2679
+ let fn = [];
2680
+ for (let i in meta) {
2681
+ col = meta[i];
2682
+ fn.push("this['" + col.name + "'] = ");
2683
+ if (col.cast == null) {
2684
+ fn.push("a[" + i + "];\n");
2685
+ } else if (col.cast === "num") {
2686
+ fn.push("a[" + i + "] && parseFloat(a[" + i + "]);\n");
2687
+ } else {
2688
+ if (col["native"] === "date") {
2689
+ fn.push("a[" + i + "] && dateParse(a[" + i + "]);\n");
2690
+ fn.push("a[" + i + "] && (this['" + col.name + "'].hint = 'date');\n");
2691
+ } else if (col["native"] === "time") {
2692
+ fn.push("a[" + i + "] && timeParse(a[" + i + "]);\n");
2693
+ fn.push("a[" + i + "] && (this['" + col.name + "'].hint = 'time');\n");
2694
+ } else {
2695
+ fn.push("a[" + i + "] && datetimeParse(a[" + i + "]);\n");
2696
+ }
2697
+ }
2698
+ }
2699
+ let dateTimeParse, dateParse, timeParse;
2700
+ let now = /* @__PURE__ */ new Date();
2701
+ let yyyy = now.getFullYear();
2702
+ let mm = now.getMonth();
2703
+ let dd = now.getDate();
2704
+ dateTimeParse = function(dt) {
2705
+ dt = dt.split(/[^0-9]+/);
2706
+ return new Date(dt[0], dt[1] - 1, dt[2], dt[3], dt[4], dt[5]);
2707
+ };
2708
+ dateParse = function(d) {
2709
+ d = d.split(/[- :]/);
2710
+ let res2 = new Date(d[0], d[1] - 1, d[2], 0, 0, 0);
2711
+ res2["hint"] = "date";
2712
+ return res2;
2713
+ };
2714
+ timeParse = function(t) {
2715
+ t = t.split(/[^0-9]+/, t);
2716
+ let res2 = new Date(yyyy, mm, dd, t[0], t[1], t[2]);
2717
+ res2["hint"] = "time";
2718
+ return res2;
2719
+ };
2720
+ let ctor = Function("datetimeParse", "dateParse", "timeParse", "a", fn.join(""));
2721
+ let res = [];
2722
+ let rows = obj["rows"];
2723
+ for (let i in rows) {
2724
+ res[i] = new ctor(dateTimeParse, dateParse, timeParse, rows[i]);
2725
+ }
2726
+ res["meta"] = meta;
2727
+ res["rowConstructor"] = ctor;
2728
+ return res;
2729
+ }
2730
+ },
2731
+ /**
2732
+ * From JS to Datalynk syntax
2733
+ */
2734
+ serialize: {
2735
+ /**
2736
+ * Convert JS date to datalynk datetime string
2737
+ */
2738
+ "Date": (date) => {
2739
+ return {
2740
+ "$/tools/date": [date.getFullYear(), date.getMonth() + 1, date.getDate()].join("/") + " " + [date.getHours(), date.getMinutes(), date.getSeconds()].join(":")
2741
+ };
2742
+ }
2743
+ }
2744
+ };
2745
+ class ApiCall {
2746
+ constructor(api, slice) {
2747
+ __publicField(this, "operation");
2748
+ __publicField(this, "popField");
2749
+ __publicField(this, "request", {});
2750
+ /** Log response automatically */
2751
+ __publicField(this, "debugging");
2752
+ /**
2753
+ * Whitelist and alias fields. Alias of `fields()`
2754
+ * @example
2755
+ * ```ts
2756
+ * const id: {id: number, field2: any}[] = await new Slice<T>(12345)
2757
+ * .select().alias({id: 'id', field1: 'field2'}).exec().keys();
2758
+ * ```
2759
+ * @param {object} aliasKeyVals List of properties to whitelist and what to rename them to
2760
+ * @return {Slice<T>}
2761
+ */
2762
+ __publicField(this, "alias", this.fields);
2763
+ this.api = api;
2764
+ this.slice = slice;
2765
+ }
2766
+ /** Get raw API request */
2767
+ get raw() {
2768
+ return clean({
2769
+ [this.operation]: {
2770
+ ...this.request,
2771
+ slice: this.slice
2772
+ },
2773
+ "$pop": this.popField ? this.popField : void 0
2774
+ });
2775
+ }
2776
+ /**
2777
+ * Add an 'AND' condition inside the where argument
2778
+ * @example
2779
+ * ```ts
2780
+ * const rows: T[] = await new Slice<T>(12345).select()
2781
+ * .where('field1', '>', 1)
2782
+ * .and()
2783
+ * .where({field2: 2, field3: 3})
2784
+ * .exec().rows();
2785
+ * ```
2786
+ * @return {Slice<T>}
2787
+ */
2788
+ and() {
2789
+ var _a;
2790
+ if (((_a = this.request.where) == null ? void 0 : _a[0]) == "$and") return this;
2791
+ if (this.request.where) this.request.where = ["$and", this.request.where];
2792
+ else this.request.where = ["$and"];
2793
+ return this;
2794
+ }
2795
+ /**
2796
+ * Count the returned rows
2797
+ * @example
2798
+ * ```ts
2799
+ * const count = await new Slice(12345).count()
2800
+ * .where({field1: 1})
2801
+ * .exec().count();
2802
+ * ```
2803
+ * @param {object | string} arg Count argument
2804
+ * @return {Slice<T>}
2805
+ */
2806
+ count(arg = "id") {
2807
+ this.operation = "$/slice/report";
2808
+ this.request.fields = { count: ["$count", typeof arg == "object" ? arg : ["$field", arg]] };
2809
+ return this.pop("rows:0:count");
2810
+ }
2811
+ /**
2812
+ * Output the formed request to the console for inspection
2813
+ * @param {boolean} enabled Enable/Disable console logging
2814
+ * @return {Slice<T>}
2815
+ */
2816
+ debug(enabled = true) {
2817
+ this.debugging = enabled;
2818
+ return this;
2819
+ }
2820
+ /**
2821
+ * Set the request type to delete
2822
+ * @example
2823
+ * ```ts
2824
+ * await new Slice(12345).delete(id).exec();
2825
+ * ```
2826
+ * @param {number | number[]} id ID(s) to delete
2827
+ * @return {Slice<T>}
2828
+ */
2829
+ delete(id) {
2830
+ this.operation = "$/slice/delete";
2831
+ if (id) {
2832
+ if (Array.isArray(id)) this.where("id", "$in", id);
2833
+ else this.where("id", "==", id);
2834
+ }
2835
+ return this;
2836
+ }
2837
+ /**
2838
+ * Filter rows from slice based on an excel expression
2839
+ * @example
2840
+ * ```ts
2841
+ * const rows: T[] = await new Slice<T>(12345).select()
2842
+ * .excel('contains({property}, foobar)')
2843
+ * .exec().rows();
2844
+ * ```
2845
+ * @param formula Excel formula to use as where clause
2846
+ * @return {Slice<T>}
2847
+ */
2848
+ excel(formula) {
2849
+ this.where(["$excel", formula]);
2850
+ return this;
2851
+ }
2852
+ /**
2853
+ * Compile the request and send it
2854
+ * @param {ApiRequestOptions} options API Request options
2855
+ * @return {Promise<T = any>} API response
2856
+ */
2857
+ exec(options) {
2858
+ if (!this.operation) throw new Error("No operation chosen");
2859
+ const request = this.raw;
2860
+ return this.api.request(request, options).then((resp) => {
2861
+ if (this.debugging) console.log(resp);
2862
+ return resp;
2863
+ });
2864
+ }
2865
+ fields(keys) {
2866
+ this.request.fields = Array.isArray(keys) ? keys.reduce((acc, key) => ({ ...acc, [key]: key }), {}) : keys;
2867
+ return this;
2868
+ }
2869
+ /**
2870
+ * Unwrap response returning the first ID
2871
+ * @return {Slice<T>}
2872
+ */
2873
+ id() {
2874
+ return this.pop("rows:0:id");
2875
+ }
2876
+ /**
2877
+ * Set the request type to insert
2878
+ * @example
2879
+ * ```ts
2880
+ * const id: number = await new Slice<T>(12345).insert([
2881
+ * {field1: 1},
2882
+ * {field1: 2}
2883
+ * ]).exec().keys();
2884
+ * ```
2885
+ * @param {T | T[]} rows Rows to be inserted into the slice
2886
+ * @return {Slice<T>}
2887
+ */
2888
+ insert(rows) {
2889
+ this.operation = "$/slice/xinsert";
2890
+ if (!this.request.rows) this.request.rows = [];
2891
+ if (Array.isArray(rows)) this.request.rows = this.request.rows.concat(rows);
2892
+ else this.request.rows.push(rows);
2893
+ return this;
2894
+ }
2895
+ /**
2896
+ * Limit number of rows returned
2897
+ * @example
2898
+ * ```ts
2899
+ * const rows: T[] = await new Slice<T>(12345).select().limit(10)
2900
+ * .exec().rows();
2901
+ * ```
2902
+ * @param {number} num Number of rows to return
2903
+ * @return {Slice<T>}
2904
+ */
2905
+ limit(num) {
2906
+ this.request.limit = num;
2907
+ return this;
2908
+ }
2909
+ /**
2910
+ * Add an 'OR' condition inside the where argument
2911
+ * @example
2912
+ * ```ts
2913
+ * const rows: T[] = await new Slice<T>(12345).select()
2914
+ * .where('field1', '>', 1)
2915
+ * .or()
2916
+ * .where({field2: 2, field3: 3})
2917
+ * .or()
2918
+ * .where(['$gt', ['$field', field4], 4)
2919
+ * .exec().rows();
2920
+ * ```
2921
+ * @return {Slice<T>}
2922
+ */
2923
+ or() {
2924
+ var _a;
2925
+ if (((_a = this.request.where) == null ? void 0 : _a[0]) == "$or") {
2926
+ this.request.where.push(null);
2927
+ return this;
2928
+ }
2929
+ if (this.request.where) this.request.where = ["$or", this.request.where, null];
2930
+ else this.request.where = ["$or", null];
2931
+ return this;
2932
+ }
2933
+ /**
2934
+ * Order rows by a field
2935
+ * @example
2936
+ * ```ts
2937
+ * const rows: T[] = new Slice<T>(12345).select().order('field1', true) // true = ascending
2938
+ * .exec().rows();
2939
+ * ```
2940
+ * @param {string} field property name
2941
+ * @param {boolean} ascending Sort in ascending or descending order
2942
+ * @return {Slice<T>}
2943
+ */
2944
+ order(field, ascending = true) {
2945
+ if (!this.request.order) this.request.order = [];
2946
+ this.request.order.push([ascending ? "$asc" : "$desc", ["$field", field]]);
2947
+ return this;
2948
+ }
2949
+ /**
2950
+ * Unwrap response, returning the field
2951
+ * @param {string} field Colon seperated path: `rows:0`
2952
+ * @return {Slice<T>}
2953
+ */
2954
+ pop(field) {
2955
+ this.popField = field;
2956
+ return this;
2957
+ }
2958
+ /**
2959
+ * Unwrap response returning the first row
2960
+ * @return {Slice<T>}
2961
+ */
2962
+ row() {
2963
+ return this.pop("rows:0");
2964
+ }
2965
+ /**
2966
+ * Unwrap response returning the rows
2967
+ * @return {Slice<T>}
2968
+ */
2969
+ rows() {
2970
+ return this.pop("rows");
2971
+ }
2972
+ /**
2973
+ * Save multiple rows to the slice, automatically inserts/updates
2974
+ * @param {T} rows Rows to add to slice
2975
+ * @returns {this<T>}
2976
+ */
2977
+ save(rows) {
2978
+ this.operation = "$/slice/multisave";
2979
+ this.request.rows = makeArray(rows);
2980
+ return this;
2981
+ }
2982
+ /**
2983
+ * Set the request type to select
2984
+ * @example
2985
+ * ```ts
2986
+ * const rows: T[] = new Slice<T>(12345).select().exec().rows();
2987
+ * const row: T = new Slice<T>(12345).select(id).exec().row();
2988
+ * ```
2989
+ * @param {number | number[]} id ID(s) to select, leaving blank will return all rows
2990
+ * @return {Slice<T>}
2991
+ */
2992
+ select(id) {
2993
+ this.operation = "$/slice/report";
2994
+ if (id) {
2995
+ if (Array.isArray(id)) this.where("id", "$in", id);
2996
+ else this.where("id", "==", id);
2997
+ }
2998
+ return this;
2999
+ }
3000
+ /**
3001
+ * Set the request type to update
3002
+ * @example
3003
+ * ```ts
3004
+ * const ids: number[] = await new Slice<Type>(12345).update([
3005
+ * {id: 1, field1: 1},
3006
+ * {id: 2, field1: 1}
3007
+ * ]).exec().keys();
3008
+ * ```
3009
+ * @param {T | T[]} rows Rows to be updated, each row must have an ID
3010
+ * @return {Slice<T>}
3011
+ */
3012
+ update(rows) {
3013
+ this.operation = "$/slice/xupdate";
3014
+ if (!this.request.rows) this.request.rows = [];
3015
+ if (Array.isArray(rows)) this.request.rows = this.request.rows.concat(rows);
3016
+ else this.request.rows.push(rows);
3017
+ return this;
3018
+ }
3019
+ /**
3020
+ * Add where condition to request
3021
+ * @example
3022
+ * ```ts
3023
+ * const rows: T[] = await new Slice<T>(12345).select()
3024
+ * .where('field1', '>', 1)
3025
+ * .where({field2: 2, field3: 3}) // Automatic AND
3026
+ * .or()
3027
+ * .where(['$gt', ['$field', field4], 4)
3028
+ * .exec().rows();
3029
+ * ```
3030
+ * @param {string | object} field property to compare or a map of equality comparisons
3031
+ * @param {string} operator Operation to compare with. Accepts JS operators (>=, ==, !=, ...) as well as datalynk styax ($gte, $eq, $is, $not, ...)
3032
+ * @param {any} value value to compare against
3033
+ * @return {Slice<T>}
3034
+ */
3035
+ where(field, operator, value) {
3036
+ if (this.request.where && this.request.where[0] != "$or") this.and();
3037
+ const raw = Array.isArray(field);
3038
+ if (typeof field == "object" && !raw) {
3039
+ Object.entries(field).forEach(([key, value2]) => this.where(key, "==", value2));
3040
+ } else {
3041
+ const w = raw ? field : [(() => {
3042
+ if (operator == null ? void 0 : operator.startsWith("$")) return operator;
3043
+ if (operator == "==") return "$eq";
3044
+ if (operator == "!=") return "$neq";
3045
+ if (operator == ">") return "$gt";
3046
+ if (operator == ">=") return "$gte";
3047
+ if (operator == "<") return "$lt";
3048
+ if (operator == "<=") return "$lte";
3049
+ if (operator == "!") return "$not";
3050
+ if (operator == "%") return "$mod";
3051
+ if (operator == null ? void 0 : operator.startsWith("$")) return operator;
3052
+ throw new Error(`Unknown operator: ${operator}`);
3053
+ })(), ["$field", field], value];
3054
+ if (!this.request.where) this.request.where = w;
3055
+ else {
3056
+ if (this.request.where[0] == "$or") {
3057
+ const i = this.request.where.length - 1;
3058
+ if (this.request.where[i] == null) this.request.where[i] = w;
3059
+ else {
3060
+ if (this.request.where[i][0] == "$and") this.request.where[i].push(w);
3061
+ else this.request.where[i] = ["$and", this.request.where[i], w];
3062
+ }
3063
+ } else this.request.where.push(w);
3064
+ }
3065
+ }
3066
+ return this;
3067
+ }
3068
+ }
3069
+ class Slice {
3070
+ /**
3071
+ * An object to aid in constructing requests
3072
+ *
3073
+ * @param {number} slice Slice ID to interact with
3074
+ * @param {Api} api Api to send the requests through
3075
+ */
3076
+ constructor(slice, api) {
3077
+ __publicField(this, "table");
3078
+ __publicField(this, "info");
3079
+ __publicField(this, "loaded", false);
3080
+ __publicField(this, "pendingInsert", 0);
3081
+ /** Unsubscribe from changes, undefined if not subscribed */
3082
+ __publicField(this, "unsubscribe");
3083
+ /** Cached slice data as an observable */
3084
+ __publicField(this, "cache$", new BehaviorSubject([]));
3085
+ var _a;
3086
+ this.slice = slice;
3087
+ this.api = api;
3088
+ if (this.offlineEnabled) {
3089
+ this.table = (_a = api.database) == null ? void 0 : _a.table(slice.toString());
3090
+ this.table.getAll().then((resp) => this.cache = resp).finally(() => this.loaded = true);
3091
+ this.cache$.pipe(skip(1)).subscribe(async (cache) => {
3092
+ var _a2;
3093
+ await ((_a2 = this.table) == null ? void 0 : _a2.clear());
3094
+ await Promise.all(cache.map((c) => {
3095
+ var _a3;
3096
+ return (_a3 = this.table) == null ? void 0 : _a3.put(c.id, c);
3097
+ }));
3098
+ this.fixIncrement();
3099
+ });
3100
+ this.sync();
3101
+ window.addEventListener("online", async () => {
3102
+ if (this.api.expired) await lastValueFrom(this.api.auth.user$.pipe(skip(1), takeWhile((u) => !u || this.api.expired, true)));
3103
+ this.pushChanges();
3104
+ });
3105
+ } else {
3106
+ this.loaded = true;
3107
+ }
3108
+ }
3109
+ /** Cached slice data */
3110
+ get cache() {
3111
+ return this.cache$.getValue();
3112
+ }
3113
+ /** Set cached data & alert subscribers */
3114
+ set cache(cache) {
3115
+ this.cache$.next(cache);
3116
+ }
3117
+ /** Is slice offline support enabled */
3118
+ get offlineEnabled() {
3119
+ var _a;
3120
+ return (_a = this.api.database) == null ? void 0 : _a.includes(this.slice.toString());
3121
+ }
3122
+ fixIncrement() {
3123
+ var _a;
3124
+ this.pendingInsert = ((_a = this.cache.toSorted(sortByProp("id")).pop()) == null ? void 0 : _a["id"]) || 0;
3125
+ }
3126
+ execWrapper(call) {
3127
+ const onlineExec = call.exec.bind(call);
3128
+ return async () => {
3129
+ if (this.offlineEnabled && navigator && !(navigator == null ? void 0 : navigator.onLine)) {
3130
+ const where = (row, condition) => {
3131
+ if (Array.isArray(condition) ? !condition.length : condition == null) return true;
3132
+ if (!Array.isArray(condition)) return condition;
3133
+ if (condition[0] == "$field") return row[condition[1]];
3134
+ if (condition[0] == "$not") return !where(row, condition.slice(1));
3135
+ if (condition[0] == "$and") return condition.slice(1).filter((v) => where(row, v)).length == condition.length - 1;
3136
+ if (condition[0] == "$or") return !!condition.slice(1).find((v) => where(row, v));
3137
+ if (condition[0] == "$eq") return where(row, condition[1]) == where(row, condition[2]);
3138
+ if (condition[0] == "$neq") return where(row, condition[1]) != where(row, condition[2]);
3139
+ if (condition[0] == "$gt") return where(row, condition[1]) > where(row, condition[2]);
3140
+ if (condition[0] == "$gte") return where(row, condition[1]) >= where(row, condition[2]);
3141
+ if (condition[0] == "$lt") return where(row, condition[1]) < where(row, condition[2]);
3142
+ if (condition[0] == "$lte") return where(row, condition[1]) <= where(row, condition[2]);
3143
+ if (condition[0] == "$mod") return where(row, condition[1]) % where(row, condition[2]);
3144
+ return condition[0];
3145
+ };
3146
+ await sleepWhile(() => !this.loaded);
3147
+ let request = call.raw, resp = {};
3148
+ if (request["$/slice/delete"]) {
3149
+ const found = this.cache.filter((r) => where(r, request["$/slice/delete"]["where"])).map((r) => r.id);
3150
+ this.cache = this.cache.map((r) => found.includes(r.id) ? { ...r, _sync: "delete" } : r);
3151
+ resp = {
3152
+ affected: found.length,
3153
+ "ignored-keys": [],
3154
+ keys: found,
3155
+ tx: null
3156
+ };
3157
+ } else if (request["$/slice/report"]) {
3158
+ resp["rows"] = deepCopy(this.cache).filter((r) => (r == null ? void 0 : r._sync) != "delete").filter((r) => r && where(r, request["$/slice/report"]["where"]));
3159
+ if (request["order"]) resp["rows"] = resp["rows"].toSorted(sortByProp(request["order"][1][1], request["order"] == "$desc"));
3160
+ if (request["limit"]) resp["rows"] = resp["rows"].slice(0, request["limit"]);
3161
+ if (request["fields"]) {
3162
+ if (request["fields"]["$count"]) resp["rows"] = { count: resp["rows"].length };
3163
+ else resp["rows"] = resp["rows"].map((r) => Object.entries(request["fields"]).reduce((acc, [k, v]) => ({
3164
+ ...acc,
3165
+ [v]: r[k]
3166
+ }), {}));
3167
+ }
3168
+ } else if (request["$/slice/xinsert"]) {
3169
+ const rows = request["$/slice/xinsert"]["rows"].map((r) => ({
3170
+ ...r,
3171
+ id: -++this.pendingInsert,
3172
+ _sync: "insert"
3173
+ }));
3174
+ this.cache = [...this.cache, ...rows];
3175
+ resp = {
3176
+ failed: [],
3177
+ granted: rows.map((r) => Object.keys(r).reduce((acc, key) => ({ ...acc, [key]: true }), {})),
3178
+ "ignored-fields": [],
3179
+ keys: rows.map((r) => r.id),
3180
+ publish: 1,
3181
+ tx: null
3182
+ };
3183
+ } else if (request["$/slice/xupdate"]) {
3184
+ const ids = request["$/slice/xupdate"]["rows"].map((r) => r.id);
3185
+ this.cache = [
3186
+ ...this.cache.filter((c) => !ids.includes(c.id)),
3187
+ ...request["$/slice/xupdate"]["rows"].map((r) => ({ ...r, _sync: "update" }))
3188
+ ].toSorted(sortByProp("id"));
3189
+ resp = {
3190
+ failed: [],
3191
+ granted: request["$/slice/xupdate"]["rows"].map((r) => Object.keys(r).reduce((acc, key) => ({
3192
+ ...acc,
3193
+ [key]: true
3194
+ }), {})),
3195
+ "ignored-fields": [],
3196
+ keys: request["$/slice/xupdate"]["rows"].map((r) => r.id),
3197
+ publish: 1,
3198
+ tx: null
3199
+ };
3200
+ }
3201
+ if (request["$pop"])
3202
+ resp = request["$pop"].split(":").reduce((acc, key) => acc[JSONAttemptParse(key)], resp);
3203
+ return resp;
3204
+ } else {
3205
+ return onlineExec();
3206
+ }
3207
+ };
3208
+ }
3209
+ async pushChanges() {
3210
+ if (this.offlineEnabled && this.api.online) {
3211
+ await Promise.allSettled(
3212
+ this.cache.values().map((value) => {
3213
+ if (value._sync == "delete") {
3214
+ return this.delete(value.id).exec();
3215
+ } else if (value._sync == "insert") {
3216
+ return this.insert({ ...value, id: void 0, _sync: void 0 }).exec();
3217
+ } else if (value._sync == "update") {
3218
+ return this.update({
3219
+ ...value,
3220
+ _sync: void 0
3221
+ }).where("_updatedDate", "==", value.modified).exec();
3222
+ }
3223
+ }).filter((r) => !!r)
3224
+ );
3225
+ }
3226
+ }
3227
+ /**
3228
+ * Get slice information
3229
+ * @param reload Ignore cache & reload info
3230
+ * @return {Promise<SliceInfo>}
3231
+ */
3232
+ async getInfo(reload) {
3233
+ var _a, _b, _c;
3234
+ const getType = (field) => {
3235
+ if (field.options) {
3236
+ let t = field.options.split("|").map((o) => `'${o}'`).join(" | ");
3237
+ if (field.type == "control_checkbox") t = `(${t})[]`;
3238
+ return t;
3239
+ }
3240
+ if (field.type == "control_checkbox" || field.type == "boolean") return "boolean";
3241
+ if (field.type == "control_new_date" || field.type == "control_new_time" || field.type == "control_new_datetime" || field.type == "Date")
3242
+ return "Date";
3243
+ if (field.type == "control_number" || field.type == "number") return "number";
3244
+ return "string";
3245
+ };
3246
+ if (this.info && !reload) return Promise.resolve(this.info);
3247
+ this.info = await this.api.request({ "$/slice/fetch": { slice: this.slice } });
3248
+ const fields = ((_c = (_b = (_a = this.info) == null ? void 0 : _a.meta) == null ? void 0 : _b.presentation) == null ? void 0 : _c.fields) ? Object.values(this.info.meta.presentation.fields) : [];
3249
+ this.info.types = fields.filter((value) => value.id != void 0).map((value) => {
3250
+ var _a2;
3251
+ return {
3252
+ key: value.id.toString(),
3253
+ options: (_a2 = value.options) == null ? void 0 : _a2.split("|"),
3254
+ readonly: !!value.readonly || value.id.startsWith("fid") || ["id", "creatorRef", "created", "modifierRef", "modified"].includes(value.id),
3255
+ required: !!value.required,
3256
+ type: getType(value)
3257
+ };
3258
+ });
3259
+ return this.info;
3260
+ }
3261
+ /**
3262
+ * Synchronize cache with server
3263
+ * @example
3264
+ * ```ts
3265
+ * const slice: Slice = new Slice<T>(Slices.Contact);
3266
+ * slice.sync().subscribe((rows: T[]) => {});
3267
+ * ```
3268
+ * @param {boolean} on Enable/disable events
3269
+ * @return {BehaviorSubject<T[]>} Cache which can be subscribed to
3270
+ */
3271
+ sync(on = true) {
3272
+ if (on) {
3273
+ this.pushChanges().then(() => this.select().rows().exec().then((rows) => {
3274
+ this.cache = rows;
3275
+ this.loaded = true;
3276
+ }));
3277
+ if (!this.unsubscribe) this.unsubscribe = this.api.socket.sliceEvents(this.slice, (event) => {
3278
+ const ids = [...event.data.new, ...event.data.changed];
3279
+ this.select(ids).rows().exec().then((rows) => this.cache = [...this.cache.filter((c) => c.id != null && !ids.includes(c.id)), ...rows]);
3280
+ this.cache = this.cache.filter((v) => v.id && !event.data.lost.includes(v.id));
3281
+ });
3282
+ return this.cache$;
3283
+ } else if (this.unsubscribe) {
3284
+ this.unsubscribe();
3285
+ this.unsubscribe = null;
3286
+ }
3287
+ }
3288
+ // Transaction wrapper =============================================================================================
3289
+ /**
3290
+ * {@inheritDoc ApiCall.count}
3291
+ */
3292
+ count(arg = "id") {
3293
+ const call = new ApiCall(this.api, this.slice);
3294
+ call.exec = this.execWrapper(call);
3295
+ return call.count(arg);
3296
+ }
3297
+ /**
3298
+ * {@inheritDoc ApiCall.delete}
3299
+ */
3300
+ delete(id) {
3301
+ const call = new ApiCall(this.api, this.slice);
3302
+ call.exec = this.execWrapper(call);
3303
+ return call.delete(id);
3304
+ }
3305
+ /**
3306
+ * {@inheritDoc ApiCall.insert}
3307
+ */
3308
+ insert(rows) {
3309
+ const call = new ApiCall(this.api, this.slice);
3310
+ call.exec = this.execWrapper(call);
3311
+ return call.insert(rows);
3312
+ }
3313
+ /**
3314
+ * {@inheritDoc ApiCall.save}
3315
+ */
3316
+ save(rows) {
3317
+ const call = new ApiCall(this.api, this.slice);
3318
+ call.exec = this.execWrapper(call);
3319
+ return call.save(rows);
3320
+ }
3321
+ /**
3322
+ * {@inheritDoc ApiCall.select}
3323
+ */
3324
+ select(id) {
3325
+ const call = new ApiCall(this.api, this.slice);
3326
+ call.exec = this.execWrapper(call);
3327
+ return call.select(id);
3328
+ }
3329
+ /**
3330
+ * {@inheritDoc ApiCall.update}
3331
+ */
3332
+ update(rows) {
3333
+ const call = new ApiCall(this.api, this.slice);
3334
+ call.exec = this.execWrapper(call);
3335
+ return call.update(rows);
3336
+ }
3337
+ }
3338
+ class Socket {
3339
+ constructor(api, options = {}) {
3340
+ __publicField(this, "listeners", []);
3341
+ // [ Callback, Re-subscribe ]
3342
+ __publicField(this, "retry");
3343
+ __publicField(this, "socket");
3344
+ __publicField(this, "open", false);
3345
+ this.api = api;
3346
+ this.options = options;
3347
+ if (!options.url && options.url !== false) {
3348
+ const origin = new URL(this.api.url).origin;
3349
+ this.options.url = origin.replace("http", "ws").replace(/:\d+/g, "") + `:9390`;
3350
+ }
3351
+ if (this.options.url !== false)
3352
+ api.token$.pipe(filter((u) => u !== void 0), distinctUntilChanged()).subscribe(() => this.connect());
3353
+ }
3354
+ /**
3355
+ * Add listener for all socket events
3356
+ *
3357
+ * @param {SocketListener} fn Callback function
3358
+ *
3359
+ *
3360
+ *
3361
+ *
3362
+ * @return {Unsubscribe} Function to unsubscribe callback
3363
+ */
3364
+ addListener(fn, reconnect) {
3365
+ this.listeners.push([fn, reconnect]);
3366
+ if (this.open) reconnect();
3367
+ return () => this.listeners = this.listeners.filter((l) => l[0] != fn);
3368
+ }
3369
+ /**
3370
+ * Close socket connection
3371
+ */
3372
+ close() {
3373
+ var _a;
3374
+ if (this.open) console.debug("Datalynk socket: disconnected");
3375
+ this.open = false;
3376
+ (_a = this.socket) == null ? void 0 : _a.close();
3377
+ this.socket = void 0;
3378
+ if (this.retry) clearTimeout(this.retry);
3379
+ this.retry = null;
3380
+ }
3381
+ /**
3382
+ * Connect socket client to socket server
3383
+ * @param {number} timeout Retry to connect every x seconds
3384
+ */
3385
+ connect(timeout = 30) {
3386
+ if (this.options.url === false) return console.warn("Datalynk socket disabled");
3387
+ if (this.open) this.close();
3388
+ this.retry = setTimeout(() => {
3389
+ if (this.open) return;
3390
+ this.close();
3391
+ this.connect();
3392
+ }, timeout * 1e3);
3393
+ if (this.api.online) {
3394
+ this.socket = new WebSocket(this.options.url + (this.api.token ? `?token=${this.api.token}&origin=${location.href}` : ""));
3395
+ this.socket.onopen = () => clearTimeout(this.retry);
3396
+ this.socket.onclose = () => {
3397
+ if (this.open) this.connect(timeout);
3398
+ };
3399
+ this.socket.onmessage = (message) => {
3400
+ const payload = JSON.parse(message.data);
3401
+ if (payload.connected != void 0) {
3402
+ if (payload.connected) {
3403
+ this.open = true;
3404
+ console.debug("Datalynk socket: connected");
3405
+ this.listeners.forEach((l) => l[1]());
3406
+ } else {
3407
+ throw new Error(`Datalynk socket failed: ${payload.error}`);
3408
+ }
3409
+ } else {
3410
+ this.listeners.forEach((l) => l[0](payload));
3411
+ }
3412
+ };
3413
+ }
3414
+ }
3415
+ /**
3416
+ * Send data to socket server
3417
+ *
3418
+ * @param payload Data that will be serialized
3419
+ */
3420
+ send(payload) {
3421
+ var _a;
3422
+ if (!this.open) throw new Error("Datalynk socket not connected");
3423
+ (_a = this.socket) == null ? void 0 : _a.send(JSON.stringify(payload));
3424
+ }
3425
+ /**
3426
+ * Run callback whenever the server notifies us of slice changes
3427
+ *
3428
+ * @param {number | number[]} slice Slice to subscribe to
3429
+ * @param {SocketListener<SocketEventSlice>} callback Function to run on changes
3430
+ * @return {Unsubscribe} Run returned function to unsubscribe callback
3431
+ */
3432
+ sliceEvents(slice, callback) {
3433
+ const unsubscribe = this.addListener((event) => {
3434
+ if (event.type == "sliceEvents" && event.data.slice == slice) callback(event);
3435
+ }, () => this.send({ onSliceEvents: slice }));
3436
+ return () => {
3437
+ this.send({ offSliceEvents: slice });
3438
+ unsubscribe();
3439
+ };
3440
+ }
3441
+ }
3442
+ class Superuser {
3443
+ constructor(api) {
3444
+ this.api = api;
3445
+ }
3446
+ /**
3447
+ * Switch to another user by ID
3448
+ *
3449
+ * @param {number} userId User ID
3450
+ * @return {Promise<any>} New session
3451
+ */
3452
+ assume(userId) {
3453
+ return this.api.request({ "$/report/users/become": { id: userId } }).then((resp) => {
3454
+ if (resp.token) this.api.token = resp.token;
3455
+ return resp;
3456
+ });
3457
+ }
3458
+ /**
3459
+ * Enable the superuser flag, required to make any of the requests in this helper
3460
+ *
3461
+ * @param {string} username Superuser account
3462
+ * @param {string} password Superuser password
3463
+ * @return {Promise<any>} Unknown
3464
+ */
3465
+ enable(username, password) {
3466
+ return this.api.request({ "$/superuser/validate": {
3467
+ name: username,
3468
+ password
3469
+ } });
3470
+ }
3471
+ }
3472
+ const version = "1.3.5";
3473
+ class WebRtc {
3474
+ constructor(api) {
3475
+ __publicField(this, "ice");
3476
+ var _a, _b, _c, _d, _e, _f;
3477
+ this.api = api;
3478
+ this.ice = [
3479
+ ...((_b = (_a = api.options) == null ? void 0 : _a.webrtc) == null ? void 0 : _b.ice) || [],
3480
+ { urls: ["stun:" + ((_c = this.api.options.webrtc) == null ? void 0 : _c.url)] },
3481
+ clean({
3482
+ urls: ["turn:" + ((_d = this.api.options.webrtc) == null ? void 0 : _d.url)],
3483
+ username: (_e = this.api.options.webrtc) == null ? void 0 : _e.username,
3484
+ credential: (_f = this.api.options.webrtc) == null ? void 0 : _f.password
3485
+ })
3486
+ ];
3487
+ }
3488
+ async answer(offer, stream) {
3489
+ const rtc = new RTCPeerConnection({ iceServers: this.ice });
3490
+ stream.getTracks().forEach((track) => rtc.addTrack(track, stream));
3491
+ await rtc.setRemoteDescription(new RTCSessionDescription(offer));
3492
+ const answer = await rtc.createAnswer();
3493
+ await rtc.setLocalDescription(answer);
3494
+ await new Promise((res) => {
3495
+ if (rtc.iceGatheringState === "complete") return res();
3496
+ rtc.onicegatheringstatechange = () => {
3497
+ if (rtc.iceGatheringState === "complete") res();
3498
+ };
3499
+ });
3500
+ return rtc;
3501
+ }
3502
+ async offer(stream) {
3503
+ const rtc = new RTCPeerConnection({ iceServers: this.ice });
3504
+ stream.getTracks().forEach((track) => rtc.addTrack(track, stream));
3505
+ await rtc.setLocalDescription(await rtc.createOffer());
3506
+ await new Promise((res) => {
3507
+ if (rtc.iceGatheringState === "complete") return res();
3508
+ rtc.onicegatheringstatechange = () => {
3509
+ if (rtc.iceGatheringState === "complete") res();
3510
+ };
3511
+ });
3512
+ return rtc;
3513
+ }
3514
+ /**
3515
+ * Create a new WebRTC connection to a room
3516
+ * @param {string} id Room ID
3517
+ * @param {boolean} audio Stream local audio to room/peers
3518
+ * @param {boolean} video Stream local video to room/peers
3519
+ * @returns {Promise<WebRTCSession>} Connection session
3520
+ */
3521
+ async connect(id = randomStringBuilder(16, true, true), audio = true, video = true) {
3522
+ const session = {
3523
+ open: true,
3524
+ id,
3525
+ uid: randomStringBuilder(8, true, true),
3526
+ peers: {},
3527
+ stream: await navigator.mediaDevices.getUserMedia({ audio, video }),
3528
+ disconnect: null,
3529
+ onConnected: null
3530
+ };
3531
+ const handleTracks = (session2, uid) => {
3532
+ if (!session2.open || !session2.onConnected) return;
3533
+ const peer = session2.peers[uid];
3534
+ const streams = peer.connection.getRemoteStreams();
3535
+ if (streams[0]) session2.onConnected(peer, streams[0]);
3536
+ else peer.connection.ontrack = ({ streams: streams2 }) => {
3537
+ if (session2.open && session2.onConnected) session2.onConnected(peer, streams2[0]);
3538
+ };
3539
+ };
3540
+ const unsubscribe = this.api.socket.addListener(async (event) => {
3541
+ var _a, _b, _c, _d;
3542
+ const key = Object.keys(event)[0];
3543
+ if (key == `webrtc/${id}`) {
3544
+ if (event[key].connected) {
3545
+ const payload = event[key].connected;
3546
+ session.peers[payload.uid] = {
3547
+ uid: payload.uid,
3548
+ username: payload.username,
3549
+ connection: await this.offer(session.stream)
3550
+ };
3551
+ this.api.socket.send({ [`webrtc/${id}`]: { offer: {
3552
+ to: payload.uid,
3553
+ uid: session.uid,
3554
+ username: (_a = this.api.auth.user) == null ? void 0 : _a.login,
3555
+ offer: session.peers[payload.uid].connection.localDescription
3556
+ } } });
3557
+ } else if (event[key].disconnected) {
3558
+ session.peers[event[key].disconnected.uid].connection.close();
3559
+ delete session.peers[event[key].disconnected.uid];
3560
+ } else if (event[key].offer && event[key].offer.to == session.uid) {
3561
+ const payload = event[key].offer;
3562
+ session.peers[payload.uid] = {
3563
+ uid: payload.uid,
3564
+ username: payload.username,
3565
+ connection: await this.answer(payload.offer, session.stream)
3566
+ };
3567
+ this.api.socket.send({ [`webrtc/${id}`]: { answer: {
3568
+ to: payload.uid,
3569
+ uid: session.uid,
3570
+ username: (_b = this.api.auth.user) == null ? void 0 : _b.login,
3571
+ answer: session.peers[payload.uid].connection.localDescription
3572
+ } } });
3573
+ handleTracks(session, payload.uid);
3574
+ } else if (event[key].answer && event[key].answer.to == session.uid) {
3575
+ (_d = (_c = session.peers[event[key].answer.uid]) == null ? void 0 : _c.connection) == null ? void 0 : _d.setRemoteDescription(new RTCSessionDescription(event[key].answer.answer));
3576
+ handleTracks(session, event[key].answer.uid);
3577
+ }
3578
+ }
3579
+ }, () => {
3580
+ var _a;
3581
+ return this.api.socket.send({ [`webrtc/${id}`]: { connected: { uid: session.uid, username: (_a = this.api.auth.user) == null ? void 0 : _a.login } } });
3582
+ });
3583
+ session.disconnect = () => {
3584
+ var _a;
3585
+ session.open = false;
3586
+ session.peers = {};
3587
+ this.api.socket.send({ [`webrtc/${id}`]: { disconnected: { uid: session.uid, username: (_a = this.api.auth.user) == null ? void 0 : _a.login } } });
3588
+ unsubscribe();
3589
+ };
3590
+ return session;
3591
+ }
3592
+ }
3593
+ const _Api = class _Api {
3594
+ /**
3595
+ * Connect to Datalynk & send requests
3596
+ *
3597
+ * @example
3598
+ * ```ts
3599
+ * const api = new Api('https://spoke.auxiliumgroup.com');
3600
+ * ```
3601
+ *
3602
+ * @param {string} origin API URL
3603
+ * @param {ApiOptions} options
3604
+ */
3605
+ constructor(origin, options = {}) {
3606
+ /** Current requests bundle */
3607
+ __publicField(this, "bundle", []);
3608
+ /** Bundle lifecycle tracking */
3609
+ __publicField(this, "bundleOngoing", false);
3610
+ /** Track online state */
3611
+ __publicField(this, "heartbeat", {
3612
+ interval: null,
3613
+ target: "version.php",
3614
+ timeout: 6e4
3615
+ });
3616
+ /** LocalStorage key for persisting logins */
3617
+ __publicField(this, "localStorageKey", "datalynk-token");
3618
+ /** Pending requests cache */
3619
+ __publicField(this, "pending", {});
3620
+ /** Helpers */
3621
+ /** Authentication */
3622
+ __publicField(this, "auth");
3623
+ /** File */
3624
+ __publicField(this, "files");
3625
+ /** PDF */
3626
+ __publicField(this, "pdf");
3627
+ /** PWA setup & prompt */
3628
+ __publicField(this, "pwa");
3629
+ /** Socket */
3630
+ __publicField(this, "socket");
3631
+ /** Superuser */
3632
+ __publicField(this, "superuser");
3633
+ /** WebRTC */
3634
+ __publicField(this, "webrtc");
3635
+ /** Offline database */
3636
+ __publicField(this, "database");
3637
+ /** Options */
3638
+ __publicField(this, "options");
3639
+ /** Created slices */
3640
+ __publicField(this, "sliceCache", /* @__PURE__ */ new Map());
3641
+ /** API URL */
3642
+ __publicField(this, "url");
3643
+ /** Client library version */
3644
+ __publicField(this, "version", version);
3645
+ __publicField(this, "onlineOverride", false);
3646
+ __publicField(this, "_online", typeof navigator == "undefined" ? true : navigator.onLine);
3647
+ /** API Session token */
3648
+ __publicField(this, "token$", new BehaviorSubject(void 0));
3649
+ var _a, _b;
3650
+ this.origin = origin;
3651
+ this.url = `${new URL(origin).origin}/api/`;
3652
+ this.options = {
3653
+ manifest: {},
3654
+ name: typeof document != "undefined" ? document.title : "Datalynk",
3655
+ offline: [],
3656
+ origin: typeof location !== "undefined" ? location.host : "Unknown",
3657
+ saveSession: true,
3658
+ serviceWorker: "/service.worker.mjs",
3659
+ ...options,
3660
+ webrtc: {
3661
+ url: "scarborough.auxilium.world:3478",
3662
+ username: "auxilium-webrtc",
3663
+ password: "UU3qkD95Tg54eF",
3664
+ ...options.webrtc || {}
3665
+ }
3666
+ };
3667
+ if (this.options.saveSession) {
3668
+ if (typeof localStorage == "undefined") return;
3669
+ this.token = localStorage.getItem(this.localStorageKey) || null;
3670
+ this.token$.pipe(distinctUntilChanged()).subscribe((token) => {
3671
+ if (token) localStorage.setItem(this.localStorageKey, token);
3672
+ else localStorage.removeItem(this.localStorageKey);
3673
+ });
3674
+ }
3675
+ this.socket = new Socket(this, { url: options.socket });
3676
+ this.auth = new Auth(this);
3677
+ this.files = new Files(this);
3678
+ this.pdf = new Pdf(this);
3679
+ this.pwa = new PWA(this);
3680
+ this.superuser = new Superuser(this);
3681
+ this.webrtc = new WebRtc(this);
3682
+ if (typeof window !== "undefined") {
3683
+ const handleOffline = (state) => {
3684
+ this._online = state;
3685
+ this.offlineBanner();
3686
+ };
3687
+ window.addEventListener("online", () => handleOffline(true));
3688
+ window.addEventListener("offline", () => handleOffline(false));
3689
+ this.startHeartbeat();
3690
+ this.offlineBanner();
3691
+ }
3692
+ if ((_a = this.options.offline) == null ? void 0 : _a.length) {
3693
+ this.pwa.setup();
3694
+ if (typeof indexedDB == "undefined") throw new Error("Cannot enable offline support, indexedDB is not available in this environment");
3695
+ this.database = new Database("datalynk", this.options.offline);
3696
+ (_b = this.options.offline) == null ? void 0 : _b.forEach((id) => this.slice(id));
3697
+ if (this.options.serviceWorker && typeof navigator["serviceWorker"] != "undefined") {
3698
+ (async () => {
3699
+ const init = () => {
3700
+ var _a2;
3701
+ (_a2 = navigator.serviceWorker.controller) == null ? void 0 : _a2.postMessage({ options: { ...this.options, url: this.url } });
3702
+ this.token$.subscribe((token) => {
3703
+ var _a3;
3704
+ return (_a3 = navigator.serviceWorker.controller) == null ? void 0 : _a3.postMessage({ token });
3705
+ });
3706
+ };
3707
+ await navigator.serviceWorker.getRegistration(this.options.serviceWorker).then((reg) => reg ?? navigator.serviceWorker.register(this.options.serviceWorker, { scope: "/", type: "module" }));
3708
+ navigator.serviceWorker.ready.then(() => {
3709
+ if (navigator.serviceWorker.controller) navigator.serviceWorker.ready.then(() => init());
3710
+ else navigator.serviceWorker.addEventListener("controllerchange", () => init(), { once: true });
3711
+ });
3712
+ })();
3713
+ }
3714
+ }
3715
+ }
3716
+ /** Is token expired */
3717
+ get expired() {
3718
+ var _a;
3719
+ return (((_a = this.jwtPayload) == null ? void 0 : _a.exp) ?? Infinity) * 1e3 <= Date.now();
3720
+ }
3721
+ /** Get session info from JWT payload */
3722
+ get jwtPayload() {
3723
+ if (!this.token) return null;
3724
+ return decodeJwt(this.token);
3725
+ }
3726
+ /** Check if we are connected */
3727
+ get online() {
3728
+ return this._online;
3729
+ }
3730
+ get offline() {
3731
+ return !this._online;
3732
+ }
3733
+ /** Override connection status */
3734
+ set online(value) {
3735
+ if (value == null) {
3736
+ this.onlineOverride = false;
3737
+ this._online = typeof navigator == "undefined" ? true : navigator.onLine;
3738
+ } else {
3739
+ this.onlineOverride = true;
3740
+ if (value == this.online) return;
3741
+ this._online = value;
3742
+ if (value) this.startHeartbeat();
3743
+ else this.stopHeartbeat();
3744
+ }
3745
+ this.offlineBanner();
3746
+ }
3747
+ /** Logged in spoke */
3748
+ get spoke() {
3749
+ var _a;
3750
+ return (_a = this.jwtPayload) == null ? void 0 : _a.realm;
3751
+ }
3752
+ get token() {
3753
+ return this.token$.getValue();
3754
+ }
3755
+ set token(token) {
3756
+ this.token$.next(token);
3757
+ }
3758
+ _request(req, options = {}) {
3759
+ const token = options.token || this.token;
3760
+ return fetch(this.url, {
3761
+ method: "POST",
3762
+ headers: clean({
3763
+ Authorization: token ? `Bearer ${token}` : void 0,
3764
+ "Content-Type": "application/json",
3765
+ "X-Date-Return-Format": this.options.legacyDates ? void 0 : "ISO8601"
3766
+ }),
3767
+ body: JSON.stringify(_Api.translateTokens(req))
3768
+ }).then(async (resp) => {
3769
+ this.online = true;
3770
+ let data = JSONAttemptParse(await resp.text());
3771
+ if (!resp.ok || (data == null ? void 0 : data.error)) throw Object.assign(errorFromCode(resp.status, data.error), data);
3772
+ if (!options.raw) data = _Api.translateTokens(data);
3773
+ return data;
3774
+ });
3775
+ }
3776
+ async checkConnection() {
3777
+ if (typeof navigator != "undefined" && !navigator.onLine) {
3778
+ this._online = false;
3779
+ return;
3780
+ }
3781
+ if (this.onlineOverride) return;
3782
+ const controller = new AbortController();
3783
+ const timeout = setTimeout(() => controller.abort(), this.heartbeat.timeout);
3784
+ try {
3785
+ const response = await fetch(this.url + this.heartbeat.target, { signal: controller.signal });
3786
+ this._online = response.ok;
3787
+ } catch (error) {
3788
+ this._online = false;
3789
+ } finally {
3790
+ clearTimeout(timeout);
3791
+ }
3792
+ }
3793
+ offlineBanner() {
3794
+ if (this.options.offlineBanner === false || typeof document == "undefined") return;
3795
+ const banner = document.querySelector(".datalynk-offline-banner");
3796
+ if (this.online) {
3797
+ banner == null ? void 0 : banner.remove();
3798
+ } else if (!banner) {
3799
+ const b = document.createElement("div");
3800
+ b.className = "datalynk-offline-banner";
3801
+ Object.assign(b.style, { position: "fixed", [this.options.offlineBanner === "top" ? "top" : "bottom"]: "0", left: "0", right: "0", padding: ".75rem", fontSize: "1rem", fontWeight: "bolder", backgroundColor: "#dc3545", color: "#fff", textAlign: "center", zIndex: "9999" });
3802
+ b.innerHTML = "⚠️ You are offline, please reconnect to sync changes";
3803
+ document.body.appendChild(b);
3804
+ }
3805
+ }
3806
+ startHeartbeat() {
3807
+ this.stopHeartbeat();
3808
+ this.heartbeat.interval = setInterval(() => this.checkConnection(), this.heartbeat.timeout / 2);
3809
+ this.checkConnection();
3810
+ }
3811
+ stopHeartbeat() {
3812
+ if (this.heartbeat.interval) {
3813
+ clearInterval(this.heartbeat.interval);
3814
+ this.heartbeat.interval = null;
3815
+ }
3816
+ }
3817
+ /**
3818
+ * Get list of slices
3819
+ * @return {Promise<number[]>}
3820
+ */
3821
+ getSlices() {
3822
+ return this.request({ "$/tools/action_chain": [
3823
+ { "!/env/me": {} },
3824
+ { "!/slice/permissionsLite": {} },
3825
+ { "!/tools/column": { "col": "id", "rows": { "$_": "1:rows" } } }
3826
+ ] });
3827
+ }
3828
+ /**
3829
+ * Parses API request/response object for special Datalynk tokens & converts them to native JS objects
3830
+ *
3831
+ * @param obj An API request or response
3832
+ * @return {Object} Api request or response with translated tokens
3833
+ * @private
3834
+ */
3835
+ static translateTokens(obj) {
3836
+ let dot = (obj2, param) => param.split(".").reduce((acc, index) => acc[index], obj2);
3837
+ let queue = Object.keys(obj);
3838
+ queue.forEach((key) => {
3839
+ let val = dot(obj, key);
3840
+ if (val !== null && typeof val == "object") {
3841
+ Object.keys(val).forEach((index) => {
3842
+ if (index in Serializer.deserialize) {
3843
+ val = Serializer.deserialize[index](val[index]);
3844
+ } else if (index in Serializer.serialize) {
3845
+ val = Serializer.serialize[index](val[index]);
3846
+ } else if (val[index] == "Yes") {
3847
+ val[index] = true;
3848
+ } else if (val[index] == "No") {
3849
+ val[index] = false;
3850
+ } else {
3851
+ queue.push(`${key}.${index}`);
3852
+ }
3853
+ });
3854
+ }
3855
+ });
3856
+ return obj;
3857
+ }
3858
+ /**
3859
+ * Chain multiple requests to execute together
3860
+ * @param {Slice<any>} requests List of requests to chain
3861
+ * @return {Promise<any>} API Response
3862
+ */
3863
+ chain(...requests) {
3864
+ const arr = requests.length == 1 && Array.isArray(requests[0]) ? requests[0] : requests;
3865
+ return this.request({ "$/tools/action_chain": arr.map((r) => {
3866
+ if (!(r instanceof ApiCall)) return r;
3867
+ const req = r.raw;
3868
+ Object.keys(req).forEach((key) => {
3869
+ if (key.startsWith("$/")) {
3870
+ req[key.replace("$", "!")] = req[key];
3871
+ delete req[key];
3872
+ }
3873
+ });
3874
+ return req;
3875
+ }) });
3876
+ }
3877
+ /**
3878
+ * Organize multiple requests into a single mapped request
3879
+ * @param {{[p: string]: any}} request Map of requests
3880
+ * @return {Promise<any>} Map of API Responses
3881
+ */
3882
+ chainMap(request) {
3883
+ return this.request({ "$/tools/do": [
3884
+ ...Object.entries(request).flatMap(([key, r]) => {
3885
+ if (!(r instanceof ApiCall)) return [key, r];
3886
+ const req = r.raw;
3887
+ Object.keys(req).forEach((key2) => {
3888
+ if (key2.startsWith("$/")) {
3889
+ req[key2.replace("$", "!")] = req[key2];
3890
+ delete req[key2];
3891
+ }
3892
+ });
3893
+ return [key, req];
3894
+ }),
3895
+ "returnAllBoilerplate",
3896
+ { "$_": "*" }
3897
+ ] }, {});
3898
+ }
3899
+ /**
3900
+ * Exact same as `request` method, but logs the response in the console automatically
3901
+ *
3902
+ * @param {object | string} data Datalynk request as object or string
3903
+ * @param {ApiRequestOptions} options
3904
+ * @returns {Promise<any>} Datalynk response
3905
+ */
3906
+ debug(data, options = {}) {
3907
+ return this.request(data, options).then((data2) => {
3908
+ console.log(data2);
3909
+ return data2;
3910
+ }).catch((err) => {
3911
+ console.error(err);
3912
+ return err;
3913
+ });
3914
+ }
3915
+ /**
3916
+ * Send a request to Datalynk
3917
+ *
3918
+ * @example
3919
+ * ```ts
3920
+ * const response = await api.request('$/auth/current');
3921
+ * ```
3922
+ *
3923
+ * @param {object} data Request using Datalynk API syntax. Strings will be converted: '$/auth/current' -> {'$/auth/current': {}}
3924
+ * @param {ApiRequestOptions} options
3925
+ * @returns {Promise<any>} Datalynk response or error
3926
+ */
3927
+ request(data, options = {}) {
3928
+ data = typeof data == "string" ? { [data]: {} } : data;
3929
+ if (options.noOptimize) {
3930
+ return new Promise((res, rej) => {
3931
+ this._request(data, options).then((resp) => {
3932
+ (resp == null ? void 0 : resp.error) ? rej(resp) : res(resp);
3933
+ }).catch((err) => rej(err));
3934
+ });
3935
+ }
3936
+ let key = JSON.stringify(data);
3937
+ if (!this.pending[key]) {
3938
+ this.pending[key] = new Promise((res, rej) => this.bundle.push({ data, res, rej }));
3939
+ this.pending[key].catch().then(() => delete this.pending[key]);
3940
+ if (!this.bundleOngoing) {
3941
+ this.bundleOngoing = true;
3942
+ setTimeout(() => {
3943
+ let originalBundle = this.bundle;
3944
+ this.bundle = [];
3945
+ this.bundleOngoing = false;
3946
+ data = originalBundle.map((row) => row.data);
3947
+ this._request(data, options).then((resp) => {
3948
+ if (!(resp instanceof Array)) resp = [resp];
3949
+ resp.forEach((row, i) => (row == null ? void 0 : row.error) ? originalBundle[i].rej(row.error) : originalBundle[i].res(row));
3950
+ }).catch((err) => originalBundle.forEach((req) => req.rej(err)));
3951
+ }, this.options.bundleTime);
3952
+ }
3953
+ }
3954
+ return this.pending[key];
3955
+ }
3956
+ /**
3957
+ * Create a slice object using the API
3958
+ *
3959
+ * @example
3960
+ * ```ts
3961
+ * const contactsSlice = api.slice<Contacts>(12345);
3962
+ * const allContacts = await contactsSlice.select().exec().rows();
3963
+ * const unsubscribe = contactsSlice.sync().subscribe(rows => console.log(rows));
3964
+ * ```
3965
+ *
3966
+ * @param {number} id Slice ID the object will target
3967
+ * @returns {Slice<T = any>} Object for making requests & caching rows
3968
+ */
3969
+ slice(id) {
3970
+ if (!this.sliceCache.has(+id)) this.sliceCache.set(+id, new Slice(id, this));
3971
+ return this.sliceCache.get(+id);
3972
+ }
3973
+ };
3974
+ /** Client library version */
3975
+ __publicField(_Api, "version", version);
3976
+ let Api = _Api;
3977
+ exports2.Api = Api;
3978
+ exports2.ApiCall = ApiCall;
3979
+ exports2.Auth = Auth;
3980
+ exports2.Files = Files;
3981
+ exports2.LoginPrompt = LoginPrompt;
3982
+ exports2.PWA = PWA;
3983
+ exports2.Pdf = Pdf;
3984
+ exports2.Serializer = Serializer;
3985
+ exports2.Slice = Slice;
3986
+ exports2.Socket = Socket;
3987
+ exports2.Superuser = Superuser;
3988
+ exports2.getTheme = getTheme;
3989
+ Object.defineProperty(exports2, Symbol.toStringTag, { value: "Module" });
3990
+ });