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