@auxilium/datalynk-client 1.0.20 → 1.1.0-rc1

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