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