@auxilium/datalynk-client 0.7.1 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,348 +1,400 @@
1
1
  var __defProp = Object.defineProperty;
2
2
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
3
  var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
4
- var rt = Object.defineProperty;
5
- var nt = (r, t, e) => t in r ? rt(r, t, { enumerable: true, configurable: true, writable: true, value: e }) : r[t] = e;
6
- var c = (r, t, e) => (nt(r, typeof t != "symbol" ? t + "" : t, e), e);
7
- function ot(r, t = false) {
8
- if (r == null)
9
- throw new Error("Cannot clean a NULL value");
10
- return Array.isArray(r) ? r = r.filter((e) => e != null) : Object.entries(r).forEach(([e, n]) => {
11
- (t && n === void 0 || !t && n == null) && delete r[e];
12
- }), r;
4
+ var __defProp2 = Object.defineProperty;
5
+ var __defNormalProp2 = (obj, key, value) => key in obj ? __defProp2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
6
+ var __publicField2 = (obj, key, value) => __defNormalProp2(obj, typeof key !== "symbol" ? key + "" : key, value);
7
+ function clean(obj, undefinedOnly = false) {
8
+ if (obj == null) throw new Error("Cannot clean a NULL value");
9
+ if (Array.isArray(obj)) {
10
+ obj = obj.filter((o) => o != null);
11
+ } else {
12
+ Object.entries(obj).forEach(([key, value]) => {
13
+ if (undefinedOnly && value === void 0 || !undefinedOnly && value == null) delete obj[key];
14
+ });
15
+ }
16
+ return obj;
13
17
  }
14
- function St(r) {
15
- const t = new FormData();
16
- return Object.entries(r).forEach(([e, n]) => t.append(e, n)), t;
18
+ function formData(target) {
19
+ const data = new FormData();
20
+ Object.entries(target).forEach(([key, value]) => data.append(key, value));
21
+ return data;
17
22
  }
18
- function T(r) {
23
+ function JSONAttemptParse(json) {
19
24
  try {
20
- return JSON.parse(r);
25
+ return JSON.parse(json);
21
26
  } catch {
22
- return r;
27
+ return json;
23
28
  }
24
29
  }
25
- class E extends Promise {
26
- constructor(e) {
27
- super((n, o) => e(
28
- (s) => n(s),
29
- (s) => o(s),
30
- (s) => this.progress = s
30
+ function JSONSanitize(obj, space) {
31
+ let cache = [];
32
+ return JSON.stringify(obj, (key, value) => {
33
+ if (typeof value === "object" && value !== null) {
34
+ if (cache.includes(value)) return;
35
+ cache.push(value);
36
+ }
37
+ return value;
38
+ }, space);
39
+ }
40
+ class PromiseProgress extends Promise {
41
+ constructor(executor) {
42
+ super((resolve, reject) => executor(
43
+ (value) => resolve(value),
44
+ (reason) => reject(reason),
45
+ (progress) => this.progress = progress
31
46
  ));
32
- c(this, "listeners", []);
33
- c(this, "_progress", 0);
47
+ __publicField2(this, "listeners", []);
48
+ __publicField2(this, "_progress", 0);
34
49
  }
35
50
  get progress() {
36
51
  return this._progress;
37
52
  }
38
- set progress(e) {
39
- e != this._progress && (this._progress = e, this.listeners.forEach((n) => n(e)));
53
+ set progress(p) {
54
+ if (p == this._progress) return;
55
+ this._progress = p;
56
+ this.listeners.forEach((l) => l(p));
40
57
  }
41
- static from(e) {
42
- return e instanceof E ? e : new E((n, o) => e.then((...s) => n(...s)).catch((...s) => o(...s)));
58
+ static from(promise) {
59
+ if (promise instanceof PromiseProgress) return promise;
60
+ return new PromiseProgress((res, rej) => promise.then((...args) => res(...args)).catch((...args) => rej(...args)));
43
61
  }
44
- from(e) {
45
- const n = E.from(e);
46
- return this.onProgress((o) => n.progress = o), n;
62
+ from(promise) {
63
+ const newPromise = PromiseProgress.from(promise);
64
+ this.onProgress((p) => newPromise.progress = p);
65
+ return newPromise;
47
66
  }
48
- onProgress(e) {
49
- return this.listeners.push(e), this;
67
+ onProgress(callback) {
68
+ this.listeners.push(callback);
69
+ return this;
50
70
  }
51
- then(e, n) {
52
- const o = super.then(e, n);
53
- return this.from(o);
71
+ then(res, rej) {
72
+ const resp = super.then(res, rej);
73
+ return this.from(resp);
54
74
  }
55
- catch(e) {
56
- return this.from(super.catch(e));
75
+ catch(rej) {
76
+ return this.from(super.catch(rej));
57
77
  }
58
- finally(e) {
59
- return this.from(super.finally(e));
78
+ finally(res) {
79
+ return this.from(super.finally(res));
60
80
  }
61
81
  }
62
- class v {
82
+ class TypedEmitter {
63
83
  constructor() {
64
- c(this, "listeners", {});
65
- }
66
- static emit(t, ...e) {
67
- (this.listeners["*"] || []).forEach((n) => n(t, ...e)), (this.listeners[t.toString()] || []).forEach((n) => n(...e));
84
+ __publicField2(this, "listeners", {});
68
85
  }
69
- static off(t, e) {
70
- const n = t.toString();
71
- this.listeners[n] = (this.listeners[n] || []).filter((o) => o === e);
86
+ static emit(event, ...args) {
87
+ (this.listeners["*"] || []).forEach((l) => l(event, ...args));
88
+ (this.listeners[event.toString()] || []).forEach((l) => l(...args));
72
89
  }
73
- static on(t, e) {
74
- var o;
75
- const n = t.toString();
76
- return this.listeners[n] || (this.listeners[n] = []), (o = this.listeners[n]) == null || o.push(e), () => this.off(t, e);
90
+ static off(event, listener) {
91
+ const e = event.toString();
92
+ this.listeners[e] = (this.listeners[e] || []).filter((l) => l === listener);
77
93
  }
78
- static once(t, e) {
79
- return new Promise((n) => {
80
- const o = this.on(t, (...s) => {
81
- n(s.length == 1 ? s[0] : s), e && e(...s), o();
94
+ static on(event, listener) {
95
+ var _a;
96
+ const e = event.toString();
97
+ if (!this.listeners[e]) this.listeners[e] = [];
98
+ (_a = this.listeners[e]) == null ? void 0 : _a.push(listener);
99
+ return () => this.off(event, listener);
100
+ }
101
+ static once(event, listener) {
102
+ return new Promise((res) => {
103
+ const unsubscribe = this.on(event, (...args) => {
104
+ res(args.length == 1 ? args[0] : args);
105
+ if (listener) listener(...args);
106
+ unsubscribe();
82
107
  });
83
108
  });
84
109
  }
85
- emit(t, ...e) {
86
- (this.listeners["*"] || []).forEach((n) => n(t, ...e)), (this.listeners[t] || []).forEach((n) => n(...e));
87
- }
88
- off(t, e) {
89
- this.listeners[t] = (this.listeners[t] || []).filter((n) => n === e);
110
+ emit(event, ...args) {
111
+ (this.listeners["*"] || []).forEach((l) => l(event, ...args));
112
+ (this.listeners[event] || []).forEach((l) => l(...args));
90
113
  }
91
- on(t, e) {
92
- var n;
93
- return this.listeners[t] || (this.listeners[t] = []), (n = this.listeners[t]) == null || n.push(e), () => this.off(t, e);
114
+ off(event, listener) {
115
+ this.listeners[event] = (this.listeners[event] || []).filter((l) => l === listener);
94
116
  }
95
- once(t, e) {
96
- return new Promise((n) => {
97
- const o = this.on(t, (...s) => {
98
- n(s.length == 1 ? s[0] : s), e && e(...s), o();
117
+ on(event, listener) {
118
+ var _a;
119
+ if (!this.listeners[event]) this.listeners[event] = [];
120
+ (_a = this.listeners[event]) == null ? void 0 : _a.push(listener);
121
+ return () => this.off(event, listener);
122
+ }
123
+ once(event, listener) {
124
+ return new Promise((res) => {
125
+ const unsubscribe = this.on(event, (...args) => {
126
+ res(args.length == 1 ? args[0] : args);
127
+ if (listener) listener(...args);
128
+ unsubscribe();
99
129
  });
100
130
  });
101
131
  }
102
132
  }
103
- c(v, "listeners", {});
104
- class p extends Error {
105
- constructor(e, n) {
106
- super(e);
107
- c(this, "_code");
108
- n != null && (this._code = n);
133
+ __publicField2(TypedEmitter, "listeners", {});
134
+ class CustomError extends Error {
135
+ constructor(message, code) {
136
+ super(message);
137
+ __publicField2(this, "_code");
138
+ if (code != null) this._code = code;
109
139
  }
110
140
  get code() {
111
141
  return this._code || this.constructor.code;
112
142
  }
113
- set code(e) {
114
- this._code = e;
143
+ set code(c) {
144
+ this._code = c;
115
145
  }
116
- static from(e) {
117
- const n = Number(e.statusCode) ?? Number(e.code), o = new this(e.message || e.toString());
118
- return Object.assign(o, {
119
- stack: e.stack,
120
- ...e,
121
- code: n ?? void 0
146
+ static from(err) {
147
+ const code = Number(err.statusCode) ?? Number(err.code);
148
+ const newErr = new this(err.message || err.toString());
149
+ return Object.assign(newErr, {
150
+ stack: err.stack,
151
+ ...err,
152
+ code: code ?? void 0
122
153
  });
123
154
  }
124
- static instanceof(e) {
125
- return e.constructor.code != null;
155
+ static instanceof(err) {
156
+ return err.constructor.code != void 0;
126
157
  }
127
158
  toString() {
128
159
  return this.message || super.toString();
129
160
  }
130
161
  }
131
- c(p, "code", 500);
132
- class Y extends p {
133
- constructor(t = "Bad Request") {
134
- super(t);
162
+ __publicField2(CustomError, "code", 500);
163
+ class BadRequestError extends CustomError {
164
+ constructor(message = "Bad Request") {
165
+ super(message);
135
166
  }
136
- static instanceof(t) {
137
- return t.constructor.code == this.code;
167
+ static instanceof(err) {
168
+ return err.constructor.code == this.code;
138
169
  }
139
170
  }
140
- c(Y, "code", 400);
141
- class H extends p {
142
- constructor(t = "Unauthorized") {
143
- super(t);
171
+ __publicField2(BadRequestError, "code", 400);
172
+ class UnauthorizedError extends CustomError {
173
+ constructor(message = "Unauthorized") {
174
+ super(message);
144
175
  }
145
- static instanceof(t) {
146
- return t.constructor.code == this.code;
176
+ static instanceof(err) {
177
+ return err.constructor.code == this.code;
147
178
  }
148
179
  }
149
- c(H, "code", 401);
150
- class W extends p {
151
- constructor(t = "Payment Required") {
152
- super(t);
180
+ __publicField2(UnauthorizedError, "code", 401);
181
+ class PaymentRequiredError extends CustomError {
182
+ constructor(message = "Payment Required") {
183
+ super(message);
153
184
  }
154
- static instanceof(t) {
155
- return t.constructor.code == this.code;
185
+ static instanceof(err) {
186
+ return err.constructor.code == this.code;
156
187
  }
157
188
  }
158
- c(W, "code", 402);
159
- class z extends p {
160
- constructor(t = "Forbidden") {
161
- super(t);
189
+ __publicField2(PaymentRequiredError, "code", 402);
190
+ class ForbiddenError extends CustomError {
191
+ constructor(message = "Forbidden") {
192
+ super(message);
162
193
  }
163
- static instanceof(t) {
164
- return t.constructor.code == this.code;
194
+ static instanceof(err) {
195
+ return err.constructor.code == this.code;
165
196
  }
166
197
  }
167
- c(z, "code", 403);
168
- class K extends p {
169
- constructor(t = "Not Found") {
170
- super(t);
198
+ __publicField2(ForbiddenError, "code", 403);
199
+ class NotFoundError extends CustomError {
200
+ constructor(message = "Not Found") {
201
+ super(message);
171
202
  }
172
- static instanceof(t) {
173
- return t.constructor.code == this.code;
203
+ static instanceof(err) {
204
+ return err.constructor.code == this.code;
174
205
  }
175
206
  }
176
- c(K, "code", 404);
177
- class J extends p {
178
- constructor(t = "Method Not Allowed") {
179
- super(t);
207
+ __publicField2(NotFoundError, "code", 404);
208
+ class MethodNotAllowedError extends CustomError {
209
+ constructor(message = "Method Not Allowed") {
210
+ super(message);
180
211
  }
181
- static instanceof(t) {
182
- return t.constructor.code == this.code;
212
+ static instanceof(err) {
213
+ return err.constructor.code == this.code;
183
214
  }
184
215
  }
185
- c(J, "code", 405);
186
- class Z extends p {
187
- constructor(t = "Not Acceptable") {
188
- super(t);
216
+ __publicField2(MethodNotAllowedError, "code", 405);
217
+ class NotAcceptableError extends CustomError {
218
+ constructor(message = "Not Acceptable") {
219
+ super(message);
189
220
  }
190
- static instanceof(t) {
191
- return t.constructor.code == this.code;
221
+ static instanceof(err) {
222
+ return err.constructor.code == this.code;
192
223
  }
193
224
  }
194
- c(Z, "code", 406);
195
- class V extends p {
196
- constructor(t = "Internal Server Error") {
197
- super(t);
225
+ __publicField2(NotAcceptableError, "code", 406);
226
+ class InternalServerError extends CustomError {
227
+ constructor(message = "Internal Server Error") {
228
+ super(message);
198
229
  }
199
- static instanceof(t) {
200
- return t.constructor.code == this.code;
230
+ static instanceof(err) {
231
+ return err.constructor.code == this.code;
201
232
  }
202
233
  }
203
- c(V, "code", 500);
204
- class X extends p {
205
- constructor(t = "Not Implemented") {
206
- super(t);
234
+ __publicField2(InternalServerError, "code", 500);
235
+ class NotImplementedError extends CustomError {
236
+ constructor(message = "Not Implemented") {
237
+ super(message);
207
238
  }
208
- static instanceof(t) {
209
- return t.constructor.code == this.code;
239
+ static instanceof(err) {
240
+ return err.constructor.code == this.code;
210
241
  }
211
242
  }
212
- c(X, "code", 501);
213
- class Q extends p {
214
- constructor(t = "Bad Gateway") {
215
- super(t);
243
+ __publicField2(NotImplementedError, "code", 501);
244
+ class BadGatewayError extends CustomError {
245
+ constructor(message = "Bad Gateway") {
246
+ super(message);
216
247
  }
217
- static instanceof(t) {
218
- return t.constructor.code == this.code;
248
+ static instanceof(err) {
249
+ return err.constructor.code == this.code;
219
250
  }
220
251
  }
221
- c(Q, "code", 502);
222
- class _ extends p {
223
- constructor(t = "Service Unavailable") {
224
- super(t);
252
+ __publicField2(BadGatewayError, "code", 502);
253
+ class ServiceUnavailableError extends CustomError {
254
+ constructor(message = "Service Unavailable") {
255
+ super(message);
225
256
  }
226
- static instanceof(t) {
227
- return t.constructor.code == this.code;
257
+ static instanceof(err) {
258
+ return err.constructor.code == this.code;
228
259
  }
229
260
  }
230
- c(_, "code", 503);
231
- class tt extends p {
232
- constructor(t = "Gateway Timeout") {
233
- super(t);
261
+ __publicField2(ServiceUnavailableError, "code", 503);
262
+ class GatewayTimeoutError extends CustomError {
263
+ constructor(message = "Gateway Timeout") {
264
+ super(message);
234
265
  }
235
- static instanceof(t) {
236
- return t.constructor.code == this.code;
266
+ static instanceof(err) {
267
+ return err.constructor.code == this.code;
237
268
  }
238
269
  }
239
- c(tt, "code", 504);
240
- function kt(r, t) {
241
- if (r >= 200 && r < 300)
242
- return null;
243
- switch (r) {
270
+ __publicField2(GatewayTimeoutError, "code", 504);
271
+ function errorFromCode(code, message) {
272
+ switch (code) {
244
273
  case 400:
245
- return new Y(t);
274
+ return new BadRequestError(message);
246
275
  case 401:
247
- return new H(t);
276
+ return new UnauthorizedError(message);
248
277
  case 402:
249
- return new W(t);
278
+ return new PaymentRequiredError(message);
250
279
  case 403:
251
- return new z(t);
280
+ return new ForbiddenError(message);
252
281
  case 404:
253
- return new K(t);
282
+ return new NotFoundError(message);
254
283
  case 405:
255
- return new J(t);
284
+ return new MethodNotAllowedError(message);
256
285
  case 406:
257
- return new Z(t);
286
+ return new NotAcceptableError(message);
258
287
  case 500:
259
- return new V(t);
288
+ return new InternalServerError(message);
260
289
  case 501:
261
- return new X(t);
290
+ return new NotImplementedError(message);
262
291
  case 502:
263
- return new Q(t);
292
+ return new BadGatewayError(message);
264
293
  case 503:
265
- return new _(t);
294
+ return new ServiceUnavailableError(message);
266
295
  case 504:
267
- return new tt(t);
296
+ return new GatewayTimeoutError(message);
268
297
  default:
269
- return new p(t, r);
298
+ return new CustomError(message, code);
270
299
  }
271
300
  }
272
- const w = class w2 {
273
- constructor(t = {}) {
274
- c(this, "interceptors", {});
275
- c(this, "headers", {});
276
- c(this, "url");
277
- this.url = t.url ?? null, this.headers = t.headers || {}, t.interceptors && t.interceptors.forEach((e) => w2.addInterceptor(e));
278
- }
279
- static addInterceptor(t) {
280
- const e = Object.keys(w2.interceptors).length.toString();
281
- return w2.interceptors[e] = t, () => {
282
- w2.interceptors[e] = null;
301
+ const _Http = class _Http2 {
302
+ constructor(defaults = {}) {
303
+ __publicField2(this, "interceptors", {});
304
+ __publicField2(this, "headers", {});
305
+ __publicField2(this, "url");
306
+ this.url = defaults.url ?? null;
307
+ this.headers = defaults.headers || {};
308
+ if (defaults.interceptors) {
309
+ defaults.interceptors.forEach((i) => _Http2.addInterceptor(i));
310
+ }
311
+ }
312
+ static addInterceptor(fn) {
313
+ const key = Object.keys(_Http2.interceptors).length.toString();
314
+ _Http2.interceptors[key] = fn;
315
+ return () => {
316
+ _Http2.interceptors[key] = null;
283
317
  };
284
318
  }
285
- addInterceptor(t) {
286
- const e = Object.keys(this.interceptors).length.toString();
287
- return this.interceptors[e] = t, () => {
288
- this.interceptors[e] = null;
319
+ addInterceptor(fn) {
320
+ const key = Object.keys(this.interceptors).length.toString();
321
+ this.interceptors[key] = fn;
322
+ return () => {
323
+ this.interceptors[key] = null;
289
324
  };
290
325
  }
291
- request(t = {}) {
292
- var o;
293
- if (!this.url && !t.url)
294
- throw new Error("URL needs to be set");
295
- let e = ((o = t.url) != null && o.startsWith("http") ? t.url : (this.url || "") + (t.url || "")).replace(/([^:]\/)\/+/g, "$1");
296
- if (t.fragment && (e.includes("#") ? e.replace(/#.*(\?|\n)/g, (s, i) => `#${t.fragment}${i}`) : e += "#" + t.fragment), t.query) {
297
- const s = Array.isArray(t.query) ? t.query : Object.keys(t.query).map((i) => ({ key: i, value: t.query[i] }));
298
- e += (e.includes("?") ? "&" : "?") + s.map((i) => `${i.key}=${i.value}`).join("&");
326
+ request(opts = {}) {
327
+ var _a;
328
+ if (!this.url && !opts.url) throw new Error("URL needs to be set");
329
+ let url = (((_a = opts.url) == null ? void 0 : _a.startsWith("http")) ? opts.url : (this.url || "") + (opts.url || "")).replace(/([^:]\/)\/+/g, "$1");
330
+ if (opts.fragment) url.includes("#") ? url.replace(/#.*(\?|\n)/g, (match, arg1) => `#${opts.fragment}${arg1}`) : url += "#" + opts.fragment;
331
+ if (opts.query) {
332
+ const q = Array.isArray(opts.query) ? opts.query : Object.keys(opts.query).map((k) => ({ key: k, value: opts.query[k] }));
333
+ url += (url.includes("?") ? "&" : "?") + q.map((q2) => `${q2.key}=${q2.value}`).join("&");
299
334
  }
300
- const n = ot({
301
- "Content-Type": t.body ? t.body instanceof FormData ? "multipart/form-data" : "application/json" : void 0,
302
- ...w2.headers,
335
+ const headers = clean({
336
+ "Content-Type": !opts.body ? void 0 : opts.body instanceof FormData ? "multipart/form-data" : "application/json",
337
+ ..._Http2.headers,
303
338
  ...this.headers,
304
- ...t.headers
339
+ ...opts.headers
305
340
  });
306
- return typeof t.body == "object" && t.body != null && n["Content-Type"] == "application/json" && (t.body = JSON.stringify(t.body)), new E((s, i, y) => {
307
- fetch(e, {
308
- headers: n,
309
- method: t.method || (t.body ? "POST" : "GET"),
310
- body: t.body
311
- }).then(async (u) => {
312
- var k, U;
313
- for (let a of [...Object.values(w2.interceptors), ...Object.values(this.interceptors)])
314
- await new Promise((O) => a(u, () => O()));
315
- const R = u.headers.get("Content-Length"), L = R ? parseInt(R, 10) : 0;
316
- let M = 0;
317
- const N = (k = u.body) == null ? void 0 : k.getReader(), et = new ReadableStream({
318
- start(a) {
319
- function O() {
320
- N == null || N.read().then((B) => {
321
- if (B.done)
322
- return a.close();
323
- M += B.value.byteLength, y(M / L), a.enqueue(B.value), O();
324
- }).catch((B) => a.error(B));
341
+ if (typeof opts.body == "object" && opts.body != null && headers["Content-Type"] == "application/json")
342
+ opts.body = JSON.stringify(opts.body);
343
+ return new PromiseProgress((res, rej, prog) => {
344
+ try {
345
+ fetch(url, {
346
+ headers,
347
+ method: opts.method || (opts.body ? "POST" : "GET"),
348
+ body: opts.body
349
+ }).then(async (resp) => {
350
+ var _a2, _b;
351
+ for (let fn of [...Object.values(_Http2.interceptors), ...Object.values(this.interceptors)]) {
352
+ await new Promise((res2) => fn(resp, () => res2()));
353
+ }
354
+ const contentLength = resp.headers.get("Content-Length");
355
+ const total = contentLength ? parseInt(contentLength, 10) : 0;
356
+ let loaded = 0;
357
+ const reader = (_a2 = resp.body) == null ? void 0 : _a2.getReader();
358
+ const stream = new ReadableStream({
359
+ start(controller) {
360
+ function push() {
361
+ reader == null ? void 0 : reader.read().then((event) => {
362
+ if (event.done) return controller.close();
363
+ loaded += event.value.byteLength;
364
+ prog(loaded / total);
365
+ controller.enqueue(event.value);
366
+ push();
367
+ }).catch((error) => controller.error(error));
368
+ }
369
+ push();
325
370
  }
326
- O();
371
+ });
372
+ resp.data = new Response(stream);
373
+ if (opts.decode == null || opts.decode) {
374
+ const content = (_b = resp.headers.get("Content-Type")) == null ? void 0 : _b.toLowerCase();
375
+ if (content == null ? void 0 : content.includes("form")) resp.data = await resp.data.formData();
376
+ else if (content == null ? void 0 : content.includes("json")) resp.data = await resp.data.json();
377
+ else if (content == null ? void 0 : content.includes("text")) resp.data = await resp.data.text();
378
+ else if (content == null ? void 0 : content.includes("application")) resp.data = await resp.data.blob();
327
379
  }
328
- });
329
- if (u.data = new Response(et), t.decode == null || t.decode) {
330
- const a = (U = u.headers.get("Content-Type")) == null ? void 0 : U.toLowerCase();
331
- a != null && a.includes("form") ? u.data = await u.data.formData() : a != null && a.includes("json") ? u.data = await u.data.json() : a != null && a.includes("text") ? u.data = await u.data.text() : a != null && a.includes("application") && (u.data = await u.data.blob());
332
- }
333
- u.ok ? s(u) : i(u);
334
- });
380
+ if (resp.ok) res(resp);
381
+ else rej(resp);
382
+ }).catch((err) => rej(err));
383
+ } catch (err) {
384
+ rej(err);
385
+ }
335
386
  });
336
387
  }
337
388
  };
338
- c(w, "interceptors", {}), c(w, "headers", {});
339
- function Ut(r) {
340
- const t = r.split(".")[1].replace(/-/g, "+").replace(/_/g, "/");
341
- return T(decodeURIComponent(atob(t).split("").map(function(e) {
342
- return "%" + ("00" + e.charCodeAt(0).toString(16)).slice(-2);
389
+ __publicField2(_Http, "interceptors", {});
390
+ __publicField2(_Http, "headers", {});
391
+ function jwtDecode(token) {
392
+ const base64 = token.split(".")[1].replace(/-/g, "+").replace(/_/g, "/");
393
+ return JSONAttemptParse(decodeURIComponent(atob(base64).split("").map(function(c) {
394
+ return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2);
343
395
  }).join("")));
344
396
  }
345
- const S = {
397
+ const CliEffects = {
346
398
  CLEAR: "\x1B[0m",
347
399
  BRIGHT: "\x1B[1m",
348
400
  DIM: "\x1B[2m",
@@ -350,7 +402,8 @@ const S = {
350
402
  BLINK: "\x1B[5m",
351
403
  REVERSE: "\x1B[7m",
352
404
  HIDDEN: "\x1B[8m"
353
- }, C = {
405
+ };
406
+ const CliForeground = {
354
407
  BLACK: "\x1B[30m",
355
408
  RED: "\x1B[31m",
356
409
  GREEN: "\x1B[32m",
@@ -368,65 +421,59 @@ const S = {
368
421
  LIGHT_CYAN: "\x1B[96m",
369
422
  WHITE: "\x1B[97m"
370
423
  };
371
- const g = class g2 extends v {
372
- constructor(t) {
373
- super(), this.namespace = t;
374
- }
375
- pad(t, e, n, o = false) {
376
- const s = t.toString(), i = e - s.length;
377
- if (i <= 0)
378
- return s;
379
- const y = Array(~~(i / n.length)).fill(n).join("");
380
- return o ? s + y : y + s;
381
- }
382
- format(...t) {
383
- const e = /* @__PURE__ */ new Date();
384
- return `${`${e.getFullYear()}-${e.getMonth() + 1}-${e.getDate()} ${this.pad(e.getHours().toString(), 2, "0")}:${this.pad(e.getMinutes().toString(), 2, "0")}:${this.pad(e.getSeconds().toString(), 2, "0")}.${this.pad(e.getMilliseconds().toString(), 3, "0", true)}`}${this.namespace ? ` [${this.namespace}]` : ""} ${t.join(" ")}`;
385
- }
386
- debug(...t) {
387
- if (g2.LOG_LEVEL < 4)
388
- return;
389
- const e = this.format(...t);
390
- g2.emit(4, e), console.debug(C.LIGHT_GREY + e + S.CLEAR);
391
- }
392
- log(...t) {
393
- if (g2.LOG_LEVEL < 3)
394
- return;
395
- const e = this.format(...t);
396
- g2.emit(3, e), console.log(S.CLEAR + e);
397
- }
398
- info(...t) {
399
- if (g2.LOG_LEVEL < 2)
400
- return;
401
- const e = this.format(...t);
402
- g2.emit(2, e), console.info(C.BLUE + e + S.CLEAR);
403
- }
404
- warn(...t) {
405
- if (g2.LOG_LEVEL < 1)
406
- return;
407
- const e = this.format(...t);
408
- g2.emit(1, e), console.warn(C.YELLOW + e + S.CLEAR);
409
- }
410
- error(...t) {
411
- if (g2.LOG_LEVEL < 0)
412
- return;
413
- const e = this.format(...t);
414
- g2.emit(0, e), console.error(C.RED + e + S.CLEAR);
424
+ const _Logger = class _Logger2 extends TypedEmitter {
425
+ constructor(namespace) {
426
+ super();
427
+ this.namespace = namespace;
428
+ }
429
+ format(...text) {
430
+ const now = /* @__PURE__ */ new Date();
431
+ 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")}`;
432
+ return `${timestamp}${this.namespace ? ` [${this.namespace}]` : ""} ${text.map((t) => typeof t == "string" ? t : JSONSanitize(t, 2)).join(" ")}`;
433
+ }
434
+ debug(...args) {
435
+ if (_Logger2.LOG_LEVEL < 4) return;
436
+ const str = this.format(...args);
437
+ _Logger2.emit(4, str);
438
+ console.debug(CliForeground.LIGHT_GREY + str + CliEffects.CLEAR);
439
+ }
440
+ log(...args) {
441
+ if (_Logger2.LOG_LEVEL < 3) return;
442
+ const str = this.format(...args);
443
+ _Logger2.emit(3, str);
444
+ console.log(CliEffects.CLEAR + str);
445
+ }
446
+ info(...args) {
447
+ if (_Logger2.LOG_LEVEL < 2) return;
448
+ const str = this.format(...args);
449
+ _Logger2.emit(2, str);
450
+ console.info(CliForeground.BLUE + str + CliEffects.CLEAR);
451
+ }
452
+ warn(...args) {
453
+ if (_Logger2.LOG_LEVEL < 1) return;
454
+ const str = this.format(...args);
455
+ _Logger2.emit(1, str);
456
+ console.warn(CliForeground.YELLOW + str + CliEffects.CLEAR);
457
+ }
458
+ error(...args) {
459
+ if (_Logger2.LOG_LEVEL < 0) return;
460
+ const str = this.format(...args);
461
+ _Logger2.emit(0, str);
462
+ console.error(CliForeground.RED + str + CliEffects.CLEAR);
415
463
  }
416
464
  };
417
- c(g, "LOG_LEVEL", 4);
418
- function mt(r) {
419
- return new Promise((t) => setTimeout(t, r));
465
+ __publicField2(_Logger, "LOG_LEVEL", 4);
466
+ function sleep(ms) {
467
+ return new Promise((res) => setTimeout(res, ms));
420
468
  }
421
- async function _t(r, t = 100) {
422
- for (; await r(); )
423
- await mt(t);
469
+ async function sleepWhile(fn, checkInterval = 100) {
470
+ while (await fn()) await sleep(checkInterval);
424
471
  }
425
472
  var extendStatics = function(d, b) {
426
473
  extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
427
474
  d2.__proto__ = b2;
428
475
  } || function(d2, b2) {
429
- for (var p2 in b2) if (Object.prototype.hasOwnProperty.call(b2, p2)) d2[p2] = b2[p2];
476
+ for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p];
430
477
  };
431
478
  return extendStatics(d, b);
432
479
  };
@@ -1546,9 +1593,9 @@ class Auth {
1546
1593
  * @returns {Promise<any>} Session information returned from login request
1547
1594
  */
1548
1595
  login(spoke, login, password, twoFactor) {
1549
- return fetch(`${this.api.url + "login"}`, {
1596
+ return fetch(`${this.api.url}login`, {
1550
1597
  method: "POST",
1551
- body: St(ot({
1598
+ body: formData(clean({
1552
1599
  realm: spoke.trim(),
1553
1600
  login: login.trim(),
1554
1601
  password: password.trim(),
@@ -1557,7 +1604,7 @@ class Auth {
1557
1604
  }))
1558
1605
  }).then(async (resp) => {
1559
1606
  const data = await resp.json().catch(() => ({}));
1560
- if (!resp.ok || data["error"]) throw Object.assign(kt(resp.status, data.error) || {}, data);
1607
+ if (!resp.ok || data["error"]) throw Object.assign(errorFromCode(resp.status, data.error) || {}, data);
1561
1608
  this.api.token = data["token"];
1562
1609
  return data;
1563
1610
  });
@@ -1568,9 +1615,9 @@ class Auth {
1568
1615
  * @return {Promise<any>}
1569
1616
  */
1570
1617
  loginGuest() {
1571
- return fetch(`${this.api.url.replace("/api/", "/guest/")}`).then(async (resp) => {
1618
+ return fetch(`${this.api.url}guest`).then(async (resp) => {
1572
1619
  const data = await resp.json().catch(() => ({}));
1573
- if (!resp.ok || data["error"]) throw Object.assign(kt(resp.status, data.error) || {}, data);
1620
+ if (!resp.ok || data["error"]) throw Object.assign(errorFromCode(resp.status, data.error) || {}, data);
1574
1621
  this.api.token = data["token"];
1575
1622
  return data;
1576
1623
  });
@@ -1662,11 +1709,11 @@ class Files {
1662
1709
  data.append("", file, file.name);
1663
1710
  return fetch(this.url, {
1664
1711
  method: "POST",
1665
- headers: ot({ "Authorization": this.api.token ? `Bearer ${this.api.token}` : "" }),
1712
+ headers: clean({ "Authorization": this.api.token ? `Bearer ${this.api.token}` : "" }),
1666
1713
  body: data
1667
1714
  }).then(async (resp) => {
1668
1715
  const data2 = await resp.json().catch(() => ({}));
1669
- if (!resp.ok || data2["error"]) throw Object.assign(kt(resp.status, data2.error) || {}, data2);
1716
+ if (!resp.ok || data2["error"]) throw Object.assign(errorFromCode(resp.status, data2.error) || {}, data2);
1670
1717
  return resp;
1671
1718
  });
1672
1719
  })).then(async (files2) => {
@@ -2061,8 +2108,8 @@ class Slice {
2061
2108
  new Slice(this.slice, this.api).select().exec().rows().then((rows) => this.cache = rows);
2062
2109
  if (!this.unsubscribe) this.unsubscribe = this.api.socket.sliceEvents(this.slice, (event) => {
2063
2110
  const ids = [...event.data.new, ...event.data.changed];
2064
- new Slice(this.slice, this.api).select(ids).exec().rows().then((rows) => this.cache = [...this.cache.filter((c2) => c2.id != null && !ids.includes(c2.id)), ...rows]);
2065
- this.cache = this.cache.filter((v2) => v2.id && !event.data.lost.includes(v2.id));
2111
+ new Slice(this.slice, this.api).select(ids).exec().rows().then((rows) => this.cache = [...this.cache.filter((c) => c.id != null && !ids.includes(c.id)), ...rows]);
2112
+ this.cache = this.cache.filter((v) => v.id && !event.data.lost.includes(v.id));
2066
2113
  });
2067
2114
  return this.cache$;
2068
2115
  } else if (this.unsubscribe) {
@@ -2127,22 +2174,20 @@ class Socket {
2127
2174
  __publicField(this, "listeners", []);
2128
2175
  __publicField(this, "reconnect", false);
2129
2176
  __publicField(this, "socket");
2177
+ __publicField(this, "_connected", false);
2130
2178
  this.api = api;
2131
2179
  this.options = options;
2180
+ const url = new URL(this.api.url.replace("http", "ws"));
2181
+ url.port = "9390";
2132
2182
  this.options = {
2133
- url: this.api.url.replace("http", "ws") + ":3000",
2183
+ url: url.origin,
2134
2184
  ...this.options
2135
2185
  };
2136
2186
  if (this.options.url !== false)
2137
2187
  api.token$.pipe(distinctUntilChanged()).subscribe(() => this.connect());
2138
2188
  }
2139
- /**
2140
- * Is socket connected to Datalynk
2141
- * @return {boolean} true if connected, false if offline
2142
- */
2143
- get open() {
2144
- var _a;
2145
- return ((_a = this.socket) == null ? void 0 : _a.readyState) == 1;
2189
+ get connected() {
2190
+ return this._connected;
2146
2191
  }
2147
2192
  /**
2148
2193
  * Add listener for all socket events
@@ -2158,6 +2203,7 @@ class Socket {
2158
2203
  * Close socket connection
2159
2204
  */
2160
2205
  close() {
2206
+ this._connected = false;
2161
2207
  this.reconnect = false;
2162
2208
  this.socket.close();
2163
2209
  }
@@ -2167,28 +2213,34 @@ class Socket {
2167
2213
  * @param {number} timeout Retry interval, defaults to 30s
2168
2214
  */
2169
2215
  connect(timeout = 3e4) {
2170
- if (this.options.url === false) throw new Error("Socket is disabled");
2171
- if (this.open) {
2216
+ if (!this.options.url) throw new Error("Socket is disabled");
2217
+ if (this.connected) {
2172
2218
  this.reconnect = false;
2173
2219
  this.socket.close();
2174
2220
  }
2175
2221
  this.socket = new WebSocket(this.options.url + (this.api.token ? `?token=${this.api.token}` : ""));
2176
- const t = setTimeout(() => {
2177
- if (this.open) return;
2178
- this.socket.close();
2179
- this.connect();
2222
+ let t = setTimeout(() => {
2223
+ if (this.reconnect && !this.connected) this.connect();
2180
2224
  }, timeout);
2181
- this.socket.onopen = () => {
2182
- clearTimeout(t);
2183
- this.reconnect = true;
2184
- console.debug("Datalynk Socket: Connected");
2185
- };
2186
2225
  this.socket.onmessage = (message) => {
2187
2226
  const payload = JSON.parse(message.data);
2188
- this.listeners.forEach((l) => l(payload));
2227
+ if (payload.connected != void 0) {
2228
+ if (payload.connected) {
2229
+ clearTimeout(t);
2230
+ t = null;
2231
+ this._connected = true;
2232
+ this.reconnect = true;
2233
+ console.debug("Datalynk Socket: Connected");
2234
+ } else {
2235
+ throw new Error(`Socket failed to connect: ${payload.error}`);
2236
+ }
2237
+ } else {
2238
+ this.listeners.forEach((l) => l(payload));
2239
+ }
2189
2240
  };
2190
2241
  this.socket.onclose = () => {
2191
- if (this.reconnect) this.connect();
2242
+ this._connected = false;
2243
+ if (this.reconnect && !t) this.connect();
2192
2244
  console.debug("Datalynk Socket: Disconnected");
2193
2245
  };
2194
2246
  }
@@ -2208,14 +2260,15 @@ class Socket {
2208
2260
  * @return {Unsubscribe} Run returned function to unsubscribe callback
2209
2261
  */
2210
2262
  sliceEvents(slice, callback) {
2211
- _t(() => {
2212
- var _a;
2213
- return ((_a = this.socket) == null ? void 0 : _a.readyState) != 1;
2214
- }).then(() => this.send({ onSliceEvents: slice }));
2263
+ let cancelled = false;
2264
+ sleepWhile(() => !this.connected).then(() => {
2265
+ if (!cancelled) this.send({ onSliceEvents: slice });
2266
+ });
2215
2267
  const unsubscribe = this.addListener((event) => {
2216
2268
  if (event.type == "sliceEvents" && event.data.slice == slice) callback(event);
2217
2269
  });
2218
2270
  return () => {
2271
+ cancelled = true;
2219
2272
  this.send({ offSliceEvents: slice });
2220
2273
  unsubscribe();
2221
2274
  };
@@ -2289,7 +2342,7 @@ class Api {
2289
2342
  /** API Session token */
2290
2343
  __publicField(this, "token$", new BehaviorSubject(null));
2291
2344
  this.options = options;
2292
- this.url = `${url}${url.endsWith("/") ? "" : "/"}api/`;
2345
+ this.url = `${new URL(url).origin}/api/`;
2293
2346
  this.options = {
2294
2347
  bundleTime: 100,
2295
2348
  origin: typeof location !== "undefined" ? location.host : "Unknown",
@@ -2317,21 +2370,20 @@ class Api {
2317
2370
  /** Get session info from JWT payload */
2318
2371
  get jwtPayload() {
2319
2372
  if (!this.token) return null;
2320
- return Ut(this.token);
2373
+ return jwtDecode(this.token);
2321
2374
  }
2322
2375
  _request(req, options = {}) {
2323
2376
  return fetch(this.url, {
2324
2377
  method: "POST",
2325
- headers: ot({
2378
+ headers: clean({
2326
2379
  Authorization: this.token ? `Bearer ${this.token}` : void 0,
2327
2380
  "Content-Type": "application/json"
2328
2381
  }),
2329
2382
  body: JSON.stringify(Api.translateTokens(req))
2330
2383
  }).then(async (resp) => {
2331
- if (!resp.ok) throw kt(resp.status);
2332
- let data = await resp.json();
2384
+ let data = JSONAttemptParse(await resp.text());
2385
+ if (!resp.ok || (data == null ? void 0 : data.error)) throw Object.assign(errorFromCode(resp.status, data.error), data);
2333
2386
  if (!options.raw) data = Api.translateTokens(data);
2334
- if (data["error"]) throw Object.assign(kt(resp.status, data["error"]) || {}, data);
2335
2387
  return data;
2336
2388
  });
2337
2389
  }