@ztimson/momentum 0.46.0 → 0.48.0

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