@ztimson/momentum 0.47.0 → 0.48.0

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,40 +5,49 @@
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 st = Object.defineProperty;
9
- var it = (r, t, e) => t in r ? st(r, t, { enumerable: true, configurable: true, writable: true, value: e }) : r[t] = e;
10
- var c = (r, t, e) => it(r, typeof t != "symbol" ? t + "" : t, e);
11
- function ot(r, t = false) {
12
- if (r == null) throw new Error("Cannot clean a NULL value");
13
- return Array.isArray(r) ? r = r.filter((e) => e != null) : Object.entries(r).forEach(([e, n]) => {
14
- (t && n === void 0 || !t && n == null) && delete r[e];
15
- }), 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;
16
21
  }
17
- function O(r, t) {
18
- const e = typeof r, n = typeof t;
19
- return e != "object" || r == null || n != "object" || t == null ? e == "function" && n == "function" ? r.toString() == t.toString() : r === t : Object.keys(r).length != Object.keys(t).length ? false : Object.keys(r).every((i) => O(r[i], t[i]));
22
+ function isEqual(a, b) {
23
+ const ta = typeof a, tb = typeof b;
24
+ if (ta != "object" || a == null || (tb != "object" || b == null))
25
+ return ta == "function" && tb == "function" ? a.toString() == b.toString() : a === b;
26
+ const keys = Object.keys(a);
27
+ if (keys.length != Object.keys(b).length) return false;
28
+ return Object.keys(a).every((key) => isEqual(a[key], b[key]));
20
29
  }
21
- function I(r) {
30
+ function JSONAttemptParse(json) {
22
31
  try {
23
- return JSON.parse(r);
32
+ return JSON.parse(json);
24
33
  } catch {
25
- return r;
34
+ return json;
26
35
  }
27
36
  }
28
- function Ot(r, t) {
29
- let e = [];
30
- return JSON.stringify(r, (n, s) => {
31
- if (typeof s == "object" && s !== null) {
32
- if (e.includes(s)) return;
33
- e.push(s);
37
+ function JSONSanitize(obj, space) {
38
+ let cache = [];
39
+ return JSON.stringify(obj, (key, value) => {
40
+ if (typeof value === "object" && value !== null) {
41
+ if (cache.includes(value)) return;
42
+ cache.push(value);
34
43
  }
35
- return s;
36
- }, t);
44
+ return value;
45
+ }, space);
37
46
  }
38
- function m(r) {
39
- return Array.isArray(r) ? r : [r];
47
+ function makeArray(value) {
48
+ return Array.isArray(value) ? value : [value];
40
49
  }
41
- class S extends Array {
50
+ class ASet extends Array {
42
51
  /** Number of elements in set */
43
52
  get size() {
44
53
  return this.length;
@@ -47,118 +56,144 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
47
56
  * Array to create set from, duplicate values will be removed
48
57
  * @param {T[]} elements Elements which will be added to set
49
58
  */
50
- constructor(t = []) {
51
- super(), t != null && t.forEach && t.forEach((e) => this.add(e));
59
+ constructor(elements = []) {
60
+ super();
61
+ if (!!(elements == null ? void 0 : elements["forEach"]))
62
+ elements.forEach((el) => this.add(el));
52
63
  }
53
64
  /**
54
65
  * Add elements to set if unique
55
66
  * @param items
56
67
  */
57
- add(...t) {
58
- t.filter((e) => !this.has(e)).forEach((e) => this.push(e));
68
+ add(...items) {
69
+ items.filter((el) => !this.has(el)).forEach((el) => this.push(el));
70
+ return this;
59
71
  }
60
72
  /**
61
73
  * Delete elements from set
62
74
  * @param items Elements that will be deleted
63
75
  */
64
- delete(...t) {
65
- t.forEach((e) => {
66
- const n = this.indexOf(e);
67
- n != -1 && this.slice(n, 1);
76
+ delete(...items) {
77
+ items.forEach((el) => {
78
+ const index = this.indexOf(el);
79
+ if (index != -1) this.splice(index, 1);
68
80
  });
81
+ return this;
69
82
  }
70
83
  /**
71
84
  * Create list of elements this set has which the comparison set does not
72
85
  * @param {ASet<T>} set Set to compare against
73
86
  * @return {ASet<T>} Different elements
74
87
  */
75
- difference(t) {
76
- return new S(this.filter((e) => !t.has(e)));
88
+ difference(set) {
89
+ return new ASet(this.filter((el) => !set.has(el)));
77
90
  }
78
91
  /**
79
92
  * Check if set includes element
80
93
  * @param {T} el Element to look for
81
94
  * @return {boolean} True if element was found, false otherwise
82
95
  */
83
- has(t) {
84
- return this.indexOf(t) != -1;
96
+ has(el) {
97
+ return this.indexOf(el) != -1;
98
+ }
99
+ /**
100
+ * Find index number of element, or -1 if it doesn't exist. Matches by equality not reference
101
+ *
102
+ * @param {T} search Element to find
103
+ * @param {number} fromIndex Starting index position
104
+ * @return {number} Element index number or -1 if missing
105
+ */
106
+ indexOf(search, fromIndex) {
107
+ return super.findIndex((el) => isEqual(el, search), fromIndex);
85
108
  }
86
109
  /**
87
110
  * Create list of elements this set has in common with the comparison set
88
111
  * @param {ASet<T>} set Set to compare against
89
112
  * @return {boolean} Set of common elements
90
113
  */
91
- intersection(t) {
92
- return new S(this.filter((e) => t.has(e)));
114
+ intersection(set) {
115
+ return new ASet(this.filter((el) => set.has(el)));
93
116
  }
94
117
  /**
95
118
  * Check if this set has no elements in common with the comparison set
96
119
  * @param {ASet<T>} set Set to compare against
97
120
  * @return {boolean} True if nothing in common, false otherwise
98
121
  */
99
- isDisjointFrom(t) {
100
- return this.intersection(t).size == 0;
122
+ isDisjointFrom(set) {
123
+ return this.intersection(set).size == 0;
101
124
  }
102
125
  /**
103
126
  * Check if all elements in this set are included in the comparison set
104
127
  * @param {ASet<T>} set Set to compare against
105
128
  * @return {boolean} True if all elements are included, false otherwise
106
129
  */
107
- isSubsetOf(t) {
108
- return this.findIndex((e) => !t.has(e)) == -1;
130
+ isSubsetOf(set) {
131
+ return this.findIndex((el) => !set.has(el)) == -1;
109
132
  }
110
133
  /**
111
134
  * Check if all elements from comparison set are included in this set
112
135
  * @param {ASet<T>} set Set to compare against
113
136
  * @return {boolean} True if all elements are included, false otherwise
114
137
  */
115
- isSuperset(t) {
116
- return t.findIndex((e) => !this.has(e)) == -1;
138
+ isSuperset(set) {
139
+ return set.findIndex((el) => !this.has(el)) == -1;
117
140
  }
118
141
  /**
119
142
  * Create list of elements that are only in one set but not both (XOR)
120
143
  * @param {ASet<T>} set Set to compare against
121
144
  * @return {ASet<T>} New set of unique elements
122
145
  */
123
- symmetricDifference(t) {
124
- return new S([...this.difference(t), ...t.difference(this)]);
146
+ symmetricDifference(set) {
147
+ return new ASet([...this.difference(set), ...set.difference(this)]);
125
148
  }
126
149
  /**
127
150
  * Create joined list of elements included in this & the comparison set
128
151
  * @param {ASet<T>} set Set join
129
152
  * @return {ASet<T>} New set of both previous sets combined
130
153
  */
131
- union(t) {
132
- return new S([...this, ...t]);
154
+ union(set) {
155
+ return new ASet([...this, ...set]);
133
156
  }
134
157
  }
135
- class Tt {
158
+ class Cache {
136
159
  /**
137
160
  * Create new cache
138
161
  *
139
162
  * @param {keyof T} key Default property to use as primary key
140
163
  * @param options
141
164
  */
142
- constructor(t, e = {}) {
143
- c(this, "store", {});
144
- c(this, "complete", false);
145
- c(this, "values", this.all());
146
- if (this.key = t, this.options = e, e.storageKey && !e.storage && (e.storage = localStorage), e.storageKey && e.storage) {
147
- const n = e.storage.getItem(e.storageKey);
148
- if (n)
165
+ constructor(key, options = {}) {
166
+ __publicField2(this, "store", {});
167
+ __publicField2(this, "complete", false);
168
+ __publicField2(this, "values", this.all());
169
+ this.key = key;
170
+ this.options = options;
171
+ if (options.storageKey && !options.storage && typeof Storage !== "undefined")
172
+ options.storage = localStorage;
173
+ if (options.storageKey && options.storage) {
174
+ const stored = options.storage.getItem(options.storageKey);
175
+ if (stored) {
149
176
  try {
150
- Object.assign(this.store, JSON.parse(n));
177
+ Object.assign(this.store, JSON.parse(stored));
151
178
  } catch {
152
179
  }
180
+ }
153
181
  }
154
182
  return new Proxy(this, {
155
- get: (n, s) => s in n ? n[s] : n.store[s],
156
- set: (n, s, i) => (s in n ? n[s] = i : n.store[s] = i, true)
183
+ get: (target, prop) => {
184
+ if (prop in target) return target[prop];
185
+ return target.store[prop];
186
+ },
187
+ set: (target, prop, value) => {
188
+ if (prop in target) target[prop] = value;
189
+ else target.store[prop] = value;
190
+ return true;
191
+ }
157
192
  });
158
193
  }
159
- getKey(t) {
194
+ getKey(value) {
160
195
  if (!this.key) throw new Error("No key defined");
161
- return t[this.key];
196
+ return value[this.key];
162
197
  }
163
198
  /**
164
199
  * Get all cached items
@@ -175,9 +210,10 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
175
210
  * @param {number | undefined} ttl Override default expiry
176
211
  * @return {this}
177
212
  */
178
- add(t, e = this.ttl) {
179
- const n = this.getKey(t);
180
- return this.set(n, t, e), this;
213
+ add(value, ttl = this.ttl) {
214
+ const key = this.getKey(value);
215
+ this.set(key, value, ttl);
216
+ return this;
181
217
  }
182
218
  /**
183
219
  * Add several rows to the cache
@@ -186,8 +222,10 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
186
222
  * @param complete Mark cache as complete & reliable, defaults to true
187
223
  * @return {this}
188
224
  */
189
- addAll(t, e = true) {
190
- return t.forEach((n) => this.add(n)), this.complete = e, this;
225
+ addAll(rows, complete = true) {
226
+ rows.forEach((r) => this.add(r));
227
+ this.complete = complete;
228
+ return this;
191
229
  }
192
230
  /**
193
231
  * Remove all keys from cache
@@ -200,8 +238,10 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
200
238
  *
201
239
  * @param {K} key Item's primary key
202
240
  */
203
- delete(t) {
204
- delete this.store[t], this.options.storageKey && this.options.storage && this.options.storage.setItem(this.options.storageKey, JSON.stringify(this.store));
241
+ delete(key) {
242
+ delete this.store[key];
243
+ if (this.options.storageKey && this.options.storage)
244
+ this.options.storage.setItem(this.options.storageKey, JSON.stringify(this.store));
205
245
  }
206
246
  /**
207
247
  * Return cache as an array of key-value pairs
@@ -215,8 +255,8 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
215
255
  * @param {K} key Key to lookup
216
256
  * @return {T} Cached item
217
257
  */
218
- get(t) {
219
- return this.store[t];
258
+ get(key) {
259
+ return this.store[key];
220
260
  }
221
261
  /**
222
262
  * Get a list of cached keys
@@ -242,326 +282,389 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
242
282
  * @param {number | undefined} ttl Override default expiry in seconds
243
283
  * @return {this}
244
284
  */
245
- set(t, e, n = this.options.ttl) {
246
- return this.store[t] = e, this.options.storageKey && this.options.storage && this.options.storage.setItem(this.options.storageKey, JSON.stringify(this.store)), n && setTimeout(() => {
247
- this.complete = false, this.delete(t);
248
- }, n * 1e3), this;
285
+ set(key, value, ttl = this.options.ttl) {
286
+ this.store[key] = value;
287
+ if (this.options.storageKey && this.options.storage)
288
+ this.options.storage.setItem(this.options.storageKey, JSON.stringify(this.store));
289
+ if (ttl) setTimeout(() => {
290
+ this.complete = false;
291
+ this.delete(key);
292
+ }, ttl * 1e3);
293
+ return this;
249
294
  }
250
295
  }
251
- class x extends Promise {
252
- constructor(e) {
253
- super((n, s) => e(
254
- (i) => n(i),
255
- (i) => s(i),
256
- (i) => this.progress = i
296
+ class PromiseProgress extends Promise {
297
+ constructor(executor) {
298
+ super((resolve, reject) => executor(
299
+ (value) => resolve(value),
300
+ (reason) => reject(reason),
301
+ (progress) => this.progress = progress
257
302
  ));
258
- c(this, "listeners", []);
259
- c(this, "_progress", 0);
303
+ __publicField2(this, "listeners", []);
304
+ __publicField2(this, "_progress", 0);
260
305
  }
261
306
  get progress() {
262
307
  return this._progress;
263
308
  }
264
- set progress(e) {
265
- e != this._progress && (this._progress = e, this.listeners.forEach((n) => n(e)));
309
+ set progress(p) {
310
+ if (p == this._progress) return;
311
+ this._progress = p;
312
+ this.listeners.forEach((l) => l(p));
266
313
  }
267
- static from(e) {
268
- return e instanceof x ? e : new x((n, s) => e.then((...i) => n(...i)).catch((...i) => s(...i)));
314
+ static from(promise) {
315
+ if (promise instanceof PromiseProgress) return promise;
316
+ return new PromiseProgress((res, rej) => promise.then((...args) => res(...args)).catch((...args) => rej(...args)));
269
317
  }
270
- from(e) {
271
- const n = x.from(e);
272
- return this.onProgress((s) => n.progress = s), n;
318
+ from(promise) {
319
+ const newPromise = PromiseProgress.from(promise);
320
+ this.onProgress((p) => newPromise.progress = p);
321
+ return newPromise;
273
322
  }
274
- onProgress(e) {
275
- return this.listeners.push(e), this;
323
+ onProgress(callback) {
324
+ this.listeners.push(callback);
325
+ return this;
276
326
  }
277
- then(e, n) {
278
- const s = super.then(e, n);
279
- return this.from(s);
327
+ then(res, rej) {
328
+ const resp = super.then(res, rej);
329
+ return this.from(resp);
280
330
  }
281
- catch(e) {
282
- return this.from(super.catch(e));
331
+ catch(rej) {
332
+ return this.from(super.catch(rej));
283
333
  }
284
- finally(e) {
285
- return this.from(super.finally(e));
334
+ finally(res) {
335
+ return this.from(super.finally(res));
286
336
  }
287
337
  }
288
- function Dt(r, t) {
289
- r instanceof Blob || (r = new Blob(m(r)));
290
- const e = URL.createObjectURL(r);
291
- lt(e, t), URL.revokeObjectURL(e);
338
+ function downloadFile(blob, name) {
339
+ if (!(blob instanceof Blob)) blob = new Blob(makeArray(blob));
340
+ const url = URL.createObjectURL(blob);
341
+ downloadUrl(url, name);
342
+ URL.revokeObjectURL(url);
292
343
  }
293
- function lt(r, t) {
294
- const e = document.createElement("a");
295
- e.href = r, e.download = t || r.split("/").pop(), document.body.appendChild(e), e.click(), document.body.removeChild(e);
344
+ function downloadUrl(href, name) {
345
+ const a = document.createElement("a");
346
+ a.href = href;
347
+ a.download = name || href.split("/").pop();
348
+ document.body.appendChild(a);
349
+ a.click();
350
+ document.body.removeChild(a);
296
351
  }
297
- function Mt(r = {}) {
298
- return new Promise((t) => {
299
- const e = document.createElement("input");
300
- e.type = "file", e.accept = r.accept || "*", e.style.display = "none", e.multiple = !!r.multiple, e.onblur = e.onchange = async () => {
301
- t(Array.from(e.files)), e.remove();
302
- }, document.body.appendChild(e), e.click();
352
+ function fileBrowser(options = {}) {
353
+ return new Promise((res) => {
354
+ const input = document.createElement("input");
355
+ input.type = "file";
356
+ input.accept = options.accept || "*";
357
+ input.style.display = "none";
358
+ input.multiple = !!options.multiple;
359
+ input.onblur = input.onchange = async () => {
360
+ res(Array.from(input.files));
361
+ input.remove();
362
+ };
363
+ document.body.appendChild(input);
364
+ input.click();
303
365
  });
304
366
  }
305
- function kt(r, t = /* @__PURE__ */ new Date()) {
306
- (typeof t == "number" || typeof t == "string") && (t = new Date(t));
307
- const e = `${t.getFullYear()}-${(t.getMonth() + 1).toString().padStart(2, "0")}-${t.getDate().toString().padStart(2, "0")}_${t.getHours().toString().padStart(2, "0")}-${t.getMinutes().toString().padStart(2, "0")}-${t.getSeconds().toString().padStart(2, "0")}`;
308
- return e;
367
+ function timestampFilename(name, date = /* @__PURE__ */ new Date()) {
368
+ if (typeof date == "number" || typeof date == "string") date = new Date(date);
369
+ const timestamp = `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, "0")}-${date.getDate().toString().padStart(2, "0")}_${date.getHours().toString().padStart(2, "0")}-${date.getMinutes().toString().padStart(2, "0")}-${date.getSeconds().toString().padStart(2, "0")}`;
370
+ return timestamp;
309
371
  }
310
- function Pt(r) {
311
- return new x((t, e, n) => {
312
- const s = new XMLHttpRequest(), i = new FormData();
313
- r.files.forEach((o) => i.append("file", o)), s.withCredentials = !!r.withCredentials, s.upload.addEventListener("progress", (o) => o.lengthComputable ? n(o.loaded / o.total) : null), s.addEventListener("loadend", () => t(I(s.responseText))), s.addEventListener("error", () => e(I(s.responseText))), s.addEventListener("timeout", () => e({ error: "Request timed out" })), s.open("POST", r.url), Object.entries(r.headers || {}).forEach(([o, a]) => s.setRequestHeader(o, a)), s.send(i);
372
+ function uploadWithProgress(options) {
373
+ return new PromiseProgress((res, rej, prog) => {
374
+ const xhr = new XMLHttpRequest();
375
+ const formData2 = new FormData();
376
+ options.files.forEach((f) => formData2.append("file", f));
377
+ xhr.withCredentials = !!options.withCredentials;
378
+ xhr.upload.addEventListener("progress", (event) => event.lengthComputable ? prog(event.loaded / event.total) : null);
379
+ xhr.addEventListener("loadend", () => res(JSONAttemptParse(xhr.responseText)));
380
+ xhr.addEventListener("error", () => rej(JSONAttemptParse(xhr.responseText)));
381
+ xhr.addEventListener("timeout", () => rej({ error: "Request timed out" }));
382
+ xhr.open("POST", options.url);
383
+ Object.entries(options.headers || {}).forEach(([key, value]) => xhr.setRequestHeader(key, value));
384
+ xhr.send(formData2);
314
385
  });
315
386
  }
316
- class K {
387
+ class TypedEmitter {
317
388
  constructor() {
318
- c(this, "listeners", {});
319
- }
320
- static emit(t, ...e) {
321
- (this.listeners["*"] || []).forEach((n) => n(t, ...e)), (this.listeners[t.toString()] || []).forEach((n) => n(...e));
389
+ __publicField2(this, "listeners", {});
322
390
  }
323
- static off(t, e) {
324
- const n = t.toString();
325
- this.listeners[n] = (this.listeners[n] || []).filter((s) => s === e);
391
+ static emit(event, ...args) {
392
+ (this.listeners["*"] || []).forEach((l) => l(event, ...args));
393
+ (this.listeners[event.toString()] || []).forEach((l) => l(...args));
326
394
  }
327
- static on(t, e) {
328
- var s;
329
- const n = t.toString();
330
- return this.listeners[n] || (this.listeners[n] = []), (s = this.listeners[n]) == null || s.push(e), () => this.off(t, e);
395
+ static off(event, listener) {
396
+ const e = event.toString();
397
+ this.listeners[e] = (this.listeners[e] || []).filter((l) => l === listener);
331
398
  }
332
- static once(t, e) {
333
- return new Promise((n) => {
334
- const s = this.on(t, (...i) => {
335
- n(i.length == 1 ? i[0] : i), e && e(...i), s();
399
+ static on(event, listener) {
400
+ var _a;
401
+ const e = event.toString();
402
+ if (!this.listeners[e]) this.listeners[e] = [];
403
+ (_a = this.listeners[e]) == null ? void 0 : _a.push(listener);
404
+ return () => this.off(event, listener);
405
+ }
406
+ static once(event, listener) {
407
+ return new Promise((res) => {
408
+ const unsubscribe = this.on(event, (...args) => {
409
+ res(args.length == 1 ? args[0] : args);
410
+ if (listener) listener(...args);
411
+ unsubscribe();
336
412
  });
337
413
  });
338
414
  }
339
- emit(t, ...e) {
340
- (this.listeners["*"] || []).forEach((n) => n(t, ...e)), (this.listeners[t] || []).forEach((n) => n(...e));
341
- }
342
- off(t, e) {
343
- this.listeners[t] = (this.listeners[t] || []).filter((n) => n === e);
415
+ emit(event, ...args) {
416
+ (this.listeners["*"] || []).forEach((l) => l(event, ...args));
417
+ (this.listeners[event] || []).forEach((l) => l(...args));
344
418
  }
345
- on(t, e) {
346
- var n;
347
- return this.listeners[t] || (this.listeners[t] = []), (n = this.listeners[t]) == null || n.push(e), () => this.off(t, e);
419
+ off(event, listener) {
420
+ this.listeners[event] = (this.listeners[event] || []).filter((l) => l === listener);
348
421
  }
349
- once(t, e) {
350
- return new Promise((n) => {
351
- const s = this.on(t, (...i) => {
352
- n(i.length == 1 ? i[0] : i), e && e(...i), s();
422
+ on(event, listener) {
423
+ var _a;
424
+ if (!this.listeners[event]) this.listeners[event] = [];
425
+ (_a = this.listeners[event]) == null ? void 0 : _a.push(listener);
426
+ return () => this.off(event, listener);
427
+ }
428
+ once(event, listener) {
429
+ return new Promise((res) => {
430
+ const unsubscribe = this.on(event, (...args) => {
431
+ res(args.length == 1 ? args[0] : args);
432
+ if (listener) listener(...args);
433
+ unsubscribe();
353
434
  });
354
435
  });
355
436
  }
356
437
  }
357
- c(K, "listeners", {});
358
- class g extends Error {
359
- constructor(e, n) {
360
- super(e);
361
- c(this, "_code");
362
- n != null && (this._code = n);
438
+ __publicField2(TypedEmitter, "listeners", {});
439
+ class CustomError extends Error {
440
+ constructor(message, code) {
441
+ super(message);
442
+ __publicField2(this, "_code");
443
+ if (code != null) this._code = code;
363
444
  }
364
445
  get code() {
365
446
  return this._code || this.constructor.code;
366
447
  }
367
- set code(e) {
368
- this._code = e;
448
+ set code(c) {
449
+ this._code = c;
369
450
  }
370
- static from(e) {
371
- const n = Number(e.statusCode) ?? Number(e.code), s = new this(e.message || e.toString());
372
- return Object.assign(s, {
373
- stack: e.stack,
374
- ...e,
375
- code: n ?? void 0
451
+ static from(err) {
452
+ const code = Number(err.statusCode) ?? Number(err.code);
453
+ const newErr = new this(err.message || err.toString());
454
+ return Object.assign(newErr, {
455
+ stack: err.stack,
456
+ ...err,
457
+ code: code ?? void 0
376
458
  });
377
459
  }
378
- static instanceof(e) {
379
- return e.constructor.code != null;
460
+ static instanceof(err) {
461
+ return err.constructor.code != void 0;
380
462
  }
381
463
  toString() {
382
464
  return this.message || super.toString();
383
465
  }
384
466
  }
385
- c(g, "code", 500);
386
- class W extends g {
387
- constructor(t = "Bad Request") {
388
- super(t);
467
+ __publicField2(CustomError, "code", 500);
468
+ class BadRequestError extends CustomError {
469
+ constructor(message = "Bad Request") {
470
+ super(message);
389
471
  }
390
- static instanceof(t) {
391
- return t.constructor.code == this.code;
472
+ static instanceof(err) {
473
+ return err.constructor.code == this.code;
392
474
  }
393
475
  }
394
- c(W, "code", 400);
395
- class v extends g {
396
- constructor(t = "Unauthorized") {
397
- super(t);
476
+ __publicField2(BadRequestError, "code", 400);
477
+ class UnauthorizedError extends CustomError {
478
+ constructor(message = "Unauthorized") {
479
+ super(message);
398
480
  }
399
- static instanceof(t) {
400
- return t.constructor.code == this.code;
481
+ static instanceof(err) {
482
+ return err.constructor.code == this.code;
401
483
  }
402
484
  }
403
- c(v, "code", 401);
404
- class J extends g {
405
- constructor(t = "Payment Required") {
406
- super(t);
485
+ __publicField2(UnauthorizedError, "code", 401);
486
+ class PaymentRequiredError extends CustomError {
487
+ constructor(message = "Payment Required") {
488
+ super(message);
407
489
  }
408
- static instanceof(t) {
409
- return t.constructor.code == this.code;
490
+ static instanceof(err) {
491
+ return err.constructor.code == this.code;
410
492
  }
411
493
  }
412
- c(J, "code", 402);
413
- class z extends g {
414
- constructor(t = "Forbidden") {
415
- super(t);
494
+ __publicField2(PaymentRequiredError, "code", 402);
495
+ class ForbiddenError extends CustomError {
496
+ constructor(message = "Forbidden") {
497
+ super(message);
416
498
  }
417
- static instanceof(t) {
418
- return t.constructor.code == this.code;
499
+ static instanceof(err) {
500
+ return err.constructor.code == this.code;
419
501
  }
420
502
  }
421
- c(z, "code", 403);
422
- class Z extends g {
423
- constructor(t = "Not Found") {
424
- super(t);
503
+ __publicField2(ForbiddenError, "code", 403);
504
+ class NotFoundError extends CustomError {
505
+ constructor(message = "Not Found") {
506
+ super(message);
425
507
  }
426
- static instanceof(t) {
427
- return t.constructor.code == this.code;
508
+ static instanceof(err) {
509
+ return err.constructor.code == this.code;
428
510
  }
429
511
  }
430
- c(Z, "code", 404);
431
- class V extends g {
432
- constructor(t = "Method Not Allowed") {
433
- super(t);
512
+ __publicField2(NotFoundError, "code", 404);
513
+ class MethodNotAllowedError extends CustomError {
514
+ constructor(message = "Method Not Allowed") {
515
+ super(message);
434
516
  }
435
- static instanceof(t) {
436
- return t.constructor.code == this.code;
517
+ static instanceof(err) {
518
+ return err.constructor.code == this.code;
437
519
  }
438
520
  }
439
- c(V, "code", 405);
440
- class X extends g {
441
- constructor(t = "Not Acceptable") {
442
- super(t);
521
+ __publicField2(MethodNotAllowedError, "code", 405);
522
+ class NotAcceptableError extends CustomError {
523
+ constructor(message = "Not Acceptable") {
524
+ super(message);
443
525
  }
444
- static instanceof(t) {
445
- return t.constructor.code == this.code;
526
+ static instanceof(err) {
527
+ return err.constructor.code == this.code;
446
528
  }
447
529
  }
448
- c(X, "code", 406);
449
- class Q extends g {
450
- constructor(t = "Internal Server Error") {
451
- super(t);
530
+ __publicField2(NotAcceptableError, "code", 406);
531
+ class InternalServerError extends CustomError {
532
+ constructor(message = "Internal Server Error") {
533
+ super(message);
452
534
  }
453
- static instanceof(t) {
454
- return t.constructor.code == this.code;
535
+ static instanceof(err) {
536
+ return err.constructor.code == this.code;
455
537
  }
456
538
  }
457
- c(Q, "code", 500);
458
- class _ extends g {
459
- constructor(t = "Not Implemented") {
460
- super(t);
539
+ __publicField2(InternalServerError, "code", 500);
540
+ class NotImplementedError extends CustomError {
541
+ constructor(message = "Not Implemented") {
542
+ super(message);
461
543
  }
462
- static instanceof(t) {
463
- return t.constructor.code == this.code;
544
+ static instanceof(err) {
545
+ return err.constructor.code == this.code;
464
546
  }
465
547
  }
466
- c(_, "code", 501);
467
- class tt extends g {
468
- constructor(t = "Bad Gateway") {
469
- super(t);
548
+ __publicField2(NotImplementedError, "code", 501);
549
+ class BadGatewayError extends CustomError {
550
+ constructor(message = "Bad Gateway") {
551
+ super(message);
470
552
  }
471
- static instanceof(t) {
472
- return t.constructor.code == this.code;
553
+ static instanceof(err) {
554
+ return err.constructor.code == this.code;
473
555
  }
474
556
  }
475
- c(tt, "code", 502);
476
- class et extends g {
477
- constructor(t = "Service Unavailable") {
478
- super(t);
557
+ __publicField2(BadGatewayError, "code", 502);
558
+ class ServiceUnavailableError extends CustomError {
559
+ constructor(message = "Service Unavailable") {
560
+ super(message);
479
561
  }
480
- static instanceof(t) {
481
- return t.constructor.code == this.code;
562
+ static instanceof(err) {
563
+ return err.constructor.code == this.code;
482
564
  }
483
565
  }
484
- c(et, "code", 503);
485
- class rt extends g {
486
- constructor(t = "Gateway Timeout") {
487
- super(t);
566
+ __publicField2(ServiceUnavailableError, "code", 503);
567
+ class GatewayTimeoutError extends CustomError {
568
+ constructor(message = "Gateway Timeout") {
569
+ super(message);
488
570
  }
489
- static instanceof(t) {
490
- return t.constructor.code == this.code;
571
+ static instanceof(err) {
572
+ return err.constructor.code == this.code;
491
573
  }
492
574
  }
493
- c(rt, "code", 504);
494
- const E = class E2 {
495
- constructor(t = {}) {
496
- c(this, "interceptors", {});
497
- c(this, "headers", {});
498
- c(this, "url");
499
- this.url = t.url ?? null, this.headers = t.headers || {}, t.interceptors && t.interceptors.forEach((e) => E2.addInterceptor(e));
500
- }
501
- static addInterceptor(t) {
502
- const e = Object.keys(E2.interceptors).length.toString();
503
- return E2.interceptors[e] = t, () => {
504
- E2.interceptors[e] = null;
575
+ __publicField2(GatewayTimeoutError, "code", 504);
576
+ const _Http = class _Http2 {
577
+ constructor(defaults = {}) {
578
+ __publicField2(this, "interceptors", {});
579
+ __publicField2(this, "headers", {});
580
+ __publicField2(this, "url");
581
+ this.url = defaults.url ?? null;
582
+ this.headers = defaults.headers || {};
583
+ if (defaults.interceptors) {
584
+ defaults.interceptors.forEach((i) => _Http2.addInterceptor(i));
585
+ }
586
+ }
587
+ static addInterceptor(fn) {
588
+ const key = Object.keys(_Http2.interceptors).length.toString();
589
+ _Http2.interceptors[key] = fn;
590
+ return () => {
591
+ _Http2.interceptors[key] = null;
505
592
  };
506
593
  }
507
- addInterceptor(t) {
508
- const e = Object.keys(this.interceptors).length.toString();
509
- return this.interceptors[e] = t, () => {
510
- this.interceptors[e] = null;
594
+ addInterceptor(fn) {
595
+ const key = Object.keys(this.interceptors).length.toString();
596
+ this.interceptors[key] = fn;
597
+ return () => {
598
+ this.interceptors[key] = null;
511
599
  };
512
600
  }
513
- request(t = {}) {
514
- var s;
515
- if (!this.url && !t.url) throw new Error("URL needs to be set");
516
- let e = ((s = t.url) != null && s.startsWith("http") ? t.url : (this.url || "") + (t.url || "")).replace(/([^:]\/)\/+/g, "$1");
517
- if (t.fragment && (e.includes("#") ? e.replace(/#.*(\?|\n)/g, (i, o) => `#${t.fragment}${o}`) : e += "#" + t.fragment), t.query) {
518
- const i = Array.isArray(t.query) ? t.query : Object.keys(t.query).map((o) => ({ key: o, value: t.query[o] }));
519
- e += (e.includes("?") ? "&" : "?") + i.map((o) => `${o.key}=${o.value}`).join("&");
601
+ request(opts = {}) {
602
+ var _a;
603
+ if (!this.url && !opts.url) throw new Error("URL needs to be set");
604
+ let url = (((_a = opts.url) == null ? void 0 : _a.startsWith("http")) ? opts.url : (this.url || "") + (opts.url || "")).replace(/([^:]\/)\/+/g, "$1");
605
+ if (opts.fragment) url.includes("#") ? url.replace(/#.*(\?|\n)/g, (match, arg1) => `#${opts.fragment}${arg1}`) : url += "#" + opts.fragment;
606
+ if (opts.query) {
607
+ const q = Array.isArray(opts.query) ? opts.query : Object.keys(opts.query).map((k) => ({ key: k, value: opts.query[k] }));
608
+ url += (url.includes("?") ? "&" : "?") + q.map((q2) => `${q2.key}=${q2.value}`).join("&");
520
609
  }
521
- const n = ot({
522
- "Content-Type": t.body ? t.body instanceof FormData ? "multipart/form-data" : "application/json" : void 0,
523
- ...E2.headers,
610
+ const headers = clean({
611
+ "Content-Type": !opts.body ? void 0 : opts.body instanceof FormData ? "multipart/form-data" : "application/json",
612
+ ..._Http2.headers,
524
613
  ...this.headers,
525
- ...t.headers
614
+ ...opts.headers
526
615
  });
527
- return typeof t.body == "object" && t.body != null && n["Content-Type"] == "application/json" && (t.body = JSON.stringify(t.body)), new x((i, o, a) => {
616
+ if (typeof opts.body == "object" && opts.body != null && headers["Content-Type"] == "application/json")
617
+ opts.body = JSON.stringify(opts.body);
618
+ return new PromiseProgress((res, rej, prog) => {
528
619
  try {
529
- fetch(e, {
530
- headers: n,
531
- method: t.method || (t.body ? "POST" : "GET"),
532
- body: t.body
533
- }).then(async (u) => {
534
- var G, U;
535
- for (let l of [...Object.values(E2.interceptors), ...Object.values(this.interceptors)])
536
- await new Promise((C) => l(u, () => C()));
537
- const $ = u.headers.get("Content-Length"), j = $ ? parseInt($, 10) : 0;
538
- let P = 0;
539
- const T = (G = u.body) == null ? void 0 : G.getReader(), nt = new ReadableStream({
540
- start(l) {
541
- function C() {
542
- T == null || T.read().then((A) => {
543
- if (A.done) return l.close();
544
- P += A.value.byteLength, a(P / j), l.enqueue(A.value), C();
545
- }).catch((A) => l.error(A));
620
+ fetch(url, {
621
+ headers,
622
+ method: opts.method || (opts.body ? "POST" : "GET"),
623
+ body: opts.body
624
+ }).then(async (resp) => {
625
+ var _a2, _b;
626
+ for (let fn of [...Object.values(_Http2.interceptors), ...Object.values(this.interceptors)]) {
627
+ await new Promise((res2) => fn(resp, () => res2()));
628
+ }
629
+ const contentLength = resp.headers.get("Content-Length");
630
+ const total = contentLength ? parseInt(contentLength, 10) : 0;
631
+ let loaded = 0;
632
+ const reader = (_a2 = resp.body) == null ? void 0 : _a2.getReader();
633
+ const stream = new ReadableStream({
634
+ start(controller) {
635
+ function push() {
636
+ reader == null ? void 0 : reader.read().then((event) => {
637
+ if (event.done) return controller.close();
638
+ loaded += event.value.byteLength;
639
+ prog(loaded / total);
640
+ controller.enqueue(event.value);
641
+ push();
642
+ }).catch((error) => controller.error(error));
546
643
  }
547
- C();
644
+ push();
548
645
  }
549
646
  });
550
- if (u.data = new Response(nt), t.decode == null || t.decode) {
551
- const l = (U = u.headers.get("Content-Type")) == null ? void 0 : U.toLowerCase();
552
- l != null && l.includes("form") ? u.data = await u.data.formData() : l != null && l.includes("json") ? u.data = await u.data.json() : l != null && l.includes("text") ? u.data = await u.data.text() : l != null && l.includes("application") && (u.data = await u.data.blob());
647
+ resp.data = new Response(stream);
648
+ if (opts.decode == null || opts.decode) {
649
+ const content = (_b = resp.headers.get("Content-Type")) == null ? void 0 : _b.toLowerCase();
650
+ if (content == null ? void 0 : content.includes("form")) resp.data = await resp.data.formData();
651
+ else if (content == null ? void 0 : content.includes("json")) resp.data = await resp.data.json();
652
+ else if (content == null ? void 0 : content.includes("text")) resp.data = await resp.data.text();
653
+ else if (content == null ? void 0 : content.includes("application")) resp.data = await resp.data.blob();
553
654
  }
554
- u.ok ? i(u) : o(u);
555
- }).catch((u) => o(u));
556
- } catch (u) {
557
- o(u);
655
+ if (resp.ok) res(resp);
656
+ else rej(resp);
657
+ }).catch((err) => rej(err));
658
+ } catch (err) {
659
+ rej(err);
558
660
  }
559
661
  });
560
662
  }
561
663
  };
562
- c(E, "interceptors", {}), c(E, "headers", {});
563
- let F = E;
564
- const R = {
664
+ __publicField2(_Http, "interceptors", {});
665
+ __publicField2(_Http, "headers", {});
666
+ let Http = _Http;
667
+ const CliEffects = {
565
668
  CLEAR: "\x1B[0m",
566
669
  BRIGHT: "\x1B[1m",
567
670
  DIM: "\x1B[2m",
@@ -569,7 +672,8 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
569
672
  BLINK: "\x1B[5m",
570
673
  REVERSE: "\x1B[7m",
571
674
  HIDDEN: "\x1B[8m"
572
- }, L = {
675
+ };
676
+ const CliForeground = {
573
677
  BLACK: "\x1B[30m",
574
678
  RED: "\x1B[31m",
575
679
  GREEN: "\x1B[32m",
@@ -587,80 +691,138 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
587
691
  LIGHT_CYAN: "\x1B[96m",
588
692
  WHITE: "\x1B[97m"
589
693
  };
590
- var ft = /* @__PURE__ */ ((r) => (r[r.ERROR = 0] = "ERROR", r[r.WARN = 1] = "WARN", r[r.INFO = 2] = "INFO", r[r.LOG = 3] = "LOG", r[r.DEBUG = 4] = "DEBUG", r))(ft || {});
591
- const w = class w2 extends K {
592
- constructor(t) {
593
- super(), this.namespace = t;
594
- }
595
- pad(t, e, n, s = false) {
596
- const i = t.toString(), o = e - i.length;
597
- if (o <= 0) return i;
598
- const a = Array(~~(o / n.length)).fill(n).join("");
599
- return s ? i + a : a + i;
600
- }
601
- format(...t) {
602
- const e = /* @__PURE__ */ new Date();
603
- 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(" ")}`;
604
- }
605
- debug(...t) {
606
- if (w2.LOG_LEVEL < 4) return;
607
- const e = this.format(...t);
608
- w2.emit(4, e), console.debug(L.LIGHT_GREY + e + R.CLEAR);
609
- }
610
- log(...t) {
611
- if (w2.LOG_LEVEL < 3) return;
612
- const e = this.format(...t);
613
- w2.emit(3, e), console.log(R.CLEAR + e);
614
- }
615
- info(...t) {
616
- if (w2.LOG_LEVEL < 2) return;
617
- const e = this.format(...t);
618
- w2.emit(2, e), console.info(L.BLUE + e + R.CLEAR);
619
- }
620
- warn(...t) {
621
- if (w2.LOG_LEVEL < 1) return;
622
- const e = this.format(...t);
623
- w2.emit(1, e), console.warn(L.YELLOW + e + R.CLEAR);
624
- }
625
- error(...t) {
626
- if (w2.LOG_LEVEL < 0) return;
627
- const e = this.format(...t);
628
- w2.emit(0, e), console.error(L.RED + e + R.CLEAR);
694
+ var LOG_LEVEL = /* @__PURE__ */ ((LOG_LEVEL2) => {
695
+ LOG_LEVEL2[LOG_LEVEL2["ERROR"] = 0] = "ERROR";
696
+ LOG_LEVEL2[LOG_LEVEL2["WARN"] = 1] = "WARN";
697
+ LOG_LEVEL2[LOG_LEVEL2["INFO"] = 2] = "INFO";
698
+ LOG_LEVEL2[LOG_LEVEL2["LOG"] = 3] = "LOG";
699
+ LOG_LEVEL2[LOG_LEVEL2["DEBUG"] = 4] = "DEBUG";
700
+ return LOG_LEVEL2;
701
+ })(LOG_LEVEL || {});
702
+ const _Logger = class _Logger2 extends TypedEmitter {
703
+ constructor(namespace) {
704
+ super();
705
+ this.namespace = namespace;
706
+ }
707
+ format(...text) {
708
+ const now = /* @__PURE__ */ new Date();
709
+ 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")}`;
710
+ return `${timestamp}${this.namespace ? ` [${this.namespace}]` : ""} ${text.map((t) => typeof t == "string" ? t : JSONSanitize(t, 2)).join(" ")}`;
711
+ }
712
+ debug(...args) {
713
+ if (_Logger2.LOG_LEVEL < 4) return;
714
+ const str = this.format(...args);
715
+ _Logger2.emit(4, str);
716
+ console.debug(CliForeground.LIGHT_GREY + str + CliEffects.CLEAR);
717
+ }
718
+ log(...args) {
719
+ if (_Logger2.LOG_LEVEL < 3) return;
720
+ const str = this.format(...args);
721
+ _Logger2.emit(3, str);
722
+ console.log(CliEffects.CLEAR + str);
723
+ }
724
+ info(...args) {
725
+ if (_Logger2.LOG_LEVEL < 2) return;
726
+ const str = this.format(...args);
727
+ _Logger2.emit(2, str);
728
+ console.info(CliForeground.BLUE + str + CliEffects.CLEAR);
729
+ }
730
+ warn(...args) {
731
+ if (_Logger2.LOG_LEVEL < 1) return;
732
+ const str = this.format(...args);
733
+ _Logger2.emit(1, str);
734
+ console.warn(CliForeground.YELLOW + str + CliEffects.CLEAR);
735
+ }
736
+ error(...args) {
737
+ if (_Logger2.LOG_LEVEL < 0) return;
738
+ const str = this.format(...args);
739
+ _Logger2.emit(0, str);
740
+ console.error(CliForeground.RED + str + CliEffects.CLEAR);
629
741
  }
630
742
  };
631
- c(w, "LOG_LEVEL", 4);
632
- function ee(r, ...t) {
633
- const e = [];
634
- for (let n = 0; n < r.length || n < t.length; n++)
635
- r[n] && e.push(r[n]), t[n] && e.push(t[n]);
636
- return new y(e.join(""));
743
+ __publicField2(_Logger, "LOG_LEVEL", 4);
744
+ function PE(str, ...args) {
745
+ const combined = [];
746
+ for (let i = 0; i < str.length || i < args.length; i++) {
747
+ if (str[i]) combined.push(str[i]);
748
+ if (args[i]) combined.push(args[i]);
749
+ }
750
+ return new PathEvent(combined.join(""));
751
+ }
752
+ function PES(str, ...args) {
753
+ let combined = [];
754
+ for (let i = 0; i < str.length || i < args.length; i++) {
755
+ if (str[i]) combined.push(str[i]);
756
+ if (args[i]) combined.push(args[i]);
757
+ }
758
+ const [paths, methods] = combined.join("").split(":");
759
+ return PathEvent.toString(paths, methods == null ? void 0 : methods.split(""));
637
760
  }
638
- function mt(r, ...t) {
639
- let e = [];
640
- for (let i = 0; i < r.length || i < t.length; i++)
641
- r[i] && e.push(r[i]), t[i] && e.push(t[i]);
642
- const [n, s] = e.join("").split(":");
643
- return y.toString(n, s == null ? void 0 : s.split(""));
761
+ class PathError extends Error {
644
762
  }
645
- class y {
646
- constructor(t) {
647
- c(this, "module");
648
- c(this, "fullPath");
649
- c(this, "path");
650
- c(this, "name");
651
- c(this, "methods");
652
- c(this, "all");
653
- c(this, "none");
654
- c(this, "create");
655
- c(this, "read");
656
- c(this, "update");
657
- c(this, "delete");
658
- var o;
659
- if (typeof t == "object") return Object.assign(this, t);
660
- let [e, n, s] = t.split(":");
661
- s || (s = n || "*"), (e == "*" || !e && s == "*") && (e = "", s = "*");
662
- let i = e.split("/").filter((a) => !!a);
663
- this.module = ((o = i.splice(0, 1)[0]) == null ? void 0 : o.toLowerCase()) || "", this.fullPath = e, this.path = i.join("/"), this.name = i.pop() || "", this.methods = s.split(""), this.all = s == null ? void 0 : s.includes("*"), this.none = s == null ? void 0 : s.includes("n"), this.create = !(s != null && s.includes("n")) && ((s == null ? void 0 : s.includes("*")) || (s == null ? void 0 : s.includes("w")) || (s == null ? void 0 : s.includes("c"))), this.read = !(s != null && s.includes("n")) && ((s == null ? void 0 : s.includes("*")) || (s == null ? void 0 : s.includes("r"))), this.update = !(s != null && s.includes("n")) && ((s == null ? void 0 : s.includes("*")) || (s == null ? void 0 : s.includes("w")) || (s == null ? void 0 : s.includes("u"))), this.delete = !(s != null && s.includes("n")) && ((s == null ? void 0 : s.includes("*")) || (s == null ? void 0 : s.includes("w")) || (s == null ? void 0 : s.includes("d")));
763
+ class PathEvent {
764
+ constructor(Event) {
765
+ __publicField2(this, "module");
766
+ __publicField2(this, "fullPath");
767
+ __publicField2(this, "path");
768
+ __publicField2(this, "name");
769
+ __publicField2(this, "methods");
770
+ var _a;
771
+ if (typeof Event == "object") return Object.assign(this, Event);
772
+ let [p, scope, method] = Event.split(":");
773
+ if (!method) method = scope || "*";
774
+ if (p == "*" || !p && method == "*") {
775
+ p = "";
776
+ method = "*";
777
+ }
778
+ let temp = p.split("/").filter((p2) => !!p2);
779
+ this.module = ((_a = temp.splice(0, 1)[0]) == null ? void 0 : _a.toLowerCase()) || "";
780
+ this.fullPath = p;
781
+ this.path = temp.join("/");
782
+ this.name = temp.pop() || "";
783
+ this.methods = new ASet(method.split(""));
784
+ }
785
+ /** All/Wildcard specified */
786
+ get all() {
787
+ return this.methods.has("*");
788
+ }
789
+ set all(v) {
790
+ v ? new ASet(["*"]) : this.methods.delete("*");
791
+ }
792
+ /** None specified */
793
+ get none() {
794
+ return this.methods.has("n");
795
+ }
796
+ set none(v) {
797
+ v ? this.methods = new ASet(["n"]) : this.methods.delete("n");
798
+ }
799
+ /** Create method specified */
800
+ get create() {
801
+ return !this.methods.has("n") && (this.methods.has("*") || this.methods.has("c"));
802
+ }
803
+ set create(v) {
804
+ v ? this.methods.delete("n").add("c") : this.methods.delete("c");
805
+ }
806
+ /** Read method specified */
807
+ get read() {
808
+ return !this.methods.has("n") && (this.methods.has("*") || this.methods.has("r"));
809
+ }
810
+ set read(v) {
811
+ v ? this.methods.delete("n").add("r") : this.methods.delete("r");
812
+ }
813
+ /** Update method specified */
814
+ get update() {
815
+ return !this.methods.has("n") && (this.methods.has("*") || this.methods.has("u"));
816
+ }
817
+ set update(v) {
818
+ v ? this.methods.delete("n").add("u") : this.methods.delete("u");
819
+ }
820
+ /** Delete method specified */
821
+ get delete() {
822
+ return !this.methods.has("n") && (this.methods.has("*") || this.methods.has("d"));
823
+ }
824
+ set delete(v) {
825
+ v ? this.methods.delete("n").add("d") : this.methods.delete("d");
664
826
  }
665
827
  /**
666
828
  * Combine multiple events into one parsed object. Longest path takes precedent, but all subsequent methods are
@@ -669,13 +831,35 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
669
831
  * @param {string | PathEvent} paths Events as strings or pre-parsed
670
832
  * @return {PathEvent} Final combined permission
671
833
  */
672
- static combine(t) {
673
- let e = false;
674
- const n = t.map((s) => new y(s)).toSorted((s, i) => {
675
- const o = s.fullPath.length, a = i.fullPath.length;
676
- return o < a ? 1 : o > a ? -1 : 0;
677
- }).reduce((s, i) => (i.none && (e = true), s ? (e || (i.all && (s.all = true), (i.all || i.create) && (s.create = true), (i.all || i.read) && (s.read = true), (i.all || i.update) && (s.update = true), (i.all || i.delete) && (s.delete = true), s.methods = [...s.methods, ...i.methods]), s) : i), null);
678
- return n.all && (n.methods = ["*"]), n.none && (n.methods = ["n"]), n.methods = new S(n.methods), n.raw = mt`${n.fullPath}:${n.methods}`, n;
834
+ static combine(...paths) {
835
+ let hitNone = false;
836
+ const combined = paths.map((p) => new PathEvent(p)).toSorted((p1, p2) => {
837
+ const l1 = p1.fullPath.length, l2 = p2.fullPath.length;
838
+ return l1 < l2 ? 1 : l1 > l2 ? -1 : 0;
839
+ }).reduce((acc, p) => {
840
+ if (p.none) hitNone = true;
841
+ if (!acc) return p;
842
+ if (hitNone) return acc;
843
+ acc.methods = [...acc.methods, ...p.methods];
844
+ return acc;
845
+ }, null);
846
+ combined.methods = new ASet(combined.methods);
847
+ return combined;
848
+ }
849
+ /**
850
+ * Filter a set of paths based on the target
851
+ *
852
+ * @param {string | PathEvent | (string | PathEvent)[]} target Array of events that will filtered
853
+ * @param filter {...PathEvent} Must container one of
854
+ * @return {boolean} Whether there is any overlap
855
+ */
856
+ static filter(target, ...filter) {
857
+ const parsedTarget = makeArray(target).map((pe) => new PathEvent(pe));
858
+ const parsedFind = makeArray(filter).map((pe) => new PathEvent(pe));
859
+ return parsedTarget.filter((t) => {
860
+ if (!t.fullPath && t.all) return true;
861
+ return !!parsedFind.find((f) => t.fullPath.startsWith(f.fullPath) && (f.all || t.all || t.methods.intersection(f.methods).length));
862
+ });
679
863
  }
680
864
  /**
681
865
  * Squash 2 sets of paths & return true if any overlap is found
@@ -684,14 +868,15 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
684
868
  * @param has Target must have at least one of these path
685
869
  * @return {boolean} Whether there is any overlap
686
870
  */
687
- static has(t, ...e) {
688
- const n = m(e).map((i) => new y(i)), s = m(t).map((i) => new y(i));
689
- return !!n.find((i) => {
690
- if (!i.fullPath && i.all) return true;
691
- const o = s.filter((u) => i.fullPath.startsWith(u.fullPath));
692
- if (!o.length) return false;
693
- const a = y.combine(o);
694
- return !a.none && (a.all || new S(a.methods).intersection(new S(i.methods)).length);
871
+ static has(target, ...has) {
872
+ const parsedRequired = makeArray(has).map((pe) => new PathEvent(pe));
873
+ const parsedTarget = makeArray(target).map((pe) => new PathEvent(pe));
874
+ return !!parsedRequired.find((r) => {
875
+ if (!r.fullPath && r.all) return true;
876
+ const filtered = parsedTarget.filter((p) => r.fullPath.startsWith(p.fullPath));
877
+ if (!filtered.length) return false;
878
+ const combined = PathEvent.combine(...filtered);
879
+ return !combined.none && (combined.all || r.all) || combined.methods.intersection(r.methods).length;
695
880
  });
696
881
  }
697
882
  /**
@@ -701,8 +886,8 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
701
886
  * @param has Target must have all these paths
702
887
  * @return {boolean} Whether there is any overlap
703
888
  */
704
- static hasAll(t, ...e) {
705
- return e.filter((n) => y.has(t, n)).length == e.length;
889
+ static hasAll(target, ...has) {
890
+ return has.filter((h) => PathEvent.has(target, h)).length == has.length;
706
891
  }
707
892
  /**
708
893
  * Same as `has` but raises an error if there is no overlap
@@ -710,8 +895,8 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
710
895
  * @param {string | string[]} target Array of Events as strings or pre-parsed
711
896
  * @param has Target must have at least one of these path
712
897
  */
713
- static hasFatal(t, ...e) {
714
- if (!y.has(t, ...e)) throw new Error(`Requires one of: ${m(e).join(", ")}`);
898
+ static hasFatal(target, ...has) {
899
+ if (!PathEvent.has(target, ...has)) throw new PathError(`Requires one of: ${makeArray(has).join(", ")}`);
715
900
  }
716
901
  /**
717
902
  * Same as `hasAll` but raises an error if the target is missing any paths
@@ -719,8 +904,8 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
719
904
  * @param {string | string[]} target Array of Events as strings or pre-parsed
720
905
  * @param has Target must have all these paths
721
906
  */
722
- static hasAllFatal(t, ...e) {
723
- if (!y.hasAll(t, ...e)) throw new Error(`Requires all: ${m(e).join(", ")}`);
907
+ static hasAllFatal(target, ...has) {
908
+ if (!PathEvent.hasAll(target, ...has)) throw new PathError(`Requires all: ${makeArray(has).join(", ")}`);
724
909
  }
725
910
  /**
726
911
  * Create event string from its components
@@ -729,9 +914,20 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
729
914
  * @param {Method} methods Event method
730
915
  * @return {string} String representation of Event
731
916
  */
732
- static toString(t, e) {
733
- let n = m(t).filter((s) => s != null).join("/");
734
- return e != null && e.length && (n += `:${m(e).map((s) => s.toLowerCase()).join("")}`), n == null ? void 0 : n.trim().replaceAll(/\/{2,}/g, "/").replaceAll(/(^\/|\/$)/g, "");
917
+ static toString(path, methods) {
918
+ let p = makeArray(path).filter((p2) => p2 != null).join("/");
919
+ p = p == null ? void 0 : p.trim().replaceAll(/\/{2,}/g, "/").replaceAll(/(^\/|\/$)/g, "");
920
+ if (methods == null ? void 0 : methods.length) p += `:${makeArray(methods).map((m) => m.toLowerCase()).join("")}`;
921
+ return p;
922
+ }
923
+ /**
924
+ * Filter a set of paths based on this event
925
+ *
926
+ * @param {string | PathEvent | (string | PathEvent)[]} target Array of events that will filtered
927
+ * @return {boolean} Whether there is any overlap
928
+ */
929
+ filter(target) {
930
+ return PathEvent.filter(target, this);
735
931
  }
736
932
  /**
737
933
  * Create event string from its components
@@ -739,38 +935,41 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
739
935
  * @return {string} String representation of Event
740
936
  */
741
937
  toString() {
742
- return y.toString(this.fullPath, this.methods);
938
+ return PathEvent.toString(this.fullPath, this.methods);
743
939
  }
744
940
  }
745
- class re {
941
+ class PathEventEmitter {
746
942
  constructor() {
747
- c(this, "listeners", []);
943
+ __publicField2(this, "listeners", []);
748
944
  }
749
- emit(t, ...e) {
750
- const n = new y(t);
751
- this.listeners.filter((s) => y.has(s[0], t)).forEach(async (s) => s[1](n, ...e));
945
+ emit(event, ...args) {
946
+ const parsed = new PathEvent(event);
947
+ this.listeners.filter((l) => PathEvent.has(l[0], event)).forEach(async (l) => l[1](parsed, ...args));
752
948
  }
753
- off(t) {
754
- this.listeners = this.listeners.filter((e) => e[1] != t);
949
+ off(listener) {
950
+ this.listeners = this.listeners.filter((l) => l[1] != listener);
755
951
  }
756
- on(t, e) {
757
- return m(t).forEach((n) => this.listeners.push([new y(n), e])), () => this.off(e);
952
+ on(event, listener) {
953
+ makeArray(event).forEach((e) => this.listeners.push([new PathEvent(e), listener]));
954
+ return () => this.off(listener);
758
955
  }
759
- once(t, e) {
760
- return new Promise((n) => {
761
- const s = this.on(t, (i, ...o) => {
762
- n(o.length < 2 ? o[0] : o), e && e(i, ...o), s();
956
+ once(event, listener) {
957
+ return new Promise((res) => {
958
+ const unsubscribe = this.on(event, (event2, ...args) => {
959
+ res(args.length < 2 ? args[0] : args);
960
+ if (listener) listener(event2, ...args);
961
+ unsubscribe();
763
962
  });
764
963
  });
765
964
  }
766
- relayEvents(t) {
767
- t.on("*", (e, ...n) => this.emit(e, ...n));
965
+ relayEvents(emitter) {
966
+ emitter.on("*", (event, ...args) => this.emit(event, ...args));
768
967
  }
769
968
  }
770
- class Api extends F {
969
+ class Api extends Http {
771
970
  constructor(url = location.origin, opts = {}) {
772
971
  super({ ...(opts == null ? void 0 : opts.http) || {}, url });
773
- __publicField(this, "emitter", new re());
972
+ __publicField(this, "emitter", new PathEventEmitter());
774
973
  __publicField(this, "pending", {});
775
974
  __publicField(this, "storageKey");
776
975
  __publicField(this, "host");
@@ -800,27 +999,27 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
800
999
  if (token) localStorage.setItem(this.storageKey, token);
801
1000
  else localStorage.removeItem(this.storageKey);
802
1001
  }
803
- this.emit(mt`api/token:${token ? "u" : "d"}`, token);
1002
+ this.emit(PES`api/token:${token ? "u" : "d"}`, token);
804
1003
  }
805
1004
  healthcheck() {
806
1005
  return this.request({ url: "/api/healthcheck" }).then((resp) => {
807
- this.emit(mt`api/healthcheck:r`, resp);
1006
+ this.emit(PES`api/healthcheck:r`, resp);
808
1007
  return resp;
809
1008
  });
810
1009
  }
811
1010
  request(options) {
812
- const key = Ot(options);
1011
+ const key = JSONSanitize(options);
813
1012
  const method = options.method == "GET" ? "r" : options.method == "POST" ? "c" : options.method == "DELETE" ? "d" : "u";
814
1013
  if (this.pending[key] != null) return this.pending[key];
815
1014
  this.pending[key] = super.request(options).then((response) => {
816
- this.emit(mt`api/response:${method}`, { request: options, response });
1015
+ this.emit(PES`api/response:${method}`, { request: options, response });
817
1016
  return response.data;
818
1017
  }).catch((err) => {
819
1018
  const e = (err == null ? void 0 : err.data) || err;
820
- this.emit(mt`api/error:${method}`, { request: options, error: e });
1019
+ this.emit(PES`api/error:${method}`, { request: options, error: e });
821
1020
  throw e;
822
1021
  }).finally(() => delete this.pending[key]);
823
- this.emit(mt`api/request:${method}`, { request: options, response: this.pending[key] });
1022
+ this.emit(PES`api/request:${method}`, { request: options, response: this.pending[key] });
824
1023
  return this.pending[key];
825
1024
  }
826
1025
  }
@@ -834,59 +1033,60 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
834
1033
  ActionType2[ActionType2["PUT"] = 6] = "PUT";
835
1034
  return ActionType2;
836
1035
  })(ActionType || {});
837
- class Actions extends re {
1036
+ class Actions extends PathEventEmitter {
838
1037
  constructor(api) {
839
1038
  super();
840
1039
  __publicField(this, "api");
841
- __publicField(this, "cache", new Tt("_id"));
1040
+ __publicField(this, "cache", new Cache("_id"));
842
1041
  this.api = typeof api == "string" ? new Api(api) : api;
843
1042
  }
844
- all() {
845
- return this.api.request({ url: `/api/` + mt`actions` }).then((resp) => {
1043
+ async all(reload) {
1044
+ if (!reload && this.cache.complete) return this.cache.all();
1045
+ return this.api.request({ url: `/api/` + PES`actions` }).then((resp) => {
846
1046
  this.cache.addAll(resp);
847
- this.emit(mt`actions:r`, resp || []);
1047
+ this.emit(PES`actions:r`, resp || []);
848
1048
  return resp;
849
1049
  });
850
1050
  }
851
1051
  delete(id) {
852
1052
  if (!id) throw new Error("Cannot delete action, missing ID");
853
- return this.api.request({ url: `/api/` + mt`actions/${id}`, method: "DELETE" }).then(() => {
1053
+ return this.api.request({ url: `/api/` + PES`actions/${id}`, method: "DELETE" }).then(() => {
854
1054
  this.cache.delete(id);
855
- this.emit(mt`actions/${id}:d`, id);
1055
+ this.emit(PES`actions/${id}:d`, id);
856
1056
  });
857
1057
  }
858
1058
  read(id, reload = false) {
859
1059
  if (!id) throw new Error("Cannot read action, missing ID");
860
1060
  const cached = this.cache.get(id);
861
1061
  if (!reload && cached) return Promise.resolve(cached);
862
- return this.api.request({ url: `/api/` + mt`actions/${id}` }).then((action) => {
1062
+ return this.api.request({ url: `/api/` + PES`actions/${id}` }).then((action) => {
863
1063
  if (action) this.cache.add(action);
864
- this.emit(mt`actions/${id}:r`, action);
1064
+ this.emit(PES`actions/${id}:r`, action);
865
1065
  return action;
866
1066
  });
867
1067
  }
868
1068
  run(path, opts = {}) {
869
1069
  if (!path) throw new Error("Cannot run action, missing path");
870
- return this.api.request({ url: `/api/` + mt`actions/run/${path}`, ...opts });
1070
+ return this.api.request({ url: `/api/` + PES`actions/run/${path}`, ...opts });
871
1071
  }
872
1072
  runById(action, opts = {}) {
873
1073
  const id = typeof action == "string" ? action : action == null ? void 0 : action._id;
874
1074
  if (!id) throw new Error("Cannot run action, missing ID");
875
- return this.api.request({ url: "/api/" + mt`actions/run-by-id/${id}`, method: "POST", ...opts });
1075
+ return this.api.request({ url: "/api/" + PES`actions/run-by-id/${id}`, method: "POST", ...opts });
876
1076
  }
877
1077
  update(action) {
878
1078
  return this.api.request({
879
- url: `/api/` + mt`actions/${action._id}`,
1079
+ url: `/api/` + PES`actions/${action._id}`,
880
1080
  method: "POST",
881
1081
  body: action
882
1082
  }).then((action2) => {
883
1083
  if (action2) this.cache.add(action2);
884
- this.emit(mt`actions/${action2._id}:u`, action2);
1084
+ this.emit(PES`actions/${action2._id}:u`, action2);
885
1085
  return action2;
886
1086
  });
887
1087
  }
888
1088
  }
889
- class Ai extends re {
1089
+ class Ai extends PathEventEmitter {
890
1090
  constructor(api) {
891
1091
  super();
892
1092
  __publicField(this, "api");
@@ -894,19 +1094,19 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
894
1094
  }
895
1095
  ask(question, context) {
896
1096
  if (!question) throw new Error("Cannot ask AI, missing question");
897
- return this.api.request({ url: `/api/` + mt`ai`, method: "POST", body: {
1097
+ return this.api.request({ url: `/api/` + PES`ai`, method: "POST", body: {
898
1098
  question,
899
1099
  context
900
1100
  } }).then((response) => {
901
- this.emit(mt`ai:c`, { question, context, response });
1101
+ this.emit(PES`ai:c`, { question, context, response });
902
1102
  return response;
903
1103
  });
904
1104
  }
905
1105
  clear() {
906
- return this.api.request({ url: "/api/" + mt`ai`, method: "DELETE" }).then(() => this.emit(mt`ai:d`, this.api.token));
1106
+ return this.api.request({ url: "/api/" + PES`ai`, method: "DELETE" }).then(() => this.emit(PES`ai:d`, this.api.token));
907
1107
  }
908
1108
  }
909
- class Analytics extends re {
1109
+ class Analytics extends PathEventEmitter {
910
1110
  constructor(api) {
911
1111
  super();
912
1112
  __publicField(this, "api");
@@ -914,19 +1114,27 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
914
1114
  }
915
1115
  ipTrace(ip) {
916
1116
  if (!ip) throw new Error("Cannot trace, missing IP");
917
- return this.api.request({ url: `/api/` + mt`analytics/trace/${ip}` }).then((resp) => {
918
- this.emit(mt`analytics/trace/${ip}:r`, resp);
1117
+ return this.api.request({ url: `/api/` + PES`analytics/trace/${ip}` }).then((resp) => {
1118
+ this.emit(PES`analytics/trace/${ip}:r`, resp);
919
1119
  return resp;
920
1120
  });
921
1121
  }
922
1122
  }
923
- class Auth extends re {
1123
+ class Auth extends PathEventEmitter {
924
1124
  constructor(api, opts = {}) {
925
1125
  super();
926
1126
  __publicField(this, "api");
1127
+ __publicField(this, "_permissions", []);
927
1128
  __publicField(this, "_user");
1129
+ // Permission helpers
1130
+ __publicField(this, "filter", (...events) => PathEvent.filter(this.permissions, ...events));
1131
+ __publicField(this, "has", (...events) => PathEvent.has(this.permissions, ...events));
1132
+ __publicField(this, "hasAll", (...events) => PathEvent.hasAll(this.permissions, ...events));
1133
+ __publicField(this, "hasFatal", (...events) => PathEvent.hasFatal(this.permissions, ...events));
1134
+ __publicField(this, "hasAllFatal", (...events) => PathEvent.hasAllFatal(this.permissions, ...events));
928
1135
  __publicField(this, "enableTotp", this.resetTotp);
929
1136
  this.opts = opts;
1137
+ window.PathEvent = PathEvent;
930
1138
  this.api = typeof api == "string" ? new Api(api) : api;
931
1139
  this.opts = {
932
1140
  loginUrl: this.api.url + "/ui/#/login",
@@ -939,7 +1147,7 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
939
1147
  "/api/auth/totp"
940
1148
  ];
941
1149
  if (resp.status == 401 && !blacklist.find((url) => resp.url.includes(url)))
942
- this.emit(mt`auth/session-expired:d`, this.api.token);
1150
+ this.emit(PES`auth/session-expired:d`, this.api.token);
943
1151
  next();
944
1152
  });
945
1153
  if (this.api.token) this.session(this.api.token, true);
@@ -950,13 +1158,20 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
950
1158
  else this.user = null;
951
1159
  });
952
1160
  }
1161
+ get permissions() {
1162
+ return this._permissions;
1163
+ }
1164
+ set permissions(perms) {
1165
+ this._permissions = perms;
1166
+ this.emit(PES`auth/permissions:u`, this._permissions);
1167
+ }
953
1168
  get user() {
954
1169
  return this._user;
955
1170
  }
956
1171
  set user(user) {
957
- if (!O(this.user, user)) {
1172
+ if (!isEqual(this.user, user)) {
958
1173
  this._user = user ? user : null;
959
- this.emit(mt`auth/user:u`, this._user);
1174
+ this.emit(PES`auth/user:u`, this._user);
960
1175
  }
961
1176
  }
962
1177
  knownHost(host = location.origin) {
@@ -977,7 +1192,7 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
977
1192
  }).then(async (resp) => {
978
1193
  this.api.token = (resp == null ? void 0 : resp.token) || null;
979
1194
  const user = await this.once("auth/user");
980
- this.emit(mt`auth/login/${username}:u`, user);
1195
+ this.emit(PES`auth/login/${username}:u`, user);
981
1196
  return user;
982
1197
  });
983
1198
  }
@@ -998,7 +1213,7 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
998
1213
  });
999
1214
  }
1000
1215
  logout() {
1001
- this.emit(mt`auth/logout:d`, this.user);
1216
+ this.emit(PES`auth/logout:d`, this.user);
1002
1217
  this.api.token = null;
1003
1218
  this.user = null;
1004
1219
  }
@@ -1007,7 +1222,7 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
1007
1222
  if (!u.username || !u.password) throw new Error("Cannot register user, missing username or password");
1008
1223
  const user = await this.api.request({ url: "/api/auth/register", body: { ...u } });
1009
1224
  if ((_a = user == null ? void 0 : user.image) == null ? void 0 : _a.startsWith("/")) user.image = `${this.api.url}${user.image}?token=${this.api.token}`;
1010
- this.emit(mt`auth/register:c`, user);
1225
+ this.emit(PES`auth/register:c`, user);
1011
1226
  return user;
1012
1227
  }
1013
1228
  reset(emailOrPass, token) {
@@ -1020,7 +1235,7 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
1020
1235
  password: token ? emailOrPass : void 0
1021
1236
  }
1022
1237
  }).then(() => {
1023
- this.emit(mt`auth/reset:${token ? "u" : "c"}`, token || emailOrPass);
1238
+ this.emit(PES`auth/reset:${token ? "u" : "c"}`, token || emailOrPass);
1024
1239
  });
1025
1240
  }
1026
1241
  async session(token, set = false) {
@@ -1029,12 +1244,13 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
1029
1244
  url: "/api/auth/session",
1030
1245
  headers: token ? { "Authorization": `Bearer ${token}` } : void 0
1031
1246
  });
1032
- this.emit(mt`auth/session:r`, session);
1247
+ this.emit(PES`auth/session:r`, session);
1033
1248
  if (set) {
1034
1249
  this.api.token = token;
1035
1250
  if (session == null ? void 0 : session.user) session.user.image = `${this.api.url}${session.user.image}?token=${this.api.token}`;
1036
1251
  this.user = (session == null ? void 0 : session.user) || null;
1037
- if (session) this.emit(mt`auth/login:c`, session.user);
1252
+ this.permissions = (session == null ? void 0 : session.permissions) || [];
1253
+ if (session) this.emit(PES`auth/login:c`, session.user);
1038
1254
  }
1039
1255
  return session;
1040
1256
  }
@@ -1044,7 +1260,7 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
1044
1260
  url: "/api/auth/password",
1045
1261
  body: { username, password, oldPassword }
1046
1262
  }).then((resp) => {
1047
- this.emit(mt`auth/reset:u`, resp == null ? void 0 : resp.token);
1263
+ this.emit(PES`auth/reset:u`, resp == null ? void 0 : resp.token);
1048
1264
  if (resp == null ? void 0 : resp.token) this.api.token = resp.token;
1049
1265
  });
1050
1266
  }
@@ -1056,22 +1272,32 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
1056
1272
  return this.api.request({ url: `/api/auth/totp/${username}`, method: "POST" });
1057
1273
  }
1058
1274
  setupTotp(username, method = "app", totp) {
1059
- return this.api.request({ url: `/api/auth/totp/${username}`, body: ot({
1275
+ return this.api.request({ url: `/api/auth/totp/${username}`, body: clean({
1060
1276
  method,
1061
1277
  totp
1062
1278
  }) });
1063
1279
  }
1064
1280
  }
1065
- class Client extends re {
1066
- constructor(settings) {
1281
+ class Client extends PathEventEmitter {
1282
+ constructor(api, settings) {
1067
1283
  super();
1284
+ __publicField(this, "_notifications", false);
1068
1285
  __publicField(this, "_platform");
1069
1286
  __publicField(this, "_pwa");
1287
+ this.api = api;
1070
1288
  this.settings = settings;
1289
+ this.pushSubscription.then((resp) => this.notifications = !!resp);
1071
1290
  }
1072
1291
  get mobile() {
1073
1292
  return ["android", "ios"].includes(this.platform);
1074
1293
  }
1294
+ get notifications() {
1295
+ return this._notifications;
1296
+ }
1297
+ set notifications(enabled) {
1298
+ this._notifications = enabled;
1299
+ this.emit(PES`client/notifications:${enabled ? "c" : "d"}`, enabled);
1300
+ }
1075
1301
  get platform() {
1076
1302
  if (!this._platform) {
1077
1303
  const userAgent = navigator.userAgent || navigator.vendor;
@@ -1084,6 +1310,10 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
1084
1310
  }
1085
1311
  return this._platform;
1086
1312
  }
1313
+ get pushSubscription() {
1314
+ if (!navigator.serviceWorker.controller) return Promise.resolve(null);
1315
+ return navigator.serviceWorker.ready.then((sw) => sw.pushManager.getSubscription());
1316
+ }
1087
1317
  get pwa() {
1088
1318
  if (this._pwa == null)
1089
1319
  this._pwa = window.matchMedia("(display-mode: standalone)").matches || (navigator == null ? void 0 : navigator.standalone) || document.referrer.includes("android-app://");
@@ -1165,7 +1395,7 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
1165
1395
  if (!dismissed && !this.pwa && this.mobile) this.pwaPrompt();
1166
1396
  }, 500);
1167
1397
  }
1168
- this.emit(mt`client/inject:c`, this.platform);
1398
+ this.emit(PES`client/inject:c`, this.platform);
1169
1399
  }
1170
1400
  pwaPrompt(platform) {
1171
1401
  const url = this.settings.api.url;
@@ -1282,16 +1512,34 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
1282
1512
  setTimeout(() => {
1283
1513
  prompt.remove();
1284
1514
  backdrop.remove();
1285
- this.emit(mt`client/pwa:d`, platform);
1515
+ this.emit(PES`client/pwa:d`, platform);
1286
1516
  }, 500);
1287
1517
  };
1288
1518
  prompt.append(close);
1289
1519
  backdrop.append(prompt);
1290
1520
  document.body.append(backdrop);
1291
- this.emit(mt`client/pwa:c`, platform);
1521
+ this.emit(PES`client/pwa:c`, platform);
1522
+ }
1523
+ async enableNotifications() {
1524
+ const granted = await Notification.requestPermission();
1525
+ if (!granted) return null;
1526
+ const sw = await navigator.serviceWorker.ready;
1527
+ const subscription = (await sw.pushManager.subscribe({
1528
+ userVisibleOnly: true,
1529
+ applicationServerKey: this.settings.cache["push_public_key"]
1530
+ })).toJSON();
1531
+ return this.api.request({ url: "/api/notifications", body: subscription }).then(() => this.notifications = true);
1532
+ }
1533
+ async disableNotifications() {
1534
+ var _a;
1535
+ const subscription = await this.pushSubscription;
1536
+ subscription == null ? void 0 : subscription.unsubscribe();
1537
+ return this.api.request({ url: "/api/notifications", method: "DELETE", body: {
1538
+ p256dh: (_a = subscription == null ? void 0 : subscription.toJSON().keys) == null ? void 0 : _a["p256dh"]
1539
+ } }).then(() => this.notifications = false);
1292
1540
  }
1293
1541
  }
1294
- class Data extends re {
1542
+ class Data extends PathEventEmitter {
1295
1543
  constructor(api) {
1296
1544
  super();
1297
1545
  __publicField(this, "api");
@@ -1300,25 +1548,25 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
1300
1548
  create(collection, document2) {
1301
1549
  if (!collection || !document2) throw new Error("Cannot create document, missing collection or document");
1302
1550
  return this.api.request({
1303
- url: `/api/` + mt`data/${collection}`,
1551
+ url: `/api/` + PES`data/${collection}`,
1304
1552
  method: "POST",
1305
1553
  body: document2
1306
1554
  }).then((resp) => {
1307
- this.emit(mt`data/${collection}:c`, resp);
1555
+ this.emit(PES`data/${collection}:c`, resp);
1308
1556
  return resp;
1309
1557
  });
1310
1558
  }
1311
1559
  delete(collection, id) {
1312
1560
  if (!collection || !id) throw new Error("Cannot delete document, missing collection or ID");
1313
1561
  return this.api.request({
1314
- url: `/api/` + mt`data/${collection}/${id}`,
1562
+ url: `/api/` + PES`data/${collection}/${id}`,
1315
1563
  method: "DELETE"
1316
- }).then(() => this.emit(mt`data/${collection}/${id}:d`, id));
1564
+ }).then(() => this.emit(PES`data/${collection}/${id}:d`, id));
1317
1565
  }
1318
1566
  read(collection, id) {
1319
1567
  if (!collection) throw new Error("Cannot read documents, missing collection");
1320
- return this.api.request({ url: `/api/` + mt`data/${collection}/${id}` }).then((resp) => {
1321
- this.emit(mt`data/${collection}/${id}:r`, collection, resp);
1568
+ return this.api.request({ url: `/api/` + PES`data/${collection}/${id}` }).then((resp) => {
1569
+ this.emit(PES`data/${collection}/${id}:r`, collection, resp);
1322
1570
  return resp;
1323
1571
  });
1324
1572
  }
@@ -1326,42 +1574,42 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
1326
1574
  if (!collection || !document2) throw new Error("Cannot update document, missing collection or document");
1327
1575
  if (!document2._id) return this.create(collection, document2);
1328
1576
  return this.api.request({
1329
- url: `/api/` + mt`data/${collection}/${document2._id}`,
1577
+ url: `/api/` + PES`data/${collection}/${document2._id}`,
1330
1578
  method: append ? "PATCH" : "PUT",
1331
1579
  body: document2
1332
1580
  }).then((resp) => {
1333
- this.emit(mt`data/${collection}/${document2._id}:u`, resp);
1581
+ this.emit(PES`data/${collection}/${document2._id}:u`, resp);
1334
1582
  return resp;
1335
1583
  });
1336
1584
  }
1337
1585
  raw(collection, query) {
1338
1586
  if (!collection || !query) throw new Error("Cannot execute raw query, missing collection or query");
1339
1587
  const mode = query.operand.startsWith("find") ? "r" : query.operand == "insert" ? "c" : query.operand.startsWith("delete") ? "d" : "u";
1340
- return this.api.request({ url: `/api/` + mt`data/${collection}` + "?raw", body: query }).then((resp) => {
1341
- this.emit(mt`data/${collection}:${mode}`, resp);
1588
+ return this.api.request({ url: `/api/` + PES`data/${collection}` + "?raw", body: query }).then((resp) => {
1589
+ this.emit(PES`data/${collection}:${mode}`, resp);
1342
1590
  return resp;
1343
1591
  });
1344
1592
  }
1345
1593
  // Schema ==========================================================================================================
1346
1594
  deleteSchema(path) {
1347
1595
  if (!path) throw new Error("Cannot delete schema, missing collection path");
1348
- return this.api.request({ url: `/api/` + mt`schema/${path}`, method: "DELETE" }).then(() => this.emit(mt`schema/${path}:d`, path));
1596
+ return this.api.request({ url: `/api/` + PES`schema/${path}`, method: "DELETE" }).then(() => this.emit(PES`schema/${path}:d`, path));
1349
1597
  }
1350
1598
  readSchema(pathOrTree) {
1351
- return this.api.request({ url: "/api/" + mt`schema/${typeof pathOrTree == "string" ? pathOrTree : ""}` + (pathOrTree === true ? `?tree=${pathOrTree}` : "") }).then((resp) => {
1352
- this.emit(mt`schema/${typeof pathOrTree == "string" ? pathOrTree : ""}:r`, resp);
1599
+ return this.api.request({ url: "/api/" + PES`schema/${typeof pathOrTree == "string" ? pathOrTree : ""}` + (pathOrTree === true ? `?tree=${pathOrTree}` : "") }).then((resp) => {
1600
+ this.emit(PES`schema/${typeof pathOrTree == "string" ? pathOrTree : ""}:r`, resp);
1353
1601
  return resp;
1354
1602
  });
1355
1603
  }
1356
1604
  updateSchema(schema) {
1357
1605
  if (!schema.path) throw new Error("Cannot update schema, missing collection path");
1358
- return this.api.request({ url: "/api/" + mt`schema/${schema.path}`, body: schema }).then((resp) => {
1359
- this.emit(mt`schema/${schema.path}:${schema._id ? "u" : "c"}`, resp);
1606
+ return this.api.request({ url: "/api/" + PES`schema/${schema.path}`, body: schema }).then((resp) => {
1607
+ this.emit(PES`schema/${schema.path}:${schema._id ? "u" : "c"}`, resp);
1360
1608
  return resp;
1361
1609
  });
1362
1610
  }
1363
1611
  }
1364
- class Email extends re {
1612
+ class Email extends PathEventEmitter {
1365
1613
  constructor(api) {
1366
1614
  super();
1367
1615
  __publicField(this, "api");
@@ -1370,73 +1618,73 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
1370
1618
  send(email) {
1371
1619
  var _a;
1372
1620
  if (!email.to && !email.bcc || !email.body) throw new Error("Cannot send email, missing address or body");
1373
- return this.api.request({ url: "/api/" + mt`email/${(_a = email.body) == null ? void 0 : _a.template}`, body: email }).then((response) => {
1621
+ return this.api.request({ url: "/api/" + PES`email/${(_a = email.body) == null ? void 0 : _a.template}`, body: email }).then((response) => {
1374
1622
  var _a2;
1375
- this.emit(mt`email/${(_a2 = email.body) == null ? void 0 : _a2.template}:c`, { email, response });
1623
+ this.emit(PES`email/${(_a2 = email.body) == null ? void 0 : _a2.template}:c`, { email, response });
1376
1624
  return response;
1377
1625
  });
1378
1626
  }
1379
1627
  }
1380
- class Groups extends re {
1628
+ class Groups extends PathEventEmitter {
1381
1629
  constructor(api) {
1382
1630
  super();
1383
1631
  __publicField(this, "api");
1384
- __publicField(this, "cache", new Tt("name"));
1632
+ __publicField(this, "cache", new Cache("name"));
1385
1633
  this.api = typeof api == "string" ? new Api(api) : api;
1386
1634
  }
1387
1635
  async all(reload) {
1388
1636
  if (!reload && this.cache.complete) return this.cache.all();
1389
- return this.api.request({ url: `/api/` + mt`groups` }).then((resp) => {
1637
+ return this.api.request({ url: `/api/` + PES`groups` }).then((resp) => {
1390
1638
  this.cache.addAll(resp);
1391
- this.emit(mt`groups:r`, resp || []);
1639
+ this.emit(PES`groups:r`, resp || []);
1392
1640
  return resp;
1393
1641
  });
1394
1642
  }
1395
1643
  delete(name) {
1396
1644
  if (!name) throw new Error("Cannot delete group, missing name");
1397
1645
  return this.api.request({
1398
- url: `/api/` + mt`groups/${name}`,
1646
+ url: `/api/` + PES`groups/${name}`,
1399
1647
  method: "DELETE"
1400
1648
  }).then(() => {
1401
1649
  this.cache.delete(name);
1402
- this.emit(mt`groups/${name}:d`);
1650
+ this.emit(PES`groups/${name}:d`);
1403
1651
  });
1404
1652
  }
1405
1653
  create(group) {
1406
1654
  if (!group.name) throw new Error("Cannot create group, missing name");
1407
1655
  return this.api.request({
1408
- url: `/api/` + mt`groups/${group.name}`,
1656
+ url: `/api/` + PES`groups/${group.name}`,
1409
1657
  method: "POST",
1410
1658
  body: group
1411
1659
  }).then((resp) => {
1412
1660
  this.cache.add(resp);
1413
- this.emit(mt`groups/${group.name}:c`, resp);
1661
+ this.emit(PES`groups/${group.name}:c`, resp);
1414
1662
  return resp;
1415
1663
  });
1416
1664
  }
1417
1665
  async read(name, reload) {
1418
1666
  if (!name) throw new Error("Cannot read group, missing name");
1419
1667
  if (!reload && this.cache.get(name)) return this.cache.get(name);
1420
- return this.api.request({ url: `/api/` + mt`groups/${name}` }).then((resp) => {
1668
+ return this.api.request({ url: `/api/` + PES`groups/${name}` }).then((resp) => {
1421
1669
  this.cache.add(resp);
1422
- this.emit(mt`groups/${name}:r`, resp);
1670
+ this.emit(PES`groups/${name}:r`, resp);
1423
1671
  return resp;
1424
1672
  });
1425
1673
  }
1426
1674
  update(group) {
1427
1675
  if (!group.name) throw new Error("Cannot update group, missing name");
1428
1676
  return this.api.request({
1429
- url: `/api/` + mt`groups/${group.name}`,
1677
+ url: `/api/` + PES`groups/${group.name}`,
1430
1678
  method: "PATCH",
1431
1679
  body: group
1432
1680
  }).then((resp) => {
1433
1681
  this.cache.add(resp);
1434
- this.emit(mt`groups/${group.name}:u`, resp);
1682
+ this.emit(PES`groups/${group.name}:u`, resp);
1435
1683
  return resp;
1436
1684
  });
1437
1685
  }
1438
1686
  }
1439
- class Logger extends re {
1687
+ class Logger extends PathEventEmitter {
1440
1688
  constructor(api, channel, logLevel) {
1441
1689
  super();
1442
1690
  __publicField(this, "api");
@@ -1451,7 +1699,7 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
1451
1699
  if (channel.toLowerCase() == "server") throw new Error('"Server" namespace is reserved');
1452
1700
  this.api = typeof api == "string" ? new Api(api) : api;
1453
1701
  if (logLevel != null && logLevel && logLevel != "NONE") {
1454
- if (ft[logLevel] >= 0) {
1702
+ if (LOG_LEVEL[logLevel] >= 0) {
1455
1703
  console.error = (...args) => {
1456
1704
  this.console.error(...args);
1457
1705
  this.error(...args);
@@ -1466,25 +1714,25 @@ ${log}`;
1466
1714
  ((_c = event.reason) == null ? void 0 : _c.code) == null || ((_d = event.reason) == null ? void 0 : _d.code) >= 500 ? this.error(log) : this.warn(log);
1467
1715
  });
1468
1716
  }
1469
- if (ft[logLevel] >= 1) {
1717
+ if (LOG_LEVEL[logLevel] >= 1) {
1470
1718
  console.warn = (...args) => {
1471
1719
  this.console.warn(...args);
1472
1720
  this.warn(...args);
1473
1721
  };
1474
1722
  }
1475
- if (ft[logLevel] >= 2) {
1723
+ if (LOG_LEVEL[logLevel] >= 2) {
1476
1724
  console.info = (...args) => {
1477
1725
  this.console.info(...args);
1478
1726
  this.info(...args);
1479
1727
  };
1480
1728
  }
1481
- if (ft[logLevel] >= 3) {
1729
+ if (LOG_LEVEL[logLevel] >= 3) {
1482
1730
  console.log = (...args) => {
1483
1731
  this.console.log(...args);
1484
1732
  this.log(...args);
1485
1733
  };
1486
1734
  }
1487
- if (ft[logLevel] >= 4) {
1735
+ if (LOG_LEVEL[logLevel] >= 4) {
1488
1736
  console.debug = (...args) => {
1489
1737
  this.console.debug(...args);
1490
1738
  this.debug(...args);
@@ -1507,39 +1755,39 @@ ${log}`;
1507
1755
  }
1508
1756
  create(log, channel = this.channel) {
1509
1757
  if (channel.toLowerCase() == "server") throw new Error('"Server" namespace is reserved');
1510
- return this.api.request({ url: `/api/` + mt`logs/${channel}`, body: log }).then(() => this.emit(mt`logs/${channel}:c`, log)).catch(() => {
1758
+ return this.api.request({ url: `/api/` + PES`logs/${channel}`, body: log }).then(() => this.emit(PES`logs/${channel}:c`, log)).catch(() => {
1511
1759
  });
1512
1760
  }
1513
1761
  channels() {
1514
- return this.api.request({ url: "/api/" + mt`logs/channels` });
1762
+ return this.api.request({ url: "/api/" + PES`logs/channels` });
1515
1763
  }
1516
1764
  delete(channel = this.channel) {
1517
- return this.api.request({ url: `/api/` + mt`logs/${channel}`, method: "DELETE" }).then(() => this.emit(mt`logs/${channel}:d`));
1765
+ return this.api.request({ url: `/api/` + PES`logs/${channel}`, method: "DELETE" }).then(() => this.emit(PES`logs/${channel}:d`));
1518
1766
  }
1519
1767
  read(channel = this.channel) {
1520
- return this.api.request({ url: `/api/` + mt`logs/${channel}` }).then((logs) => {
1521
- this.emit(mt`logs/${channel}:r`, logs);
1768
+ return this.api.request({ url: `/api/` + PES`logs/${channel}` }).then((logs) => {
1769
+ this.emit(PES`logs/${channel}:r`, logs);
1522
1770
  return logs;
1523
1771
  });
1524
1772
  }
1525
1773
  // Console =========================================================================================================
1526
1774
  debug(log, channel = this.channel) {
1527
- return this.create(this.buildLog(ft.DEBUG, log), channel);
1775
+ return this.create(this.buildLog(LOG_LEVEL.DEBUG, log), channel);
1528
1776
  }
1529
1777
  log(log, channel = this.channel) {
1530
- return this.create(this.buildLog(ft.LOG, log), channel);
1778
+ return this.create(this.buildLog(LOG_LEVEL.LOG, log), channel);
1531
1779
  }
1532
1780
  info(log, channel = this.channel) {
1533
- return this.create(this.buildLog(ft.INFO, log), channel);
1781
+ return this.create(this.buildLog(LOG_LEVEL.INFO, log), channel);
1534
1782
  }
1535
1783
  warn(log, channel = this.channel) {
1536
- return this.create(this.buildLog(ft.WARN, log), channel);
1784
+ return this.create(this.buildLog(LOG_LEVEL.WARN, log), channel);
1537
1785
  }
1538
1786
  error(log, channel = this.channel) {
1539
- return this.create(this.buildLog(ft.ERROR, log), channel);
1787
+ return this.create(this.buildLog(LOG_LEVEL.ERROR, log), channel);
1540
1788
  }
1541
1789
  }
1542
- class Payments extends re {
1790
+ class Payments extends PathEventEmitter {
1543
1791
  constructor(api, secret) {
1544
1792
  super();
1545
1793
  __publicField(this, "api");
@@ -1562,7 +1810,7 @@ ${log}`;
1562
1810
  amount,
1563
1811
  custom
1564
1812
  } });
1565
- this.emit(mt`payments:c`, request.data.clientSecret);
1813
+ this.emit(PES`payments:c`, request.data.clientSecret);
1566
1814
  return request.data.clientSecret;
1567
1815
  }
1568
1816
  async createForm(element, amount, custom) {
@@ -1576,28 +1824,28 @@ ${log}`;
1576
1824
  });
1577
1825
  }
1578
1826
  async history(username) {
1579
- const history = await this.api.request({ url: `/api/` + mt`payments/${username}` });
1580
- this.emit(mt`payments/${username}:r`, history);
1827
+ const history = await this.api.request({ url: `/api/` + PES`payments/${username}` });
1828
+ this.emit(PES`payments/${username}:r`, history);
1581
1829
  return history;
1582
1830
  }
1583
1831
  }
1584
- class Pdf extends re {
1832
+ class Pdf extends PathEventEmitter {
1585
1833
  constructor(api) {
1586
1834
  super();
1587
1835
  __publicField(this, "api");
1588
1836
  this.api = typeof api == "string" ? new Api(api) : api;
1589
1837
  }
1590
1838
  createPdf(body, options) {
1591
- return this.api.request({ url: `/api/` + mt`pdf`, body: { ...body, options }, decode: false }).then(async (resp) => {
1839
+ return this.api.request({ url: `/api/` + PES`pdf`, body: { ...body, options }, decode: false }).then(async (resp) => {
1592
1840
  const blob = await resp.blob();
1593
1841
  if (options == null ? void 0 : options.download) {
1594
- let filename = (options == null ? void 0 : options.filename) || kt();
1842
+ let filename = (options == null ? void 0 : options.filename) || timestampFilename();
1595
1843
  if (!filename.endsWith(".pdf")) filename += ".pdf";
1596
1844
  const url = URL.createObjectURL(blob);
1597
- lt(url, filename);
1845
+ downloadUrl(url, filename);
1598
1846
  URL.revokeObjectURL(url);
1599
1847
  }
1600
- this.emit(mt`pdf:c`, blob);
1848
+ this.emit(PES`pdf:c`, blob);
1601
1849
  return blob;
1602
1850
  });
1603
1851
  }
@@ -1664,7 +1912,7 @@ ${log}`;
1664
1912
  };
1665
1913
  __publicField(_Socket, "pollingSpeed", 3e4);
1666
1914
  let Socket = _Socket;
1667
- class Storage extends re {
1915
+ let Storage$1 = class Storage extends PathEventEmitter {
1668
1916
  constructor(api) {
1669
1917
  super();
1670
1918
  __publicField(this, "api");
@@ -1672,119 +1920,119 @@ ${log}`;
1672
1920
  }
1673
1921
  copy(source, destination) {
1674
1922
  if (!source || !destination) throw new Error("Cannot copy file or folder, missing source or destination");
1675
- return this.api.request({ url: "/api/" + mt`storage/${destination}`, body: { from: source } }).then((response) => {
1676
- this.emit(mt`storage/${destination}:c`, response);
1923
+ return this.api.request({ url: "/api/" + PES`storage/${destination}`, body: { from: source } }).then((response) => {
1924
+ this.emit(PES`storage/${destination}:c`, response);
1677
1925
  return response;
1678
1926
  });
1679
1927
  }
1680
1928
  delete(path) {
1681
1929
  if (!path) throw new Error("Cannot delete file or folder, missing path");
1682
- return this.api.request({ url: "/api/" + mt`storage/${path}`, method: "DELETE" }).then(() => {
1683
- this.emit(mt`storage/${path}:d`, path);
1930
+ return this.api.request({ url: "/api/" + PES`storage/${path}`, method: "DELETE" }).then(() => {
1931
+ this.emit(PES`storage/${path}:d`, path);
1684
1932
  });
1685
1933
  }
1686
1934
  download(path, opts = {}) {
1687
1935
  if (!path) throw new Error("Cannot download file, missing path");
1688
- return this.api.request({ ...opts, url: "/api/" + mt`storage/${path}`, decode: false }).then(async (response) => {
1936
+ return this.api.request({ ...opts, url: "/api/" + PES`storage/${path}`, decode: false }).then(async (response) => {
1689
1937
  const blob = await response.blob();
1690
1938
  const name = opts.downloadAs || path.split("/").pop();
1691
- this.emit(mt`storage/${path}:r`, blob);
1692
- Dt(blob, name);
1939
+ this.emit(PES`storage/${path}:r`, blob);
1940
+ downloadFile(blob, name);
1693
1941
  return response;
1694
1942
  });
1695
1943
  }
1696
1944
  list(path) {
1697
1945
  if (!path) path = "/";
1698
- return this.api.request({ url: "/api/" + mt`storage/${path}` + "?list" }).then((resp) => {
1699
- this.emit(mt`storage/${path}:r`, resp);
1946
+ return this.api.request({ url: "/api/" + PES`storage/${path}` + "?list" }).then((resp) => {
1947
+ this.emit(PES`storage/${path}:r`, resp);
1700
1948
  return resp;
1701
1949
  });
1702
1950
  }
1703
1951
  open(path, target = "_blank") {
1704
1952
  if (!path) throw new Error("Cannot download file, missing path");
1705
- const link = `${this.api.url}/api/` + mt`storage/${path}` + (this.api.token ? `?token=${this.api.token}` : "");
1953
+ const link = `${this.api.url}/api/` + PES`storage/${path}` + (this.api.token ? `?token=${this.api.token}` : "");
1706
1954
  if (!target) return link;
1707
- this.emit(mt`storage/${path}:r`, path);
1955
+ this.emit(PES`storage/${path}:r`, path);
1708
1956
  return window.open(link, target);
1709
1957
  }
1710
1958
  mkdir(path) {
1711
1959
  if (!path) throw new Error("Cannot make directory, missing path");
1712
- return this.api.request({ url: "/api/" + mt`storage/${path}`, body: { directory: true } }).then((resp) => {
1713
- this.emit(mt`storage/${path}:c`, resp);
1960
+ return this.api.request({ url: "/api/" + PES`storage/${path}`, body: { directory: true } }).then((resp) => {
1961
+ this.emit(PES`storage/${path}:c`, resp);
1714
1962
  return resp;
1715
1963
  });
1716
1964
  }
1717
1965
  move(source, destination) {
1718
1966
  if (!source || !destination) throw new Error("Cannot move file or folder, missing source or destination");
1719
1967
  if (source == destination) return this.list(destination);
1720
- return this.api.request({ url: "/api/" + mt`storage/${source}`, method: "PATCH", body: { move: destination } }).then((response) => {
1721
- this.emit(mt`storage/${source}:u`, response);
1968
+ return this.api.request({ url: "/api/" + PES`storage/${source}`, method: "PATCH", body: { move: destination } }).then((response) => {
1969
+ this.emit(PES`storage/${source}:u`, response);
1722
1970
  return response;
1723
1971
  });
1724
1972
  }
1725
1973
  upload(files, opts) {
1726
- return new x(async (res, rej, prog) => {
1727
- if (!files) files = await Mt(typeof opts == "object" ? opts : void 0);
1974
+ return new PromiseProgress(async (res, rej, prog) => {
1975
+ if (!files) files = await fileBrowser(typeof opts == "object" ? opts : void 0);
1728
1976
  if (!files || Array.isArray(files) && !files.length) return [];
1729
1977
  const path = (opts && typeof opts == "object" ? opts == null ? void 0 : opts.path : opts) || "/";
1730
- return Pt({
1731
- url: `${this.api.url}/api/` + mt`storage/${path}`,
1732
- files: m(files),
1978
+ return uploadWithProgress({
1979
+ url: `${this.api.url}/api/` + PES`storage/${path}`,
1980
+ files: makeArray(files),
1733
1981
  headers: this.api.headers
1734
1982
  }).onProgress((p) => {
1735
1983
  prog(p);
1736
1984
  }).then((resp) => {
1737
- this.emit(mt`storage/${path}:c`, resp);
1985
+ this.emit(PES`storage/${path}:c`, resp);
1738
1986
  res(resp);
1739
1987
  }).catch((err) => rej(err));
1740
1988
  });
1741
1989
  }
1742
- }
1743
- class Users extends re {
1990
+ };
1991
+ class Users extends PathEventEmitter {
1744
1992
  constructor(api) {
1745
1993
  super();
1746
1994
  __publicField(this, "api");
1747
- __publicField(this, "cache", new Tt("username"));
1995
+ __publicField(this, "cache", new Cache("username"));
1748
1996
  this.api = typeof api == "string" ? new Api(api) : api;
1749
1997
  }
1750
1998
  async all(reload) {
1751
1999
  if (!reload && this.cache.complete) return this.cache.all();
1752
- return this.api.request({ url: "/api/" + mt`users` }).then((resp) => {
2000
+ return this.api.request({ url: "/api/" + PES`users` }).then((resp) => {
1753
2001
  resp == null ? void 0 : resp.forEach((r) => {
1754
2002
  r.image = this.api.url + r.image + `?token=${this.api.token}`;
1755
2003
  return r;
1756
2004
  });
1757
2005
  this.cache.addAll(resp);
1758
- this.emit(mt`users:r`, resp || []);
2006
+ this.emit(PES`users:r`, resp || []);
1759
2007
  return resp;
1760
2008
  });
1761
2009
  }
1762
2010
  delete(username) {
1763
2011
  if (!username) throw new Error("Cannot delete user, missing username");
1764
2012
  return this.api.request({
1765
- url: "/api/" + mt`users/${username}`,
2013
+ url: "/api/" + PES`users/${username}`,
1766
2014
  method: "DELETE"
1767
2015
  }).then(() => {
1768
2016
  this.cache.delete(username);
1769
- this.emit(mt`users/${username}:d`, username);
2017
+ this.emit(PES`users/${username}:d`, username);
1770
2018
  });
1771
2019
  }
1772
2020
  async read(username, reload) {
1773
2021
  if (!username) throw new Error("Cannot read user, missing username");
1774
2022
  if (!reload && this.cache.get(username)) return this.cache.get(username);
1775
- return this.api.request({ url: "/api/" + mt`users/${username}` }).then((resp) => {
2023
+ return this.api.request({ url: "/api/" + PES`users/${username}` }).then((resp) => {
1776
2024
  if (resp) {
1777
2025
  resp.image = this.api.url + resp.image + `?token=${this.api.token}`;
1778
2026
  this.cache.add(resp);
1779
2027
  }
1780
- this.emit(mt`users/${username}:r`, resp);
2028
+ this.emit(PES`users/${username}:r`, resp);
1781
2029
  return resp;
1782
2030
  });
1783
2031
  }
1784
2032
  update(user) {
1785
2033
  if (!user.username) throw new Error("Cannot update user, missing username");
1786
2034
  return this.api.request({
1787
- url: `/api/` + mt`users/${user.username}`,
2035
+ url: `/api/` + PES`users/${user.username}`,
1788
2036
  method: "PATCH",
1789
2037
  body: user
1790
2038
  }).then((resp) => {
@@ -1792,64 +2040,64 @@ ${log}`;
1792
2040
  resp.image = this.api.url + resp.image + `?token=${this.api.token}`;
1793
2041
  this.cache.add(resp);
1794
2042
  }
1795
- this.emit(mt`users/${user.username}:${resp._id ? "u" : "c"}`, resp);
2043
+ this.emit(PES`users/${user.username}:${resp._id ? "u" : "c"}`, resp);
1796
2044
  return resp;
1797
2045
  });
1798
2046
  }
1799
2047
  uploadImage(username, file) {
1800
2048
  if (!username || !file) throw new Error("Cannot update user image, missing username or file");
1801
- return Pt({
1802
- url: this.api.url + `/api/` + mt`users/${username}/image`,
2049
+ return uploadWithProgress({
2050
+ url: this.api.url + `/api/` + PES`users/${username}/image`,
1803
2051
  files: [file],
1804
2052
  headers: this.api.headers
1805
2053
  });
1806
2054
  }
1807
2055
  }
1808
- class Settings extends re {
2056
+ class Settings extends PathEventEmitter {
1809
2057
  constructor(api) {
1810
2058
  super();
1811
2059
  __publicField(this, "api");
1812
2060
  __publicField(this, "cache");
1813
2061
  this.api = typeof api == "string" ? new Api(api) : api;
1814
- this.cache = new Tt("key", { storageKey: `momentum:settings:${this.api.host}` });
2062
+ this.cache = new Cache("key", { storageKey: `momentum:settings:${this.api.host}` });
1815
2063
  this.api.on("api/token", () => this.all(false, true));
1816
2064
  }
1817
2065
  async all(detailed, reload) {
1818
2066
  if (!reload && !detailed && this.cache.complete) return this.cache;
1819
- return this.api.request({ url: `/api/` + mt`settings` + (detailed ? "?detailed" : "") }).then((resp) => {
2067
+ return this.api.request({ url: `/api/` + PES`settings` + (detailed ? "?detailed" : "") }).then((resp) => {
1820
2068
  this.cache.clear();
1821
2069
  if (resp) Object.keys(resp).forEach((key) => this.cache.set(key, detailed ? resp[key].value : resp[key]));
1822
2070
  this.cache.complete = true;
1823
- this.emit(mt`settings:r`, resp || []);
2071
+ this.emit(PES`settings:r`, resp || []);
1824
2072
  return resp;
1825
2073
  });
1826
2074
  }
1827
2075
  delete(key) {
1828
2076
  if (!key) throw new Error("Cannot delete setting, missing key");
1829
- return this.api.request({ url: `/api/` + mt`settings/${key}`, method: "DELETE" }).then(() => {
2077
+ return this.api.request({ url: `/api/` + PES`settings/${key}`, method: "DELETE" }).then(() => {
1830
2078
  this.cache.delete(key);
1831
- this.emit(mt`settings/${key}:d`, key);
2079
+ this.emit(PES`settings/${key}:d`, key);
1832
2080
  });
1833
2081
  }
1834
2082
  read(key, reload = false) {
1835
2083
  if (!key) throw new Error("Cannot read setting, missing key");
1836
2084
  if (!reload && this.cache.get(key)) return this.cache.get(key);
1837
- return this.api.request({ url: `/api/` + mt`settings/${key}` }).then((variable) => {
2085
+ return this.api.request({ url: `/api/` + PES`settings/${key}` }).then((variable) => {
1838
2086
  if (variable) this.cache.set(variable.key, variable.value);
1839
- this.emit(mt`settings/${key}:r`, variable);
2087
+ this.emit(PES`settings/${key}:r`, variable);
1840
2088
  return variable;
1841
2089
  });
1842
2090
  }
1843
2091
  update(variable) {
1844
2092
  if (!variable.key) throw new Error("Cannot update setting, missing key");
1845
- return this.api.request({ url: `/api/` + mt`settings/${variable.key}`, body: variable }).then((variable2) => {
2093
+ return this.api.request({ url: `/api/` + PES`settings/${variable.key}`, body: variable }).then((variable2) => {
1846
2094
  if (variable2) this.cache.set(variable2.key, variable2.value);
1847
- this.emit(`/api/` + mt`settings/${variable2.key}:${variable2._id ? "u" : "c"}`, variable2);
2095
+ this.emit(`/api/` + PES`settings/${variable2.key}:${variable2._id ? "u" : "c"}`, variable2);
1848
2096
  return variable2;
1849
2097
  });
1850
2098
  }
1851
2099
  }
1852
- class Static extends re {
2100
+ class Static extends PathEventEmitter {
1853
2101
  constructor(api) {
1854
2102
  super();
1855
2103
  __publicField(this, "api");
@@ -1857,27 +2105,27 @@ ${log}`;
1857
2105
  }
1858
2106
  delete(path) {
1859
2107
  if (!path) throw new Error("Cannot delete static asset, missing path");
1860
- return this.api.request({ url: `/api/` + mt`static/${path}`, method: "DELETE" }).then(() => {
1861
- this.emit(mt`static/${path}:d`, path);
2108
+ return this.api.request({ url: `/api/` + PES`static/${path}`, method: "DELETE" }).then(() => {
2109
+ this.emit(PES`static/${path}:d`, path);
1862
2110
  });
1863
2111
  }
1864
2112
  upload(files, path = "/") {
1865
2113
  if (!files) throw new Error("Cannot upload static assets, missing file");
1866
- return new x(async (res, rej, prog) => {
1867
- return Pt({
1868
- url: this.api.url + "/api/" + mt`static/${path}`,
1869
- files: m(files),
2114
+ return new PromiseProgress(async (res, rej, prog) => {
2115
+ return uploadWithProgress({
2116
+ url: this.api.url + "/api/" + PES`static/${path}`,
2117
+ files: makeArray(files),
1870
2118
  headers: this.api.headers
1871
2119
  }).onProgress((p) => {
1872
2120
  prog(p);
1873
2121
  }).then((resp) => {
1874
- this.emit(mt`static/${path}:c`, resp);
2122
+ this.emit(PES`static/${path}:c`, resp);
1875
2123
  res(resp);
1876
2124
  }).catch((err) => rej(err));
1877
2125
  });
1878
2126
  }
1879
2127
  }
1880
- class Momentum extends re {
2128
+ class Momentum extends PathEventEmitter {
1881
2129
  constructor(url, opts) {
1882
2130
  super();
1883
2131
  __publicField(this, "api");
@@ -1911,8 +2159,8 @@ ${log}`;
1911
2159
  this.settings = new Settings(this.api);
1912
2160
  if (opts == null ? void 0 : opts.socket) this.socket = new Socket(this.api);
1913
2161
  this.static = new Static(this.api);
1914
- this.storage = new Storage(this.api);
1915
- this.client = new Client(this.settings);
2162
+ this.storage = new Storage$1(this.api);
2163
+ this.client = new Client(this.api, this.settings);
1916
2164
  this.users = new Users(this.api);
1917
2165
  this.relayEvents(this.actions);
1918
2166
  this.relayEvents(this.ai);
@@ -1935,6 +2183,9 @@ ${log}`;
1935
2183
  const cached = this.users.cache.get(this.auth.user.username);
1936
2184
  if (cached) this.auth.user = cached;
1937
2185
  });
2186
+ if (!(opts == null ? void 0 : opts.disableWorker) && "serviceWorker" in navigator) {
2187
+ navigator.serviceWorker.register("/momentum-worker.js");
2188
+ }
1938
2189
  }
1939
2190
  }
1940
2191
  exports2.ActionType = ActionType;
@@ -1949,16 +2200,16 @@ ${log}`;
1949
2200
  exports2.Groups = Groups;
1950
2201
  exports2.Logger = Logger;
1951
2202
  exports2.Momentum = Momentum;
1952
- exports2.PE = ee;
1953
- exports2.PES = mt;
1954
- exports2.PathEvent = y;
1955
- exports2.PathEventEmitter = re;
2203
+ exports2.PE = PE;
2204
+ exports2.PES = PES;
2205
+ exports2.PathEvent = PathEvent;
2206
+ exports2.PathEventEmitter = PathEventEmitter;
1956
2207
  exports2.Payments = Payments;
1957
2208
  exports2.Pdf = Pdf;
1958
2209
  exports2.Settings = Settings;
1959
2210
  exports2.Socket = Socket;
1960
2211
  exports2.Static = Static;
1961
- exports2.Storage = Storage;
2212
+ exports2.Storage = Storage$1;
1962
2213
  exports2.Users = Users;
1963
2214
  Object.defineProperty(exports2, Symbol.toStringTag, { value: "Module" });
1964
2215
  });