@ztimson/momentum 0.42.3 → 0.44.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -38,6 +38,100 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
38
38
  function ft(r) {
39
39
  return Array.isArray(r) ? r : [r];
40
40
  }
41
+ class B extends Array {
42
+ /** Number of elements in set */
43
+ get size() {
44
+ return this.length;
45
+ }
46
+ /**
47
+ * Array to create set from, duplicate values will be removed
48
+ * @param {T[]} elements Elements which will be added to set
49
+ */
50
+ constructor(t = []) {
51
+ super(), t != null && t.forEach && t.forEach((e) => this.add(e));
52
+ }
53
+ /**
54
+ * Add elements to set if unique
55
+ * @param items
56
+ */
57
+ add(...t) {
58
+ t.filter((e) => !this.has(e)).forEach((e) => this.push(e));
59
+ }
60
+ /**
61
+ * Delete elements from set
62
+ * @param items Elements that will be deleted
63
+ */
64
+ delete(...t) {
65
+ t.forEach((e) => {
66
+ const n = this.indexOf(e);
67
+ n != -1 && this.slice(n, 1);
68
+ });
69
+ }
70
+ /**
71
+ * Create list of elements this set has which the comparison set does not
72
+ * @param {ASet<T>} set Set to compare against
73
+ * @return {ASet<T>} Different elements
74
+ */
75
+ difference(t) {
76
+ return new B(this.filter((e) => !t.has(e)));
77
+ }
78
+ /**
79
+ * Check if set includes element
80
+ * @param {T} el Element to look for
81
+ * @return {boolean} True if element was found, false otherwise
82
+ */
83
+ has(t) {
84
+ return this.indexOf(t) != -1;
85
+ }
86
+ /**
87
+ * Create list of elements this set has in common with the comparison set
88
+ * @param {ASet<T>} set Set to compare against
89
+ * @return {boolean} Set of common elements
90
+ */
91
+ intersection(t) {
92
+ return new B(this.filter((e) => t.has(e)));
93
+ }
94
+ /**
95
+ * Check if this set has no elements in common with the comparison set
96
+ * @param {ASet<T>} set Set to compare against
97
+ * @return {boolean} True if nothing in common, false otherwise
98
+ */
99
+ isDisjointFrom(t) {
100
+ return this.intersection(t).size == 0;
101
+ }
102
+ /**
103
+ * Check if all elements in this set are included in the comparison set
104
+ * @param {ASet<T>} set Set to compare against
105
+ * @return {boolean} True if all elements are included, false otherwise
106
+ */
107
+ isSubsetOf(t) {
108
+ return this.findIndex((e) => !t.has(e)) == -1;
109
+ }
110
+ /**
111
+ * Check if all elements from comparison set are included in this set
112
+ * @param {ASet<T>} set Set to compare against
113
+ * @return {boolean} True if all elements are included, false otherwise
114
+ */
115
+ isSuperset(t) {
116
+ return t.findIndex((e) => !this.has(e)) == -1;
117
+ }
118
+ /**
119
+ * Create list of elements that are only in one set but not both (XOR)
120
+ * @param {ASet<T>} set Set to compare against
121
+ * @return {ASet<T>} New set of unique elements
122
+ */
123
+ symmetricDifference(t) {
124
+ return new B([...this.difference(t), ...t.difference(this)]);
125
+ }
126
+ /**
127
+ * Create joined list of elements included in this & the comparison set
128
+ * @param {ASet<T>} set Set join
129
+ * @return {ASet<T>} New set of both previous sets combined
130
+ */
131
+ union(t) {
132
+ return new B([...this, ...t]);
133
+ }
134
+ }
41
135
  class Dt {
42
136
  /**
43
137
  * Create new cache
@@ -194,6 +288,11 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
194
288
  }, document.body.appendChild(e), e.click();
195
289
  });
196
290
  }
291
+ function qt(r, t = /* @__PURE__ */ new Date()) {
292
+ (typeof t == "number" || typeof t == "string") && (t = new Date(t));
293
+ 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")}`;
294
+ return e;
295
+ }
197
296
  function Ft(r) {
198
297
  return new E((t, e, n) => {
199
298
  const s = new XMLHttpRequest(), o = new FormData();
@@ -452,7 +551,7 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
452
551
  BLINK: "\x1B[5m",
453
552
  REVERSE: "\x1B[7m",
454
553
  HIDDEN: "\x1B[8m"
455
- }, j = {
554
+ }, $ = {
456
555
  BLACK: "\x1B[30m",
457
556
  RED: "\x1B[31m",
458
557
  GREEN: "\x1B[32m",
@@ -488,7 +587,7 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
488
587
  debug(...t) {
489
588
  if (g2.LOG_LEVEL < 4) return;
490
589
  const e = this.format(...t);
491
- g2.emit(4, e), console.debug(j.LIGHT_GREY + e + x.CLEAR);
590
+ g2.emit(4, e), console.debug($.LIGHT_GREY + e + x.CLEAR);
492
591
  }
493
592
  log(...t) {
494
593
  if (g2.LOG_LEVEL < 3) return;
@@ -498,21 +597,21 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
498
597
  info(...t) {
499
598
  if (g2.LOG_LEVEL < 2) return;
500
599
  const e = this.format(...t);
501
- g2.emit(2, e), console.info(j.BLUE + e + x.CLEAR);
600
+ g2.emit(2, e), console.info($.BLUE + e + x.CLEAR);
502
601
  }
503
602
  warn(...t) {
504
603
  if (g2.LOG_LEVEL < 1) return;
505
604
  const e = this.format(...t);
506
- g2.emit(1, e), console.warn(j.YELLOW + e + x.CLEAR);
605
+ g2.emit(1, e), console.warn($.YELLOW + e + x.CLEAR);
507
606
  }
508
607
  error(...t) {
509
608
  if (g2.LOG_LEVEL < 0) return;
510
609
  const e = this.format(...t);
511
- g2.emit(0, e), console.error(j.RED + e + x.CLEAR);
610
+ g2.emit(0, e), console.error($.RED + e + x.CLEAR);
512
611
  }
513
612
  };
514
613
  c(g, "LOG_LEVEL", 4);
515
- var $ = typeof globalThis < "u" ? globalThis : typeof window < "u" ? window : typeof global < "u" ? global : typeof self < "u" ? self : {}, xt = {}, S = {};
614
+ var j = typeof globalThis < "u" ? globalThis : typeof window < "u" ? window : typeof global < "u" ? global : typeof self < "u" ? self : {}, xt = {}, S = {};
516
615
  Object.defineProperty(S, "__esModule", { value: true });
517
616
  S.persist = S.Persist = void 0;
518
617
  class st {
@@ -632,7 +731,7 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
632
731
  }
633
732
  L.MemoryStorage = At;
634
733
  (function(r) {
635
- var t = $ && $.__createBinding || (Object.create ? function(n, s, o, i) {
734
+ var t = j && j.__createBinding || (Object.create ? function(n, s, o, i) {
636
735
  i === void 0 && (i = o);
637
736
  var a = Object.getOwnPropertyDescriptor(s, o);
638
737
  (!a || ("get" in a ? !s.__esModule : a.writable || a.configurable)) && (a = { enumerable: true, get: function() {
@@ -640,22 +739,120 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
640
739
  } }), Object.defineProperty(n, i, a);
641
740
  } : function(n, s, o, i) {
642
741
  i === void 0 && (i = o), n[i] = s[o];
643
- }), e = $ && $.__exportStar || function(n, s) {
742
+ }), e = j && j.__exportStar || function(n, s) {
644
743
  for (var o in n) o !== "default" && !Object.prototype.hasOwnProperty.call(s, o) && t(s, n, o);
645
744
  };
646
745
  Object.defineProperty(r, "__esModule", { value: true }), e(S, r), e(L, r);
647
746
  })(xt);
747
+ function combinePathedEvents(...paths) {
748
+ let hitNone = false;
749
+ const combined = paths.map((p2) => typeof p2 == "string" ? parsePathedEvent(p2) : p2).toSorted((p1, p2) => {
750
+ const l1 = p1.fullPath.length, l2 = p2.fullPath.length;
751
+ return l1 < l2 ? 1 : l1 > l2 ? -1 : 0;
752
+ }).reduce((acc, p2) => {
753
+ if (p2.none) hitNone = true;
754
+ if (!acc) return p2;
755
+ if (hitNone) return acc;
756
+ if (p2.all) acc.all = true;
757
+ if (p2.all || p2.create) acc.create = true;
758
+ if (p2.all || p2.read) acc.read = true;
759
+ if (p2.all || p2.update) acc.update = true;
760
+ if (p2.all || p2.delete) acc.delete = true;
761
+ if (p2.all || p2.execute) acc.execute = true;
762
+ acc.methods = [...acc.methods, ...p2.methods];
763
+ return acc;
764
+ }, null);
765
+ if (combined.all) combined.methods = ["*"];
766
+ if (combined.none) combined.methods = ["n"];
767
+ combined.methods = new B(combined.methods);
768
+ combined.full = pathedEvent(combined.fullPath, ...combined.methods);
769
+ return combined;
770
+ }
771
+ function hasPath(target, ...anyPath) {
772
+ const parsedRequired = anyPath.map(parsePathedEvent);
773
+ const parsedTarget = ft(target).map(parsePathedEvent);
774
+ return !!parsedRequired.find((r) => {
775
+ if (r.all) return true;
776
+ const filtered = parsedTarget.filter((p2) => r.fullPath.startsWith(p2.fullPath));
777
+ if (!filtered.length) return false;
778
+ const combined = combinePathedEvents(...filtered);
779
+ return !combined.none && (combined.all || new B(combined.methods).intersection(new B(r.methods)).length);
780
+ });
781
+ }
782
+ function hasPathFatal(target, ...paths) {
783
+ if (!hasPath(target, ...paths)) throw new Error(`Missing permission: ${paths.join(", ")}`);
784
+ }
785
+ function pathedEvent(path, ...methods) {
786
+ var _a;
787
+ let p2 = ft(path).map((p22) => p22 == null ? void 0 : p22.toString()).filter((p22) => !!p22).map((p22) => p22 == null ? void 0 : p22.replaceAll(/(^\/|\/$)/g, "")).join("/");
788
+ if (methods.length) p2 += `:${methods.join("")}`;
789
+ return (_a = p2 == null ? void 0 : p2.replaceAll("//", "/")) == null ? void 0 : _a.trim();
790
+ }
791
+ function parsePathedEvent(path) {
792
+ var _a;
793
+ if (typeof path == "object") return path;
794
+ let [p2, scope, method] = path.split(":");
795
+ if (!method) method = scope || "*";
796
+ if (p2 == "*" || !p2 && method == "*") {
797
+ p2 = "";
798
+ method = "*";
799
+ }
800
+ let temp = p2.split("/").filter((p22) => !!p22);
801
+ return {
802
+ full: path,
803
+ module: ((_a = temp.splice(0, 1)[0]) == null ? void 0 : _a.toLowerCase()) || "",
804
+ fullPath: p2,
805
+ path: temp.join("/"),
806
+ methods: method.split(""),
807
+ all: method == null ? void 0 : method.includes("*"),
808
+ none: method == null ? void 0 : method.includes("n"),
809
+ create: !(method == null ? void 0 : method.includes("n")) && ((method == null ? void 0 : method.includes("*")) || (method == null ? void 0 : method.includes("w")) || (method == null ? void 0 : method.includes("c"))),
810
+ read: !(method == null ? void 0 : method.includes("n")) && ((method == null ? void 0 : method.includes("*")) || (method == null ? void 0 : method.includes("r"))),
811
+ update: !(method == null ? void 0 : method.includes("n")) && ((method == null ? void 0 : method.includes("*")) || (method == null ? void 0 : method.includes("w")) || (method == null ? void 0 : method.includes("u"))),
812
+ delete: !(method == null ? void 0 : method.includes("n")) && ((method == null ? void 0 : method.includes("*")) || (method == null ? void 0 : method.includes("w")) || (method == null ? void 0 : method.includes("d"))),
813
+ execute: !(method == null ? void 0 : method.includes("n")) && ((method == null ? void 0 : method.includes("*")) || (method == null ? void 0 : method.includes("x")))
814
+ };
815
+ }
816
+ class PathedEventEmitter {
817
+ constructor() {
818
+ __publicField(this, "listeners", []);
819
+ }
820
+ emit(event, ...args) {
821
+ const parsed = parsePathedEvent(event);
822
+ this.listeners.filter((l) => hasPath(l[0], event)).forEach((l) => l[1](parsed, ...args));
823
+ }
824
+ off(listener) {
825
+ this.listeners = this.listeners.filter((l) => l[1] != listener);
826
+ }
827
+ on(event, listener) {
828
+ ft(event).forEach((e) => this.listeners.push([parsePathedEvent(e), listener]));
829
+ return () => this.off(listener);
830
+ }
831
+ once(event, listener) {
832
+ return new Promise((res) => {
833
+ const unsubscribe = this.on(event, (event2, ...args) => {
834
+ res(args);
835
+ if (listener) listener(event2, ...args);
836
+ unsubscribe();
837
+ });
838
+ });
839
+ }
840
+ relayEvents(emitter) {
841
+ emitter.on("*", (event, ...args) => this.emit(event, ...args));
842
+ }
843
+ }
648
844
  class Api extends F {
649
845
  constructor(url = location.origin, opts = {}) {
650
846
  opts.url = url;
651
847
  super(opts);
652
- __publicField(this, "emitter", new _());
848
+ __publicField(this, "emitter", new PathedEventEmitter());
653
849
  __publicField(this, "pending", {});
654
850
  __publicField(this, "_token", null);
655
851
  __publicField(this, "emit", this.emitter.emit.bind(this.emitter));
656
852
  __publicField(this, "off", this.emitter.off.bind(this.emitter));
657
853
  __publicField(this, "on", this.emitter.on.bind(this.emitter));
658
854
  __publicField(this, "once", this.emitter.once.bind(this.emitter));
855
+ __publicField(this, "relayEvents", this.emitter.relayEvents.bind(this.emitter));
659
856
  this.url = url;
660
857
  this.opts = opts;
661
858
  }
@@ -666,26 +863,27 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
666
863
  if (token == this._token) return;
667
864
  this._token = token;
668
865
  this.headers["Authorization"] = token ? `Bearer ${token}` : null;
669
- this.emit("token", token);
866
+ this.emit(pathedEvent("api/token", "u"), token);
670
867
  }
671
868
  healthcheck() {
672
- return this.request({ url: "/api/healthcheck" });
673
- }
674
- path(...children) {
675
- return children.filter((p2) => !!p2).join("/").replaceAll("//", "/");
869
+ return this.request({ url: "/api/healthcheck" }).then((resp) => {
870
+ this.emit(pathedEvent("api/healthcheck", "r"), resp);
871
+ return resp;
872
+ });
676
873
  }
677
874
  request(options) {
678
875
  const key = Lt(options);
876
+ const method = options.method == "GET" ? "r" : options.method == "POST" ? "c" : options.method == "DELETE" ? "d" : "u";
679
877
  if (this.pending[key] != null) return this.pending[key];
680
878
  this.pending[key] = super.request(options).then((resp) => {
681
- this.emit("response", resp, options);
879
+ this.emit(pathedEvent("api/response", method), resp, options);
682
880
  return resp.data;
683
881
  }).catch((err) => {
684
882
  const e = (err == null ? void 0 : err.data) || err;
685
- this.emit("rejected", e, options);
883
+ this.emit(pathedEvent("api/error", method), e, options);
686
884
  throw e;
687
885
  }).finally(() => delete this.pending[key]);
688
- this.emit("request", this.pending[key], options);
886
+ this.emit(pathedEvent("api/request", method), this.pending[key], options);
689
887
  return this.pending[key];
690
888
  }
691
889
  }
@@ -699,7 +897,7 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
699
897
  ActionType2[ActionType2["PUT"] = 6] = "PUT";
700
898
  return ActionType2;
701
899
  })(ActionType || {});
702
- class Actions extends _ {
900
+ class Actions extends PathedEventEmitter {
703
901
  constructor(api) {
704
902
  super();
705
903
  __publicField(this, "api");
@@ -707,80 +905,86 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
707
905
  this.api = typeof api == "string" ? new Api(api) : api;
708
906
  }
709
907
  delete(id) {
710
- return this.api.request({ url: `/api/actions/${id}`, method: "DELETE" }).then(() => {
908
+ if (!id) throw new Error("Cannot delete action, missing ID");
909
+ return this.api.request({ url: `/api/` + pathedEvent(["actions", id]), method: "DELETE" }).then(() => {
711
910
  this.cache.delete(id);
712
- this.emit("delete", id);
911
+ this.emit(pathedEvent(["actions", id], "d"), id);
713
912
  });
714
913
  }
715
914
  all() {
716
915
  return this.api.request({ url: `/api/actions` }).then((resp) => {
717
916
  this.cache.addAll(resp);
718
- this.emit("all", resp || []);
917
+ this.emit(pathedEvent("actions", "r"), resp || []);
719
918
  return resp;
720
919
  });
721
920
  }
722
921
  read(id, reload = false) {
922
+ if (!id) throw new Error("Cannot read action, missing ID");
723
923
  const cached = this.cache.get(id);
724
924
  if (!reload && cached) return Promise.resolve(cached);
725
- return this.api.request({ url: `/api/actions/${id}` }).then((action) => {
925
+ return this.api.request({ url: `/api/` + pathedEvent(["actions", id]) }).then((action) => {
726
926
  if (action) this.cache.add(action);
727
- this.emit("read", action);
927
+ this.emit(pathedEvent(["actions", id], "r"), action);
728
928
  return action;
729
929
  });
730
930
  }
731
931
  run(path, opts = {}) {
732
- return this.api.request({ url: (`/api/actions/run/` + path).replaceAll("//", "/"), ...opts }).then((resp) => {
733
- this.emit("execute", path, resp);
932
+ if (!path) throw new Error("Cannot run action, missing path");
933
+ return this.api.request({ url: `/api/` + pathedEvent(["actions/run", path]), ...opts }).then((resp) => {
934
+ this.emit(pathedEvent(["actions/run", path], "x"), resp);
734
935
  return resp;
735
936
  });
736
937
  }
737
938
  runById(action, opts = {}) {
738
- const id = typeof action == "string" ? action : action._id;
739
- return this.api.request({ url: "/api/actions/run-by-id/" + id, method: "POST", ...opts }).then((resp) => {
740
- this.emit("execute", typeof action == "string" ? action : action._id, resp);
939
+ const id = typeof action == "string" ? action : action == null ? void 0 : action._id;
940
+ if (!id) throw new Error("Cannot run action, missing ID");
941
+ return this.api.request({ url: "/api/" + pathedEvent(["actions/run-by-id", id]), method: "POST", ...opts }).then((resp) => {
942
+ this.emit(pathedEvent(["actions/run-by-id", id], "x"), resp);
741
943
  return resp;
742
944
  });
743
945
  }
744
946
  update(action) {
745
947
  return this.api.request({
746
- url: `/api/actions${action._id ? `/${action._id}` : ""}`,
948
+ url: `/api/` + pathedEvent(["actions", action._id]),
747
949
  method: "POST",
748
950
  body: action
749
951
  }).then((action2) => {
750
952
  if (action2) this.cache.add(action2);
751
- this.emit("update", action2);
953
+ this.emit(pathedEvent(["actions", action2._id], "u"), action2);
752
954
  return action2;
753
955
  });
754
956
  }
755
957
  }
756
- class Ai extends _ {
958
+ class Ai extends PathedEventEmitter {
757
959
  constructor(api) {
758
960
  super();
759
961
  __publicField(this, "api");
760
962
  this.api = typeof api == "string" ? new Api(api) : api;
761
963
  }
762
964
  ask(question, context) {
965
+ if (!question) throw new Error("Cannot ask AI, missing question");
763
966
  return this.api.request({ url: `/api/ai`, method: "POST", body: {
764
967
  question,
765
968
  context
766
969
  } }).then((resp) => {
767
- this.emit("ask", question, context, resp);
970
+ this.emit(pathedEvent("ai", "c"), question, context, resp);
768
971
  return resp;
769
972
  });
770
973
  }
771
974
  clear() {
772
- return this.api.request({ url: "/api/ai", method: "DELETE" });
975
+ return this.api.request({ url: "/api/ai", method: "DELETE" }).then(() => this.emit(pathedEvent("ai", "d")));
773
976
  }
774
977
  }
775
- class Analytics extends _ {
978
+ class Analytics extends PathedEventEmitter {
776
979
  constructor(api) {
777
980
  super();
778
981
  __publicField(this, "api");
779
982
  this.api = typeof api == "string" ? new Api(api) : api;
780
983
  }
781
984
  ipTrace(ip) {
985
+ if (!ip) throw new Error("Cannot trace, missing IP");
782
986
  return this.api.request({ url: `/api/analytics/trace?ip=${ip}` }).then((resp) => {
783
- this.emit("ipTrace", ip, resp);
987
+ this.emit(pathedEvent("analytics/trace", "r"), ip, resp);
784
988
  return resp;
785
989
  });
786
990
  }
@@ -803,7 +1007,7 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
803
1007
  }) });
804
1008
  }
805
1009
  }
806
- class Auth extends _ {
1010
+ class Auth extends PathedEventEmitter {
807
1011
  constructor(api, opts = {}) {
808
1012
  super();
809
1013
  __publicField(this, "api");
@@ -826,10 +1030,10 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
826
1030
  "/api/auth/totp"
827
1031
  ];
828
1032
  if (resp.status == 401 && !blacklist.find((url) => resp.url.includes(url)))
829
- this.emit("sessionExpired");
1033
+ this.emit(pathedEvent("auth/session-expired", "d"));
830
1034
  next();
831
1035
  });
832
- this.api.on("token", (token) => {
1036
+ this.api.on("api/token", (event, token) => {
833
1037
  var _a;
834
1038
  if ((_a = this.opts) == null ? void 0 : _a.persist) {
835
1039
  if (token) localStorage.setItem(this.storageKey, token);
@@ -853,15 +1057,18 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
853
1057
  set user(user) {
854
1058
  if (!A(this.user, user)) {
855
1059
  this._user = user ? user : null;
856
- this.emit("user", this._user);
1060
+ this.emit(pathedEvent("auth/user", "u"), this._user);
857
1061
  }
858
1062
  }
859
1063
  knownHost(host = location.origin) {
860
1064
  if (host.startsWith("/")) return Promise.resolve();
861
- return this.api.request({ url: `/api/auth/known-host?host=${encodeURI(new URL(host).origin)}` }).then(() => {
1065
+ return this.api.request({ url: `/api/auth/known-host?host=${encodeURI(new URL(host).origin)}` }).then(() => this.emit(pathedEvent("auth/known-host", "r"), host, true)).catch((err) => {
1066
+ this.emit(pathedEvent("auth/known-host", "r"), host, false);
1067
+ throw err;
862
1068
  });
863
1069
  }
864
1070
  login(username, password, totp) {
1071
+ if (!username || !password) throw new Error("Cannot login, missing username or password");
865
1072
  return this.api.request({
866
1073
  url: "/api/auth/login",
867
1074
  headers: { Authorization: void 0 },
@@ -873,8 +1080,8 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
873
1080
  }
874
1081
  }).then(async (resp) => {
875
1082
  this.api.token = (resp == null ? void 0 : resp.token) || null;
876
- const user = await this.once("user");
877
- this.emit("login", user);
1083
+ const user = await this.once("auth/user");
1084
+ this.emit(pathedEvent(["auth/login", username], "x"), user);
878
1085
  return user;
879
1086
  });
880
1087
  }
@@ -897,16 +1104,18 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
897
1104
  logout() {
898
1105
  this.api.token = null;
899
1106
  this.user = null;
900
- this.emit("logout");
1107
+ this.emit(pathedEvent("auth/logout", "d"));
901
1108
  }
902
1109
  async register(u) {
903
1110
  var _a;
1111
+ if (!u.username || !u.password) throw new Error("Cannot register user, missing username or password");
904
1112
  const user = await this.api.request({ url: "/api/auth/register", body: { ...u } });
905
1113
  if ((_a = user == null ? void 0 : user.image) == null ? void 0 : _a.startsWith("/")) user.image = `${this.api.url}${user.image}?token=${this.api.token}`;
906
- this.emit("register", user);
1114
+ this.emit(pathedEvent("auth/register", "c"), user);
907
1115
  return user;
908
1116
  }
909
1117
  reset(emailOrPass, token) {
1118
+ if (!emailOrPass) throw new Error("Cannot reset password, missing email or token");
910
1119
  return this.api.request({
911
1120
  url: "/api/auth/reset",
912
1121
  headers: { "Authorization": token ? `Bearer ${token}` : void 0 },
@@ -915,8 +1124,7 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
915
1124
  password: token ? emailOrPass : void 0
916
1125
  }
917
1126
  }).then(() => {
918
- if (token) this.emit("reset", token);
919
- else this.emit("resetRequest", emailOrPass);
1127
+ this.emit(pathedEvent("auth/reset", token ? "u" : "c"), token || emailOrPass);
920
1128
  });
921
1129
  }
922
1130
  async session(token, set = false) {
@@ -925,25 +1133,29 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
925
1133
  url: "/api/auth/session",
926
1134
  headers: token ? { "Authorization": `Bearer ${token}` } : void 0
927
1135
  });
1136
+ this.emit(pathedEvent("auth/session", "r"), session);
928
1137
  if (set) {
929
1138
  this.api.token = token;
930
1139
  if (session == null ? void 0 : session.user) session.user.image = `${this.api.url}${session.user.image}?token=${this.api.token}`;
931
1140
  this.user = (session == null ? void 0 : session.user) || null;
932
- if (session) this.emit("login", session.user);
1141
+ if (session) this.emit(pathedEvent("auth/login", "c"), session.user);
933
1142
  }
934
1143
  return session;
935
1144
  }
936
1145
  async updatePassword(username, password, oldPassword) {
1146
+ if (!username || !password) throw new Error("Cannot update password, missing username or password");
937
1147
  return this.api.request({
938
1148
  url: "/api/auth/password",
939
1149
  body: { username, password, oldPassword }
940
1150
  }).then((resp) => {
1151
+ this.emit(pathedEvent("auth/reset", "u"), resp == null ? void 0 : resp.token);
941
1152
  if (resp == null ? void 0 : resp.token) this.api.token = resp.token;
942
1153
  });
943
1154
  }
944
1155
  }
945
- class Client {
1156
+ class Client extends PathedEventEmitter {
946
1157
  constructor(settings) {
1158
+ super();
947
1159
  __publicField(this, "_platform");
948
1160
  __publicField(this, "_pwa");
949
1161
  this.settings = settings;
@@ -970,7 +1182,7 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
970
1182
  }
971
1183
  async inject(reload = false) {
972
1184
  var _a, _b, _c, _d, _e, _f, _g, _h;
973
- const settings = await this.settings.all();
1185
+ const settings = await this.settings.all(false, reload);
974
1186
  if (!document.querySelector('meta[name="mobile-web-app-capable"]')) {
975
1187
  const meta = document.createElement("meta");
976
1188
  meta.name = "mobile-web-app-capable";
@@ -1042,6 +1254,7 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
1042
1254
  if (!dismissed && !this.pwa && this.mobile) this.pwaPrompt();
1043
1255
  }, 500);
1044
1256
  }
1257
+ this.emit(pathedEvent("client/inject", "c"));
1045
1258
  }
1046
1259
  pwaPrompt(platform) {
1047
1260
  const url = this.settings.api.url;
@@ -1158,88 +1371,101 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
1158
1371
  setTimeout(() => {
1159
1372
  prompt.remove();
1160
1373
  backdrop.remove();
1374
+ this.emit(pathedEvent("client/pwa", "d"), platform);
1161
1375
  }, 500);
1162
1376
  };
1163
1377
  prompt.append(close);
1164
1378
  backdrop.append(prompt);
1165
1379
  document.body.append(backdrop);
1380
+ this.emit(pathedEvent("client/pwa", "c"), platform);
1166
1381
  }
1167
1382
  }
1168
- class Data extends _ {
1383
+ class Data extends PathedEventEmitter {
1169
1384
  constructor(api) {
1170
1385
  super();
1171
1386
  __publicField(this, "api");
1172
1387
  this.api = typeof api == "string" ? new Api(api) : api;
1173
1388
  }
1174
1389
  create(collection, document2) {
1390
+ if (!collection || !document2) throw new Error("Cannot create document, missing collection or document");
1175
1391
  return this.api.request({
1176
- url: `/api/data/${collection.replaceAll(/(^\/|\/$)/g, "")}`,
1392
+ url: `/api/` + pathedEvent(["data", collection]),
1177
1393
  method: "POST",
1178
1394
  body: document2
1179
1395
  }).then((resp) => {
1180
- this.emit("create", collection, resp);
1396
+ this.emit(pathedEvent(["data", collection], "c"), collection, resp);
1181
1397
  return resp;
1182
1398
  });
1183
1399
  }
1184
1400
  read(collection, id) {
1185
- return this.api.request({ url: `/api/data/${collection.replaceAll(/(^\/|\/$)/g, "")}/${id ?? ""}` }).then((resp) => {
1186
- this.emit("read", collection, resp);
1401
+ if (!collection) throw new Error("Cannot read documents, missing collection");
1402
+ return this.api.request({ url: `/api/` + pathedEvent(["data", collection, id]) }).then((resp) => {
1403
+ this.emit(pathedEvent(["data", collection, id], "r"), collection, resp);
1187
1404
  return resp;
1188
1405
  });
1189
1406
  }
1190
1407
  update(collection, document2, append = true) {
1408
+ if (!collection || !document2) throw new Error("Cannot update document, missing collection or document");
1191
1409
  if (!document2._id) return this.create(collection, document2);
1192
1410
  return this.api.request({
1193
- url: `/api/data/${collection.replaceAll(/(^\/|\/$)/g, "")}/${document2._id}`,
1411
+ url: `/api/` + pathedEvent(["data", collection, document2._id]),
1194
1412
  method: append ? "PATCH" : "PUT",
1195
1413
  body: document2
1196
1414
  }).then((resp) => {
1197
- this.emit("update", collection, resp);
1415
+ this.emit(pathedEvent(["data", collection, document2._id], "u"), collection, resp);
1198
1416
  return resp;
1199
1417
  });
1200
1418
  }
1201
1419
  delete(collection, id) {
1420
+ if (!collection || !id) throw new Error("Cannot delete document, missing collection or ID");
1202
1421
  return this.api.request({
1203
- url: `/api/data/${collection.replaceAll(/(^\/|\/$)/g, "")}/${id}`,
1422
+ url: `/api/` + pathedEvent(["data", collection, id]),
1204
1423
  method: "DELETE"
1205
- }).then(() => this.emit("delete", collection, id));
1424
+ }).then(() => this.emit(pathedEvent(["data", collection, id], "d"), collection, id));
1206
1425
  }
1207
1426
  raw(collection, query) {
1208
- return this.api.request({ url: `/api/data/${collection.replaceAll(/(^\/|\/$)/g, "")}`, body: query }).then((resp) => {
1209
- this.emit("raw", collection, query, resp);
1427
+ if (!collection || !query) throw new Error("Cannot execute raw query, missing collection or query");
1428
+ const mode = query.operand.startsWith("find") ? "r" : query.operand == "insert" ? "c" : query.operand.startsWith("delete") ? "d" : "u";
1429
+ return this.api.request({ url: `/api/` + pathedEvent(["data/raw", collection]) + "?raw", body: query }).then((resp) => {
1430
+ this.emit(pathedEvent(["data", collection], mode), collection, query, resp);
1210
1431
  return resp;
1211
1432
  });
1212
1433
  }
1213
- deleteSchema(collection) {
1214
- return this.api.request({ url: `/api/data/schema/${collection.replaceAll(/(^\/|\/$)/g, "")}`, method: "DELETE" });
1434
+ deleteSchema(path) {
1435
+ if (!path) throw new Error("Cannot delete schema, missing collection path");
1436
+ return this.api.request({ url: `/api/` + pathedEvent(["schema", path]), method: "DELETE" }).then(() => this.emit(pathedEvent(["schema", path], "d"), path));
1215
1437
  }
1216
1438
  getSchema(pathOrTree) {
1217
- let url = "/api/data/schema";
1218
- if (typeof pathOrTree == "string") url += `/${pathOrTree.replaceAll(/(^\/|\/$)/g, "")}`;
1219
- else if (typeof pathOrTree == "boolean") url += `?tree=${pathOrTree}`;
1220
- return this.api.request({ url });
1439
+ return this.api.request({ url: "/api/" + pathedEvent(["schema", typeof pathOrTree == "string" ? pathOrTree : ""]) + (pathOrTree === true ? `?tree=${pathOrTree}` : "") }).then((resp) => {
1440
+ this.emit(pathedEvent(["schema", typeof pathOrTree == "string" ? pathOrTree : ""], "r"), resp);
1441
+ return resp;
1442
+ });
1221
1443
  }
1222
1444
  setSchema(schema) {
1223
- if (!schema.path) throw new Error("Unable to create schema, missing path");
1224
- return this.api.request({ url: `/api/data/schema/${schema.path.replaceAll(/(^\/|\/$)/g, "")}`, body: schema });
1445
+ if (!schema.path) throw new Error("Cannot update schema, missing collection path");
1446
+ return this.api.request({ url: "/api/" + pathedEvent(["schema", schema.path]), body: schema }).then((resp) => {
1447
+ this.emit(pathedEvent(["schema", schema.path], schema._id ? "u" : "c"), resp);
1448
+ return resp;
1449
+ });
1225
1450
  }
1226
1451
  }
1227
- class Email extends _ {
1452
+ class Email extends PathedEventEmitter {
1228
1453
  constructor(api) {
1229
1454
  super();
1230
1455
  __publicField(this, "api");
1231
1456
  this.api = typeof api == "string" ? new Api(api) : api;
1232
1457
  }
1233
1458
  send(email) {
1234
- let url = "/api/email";
1235
- if (typeof email.body == "object") url += `/${email.body.template}`;
1236
- return this.api.request({ url, body: email }).then((resp) => {
1237
- this.emit("sent", email, resp);
1459
+ var _a;
1460
+ if (!email.to && !email.bcc || !email.body) throw new Error("Cannot send email, missing address or body");
1461
+ return this.api.request({ url: "/api/" + pathedEvent(["email", (_a = email.body) == null ? void 0 : _a.template]), body: email }).then((resp) => {
1462
+ var _a2;
1463
+ this.emit(pathedEvent(["email", (_a2 = email.body) == null ? void 0 : _a2.template], "c"), email, resp);
1238
1464
  return resp;
1239
1465
  });
1240
1466
  }
1241
1467
  }
1242
- class Groups extends _ {
1468
+ class Groups extends PathedEventEmitter {
1243
1469
  constructor(api) {
1244
1470
  super();
1245
1471
  __publicField(this, "api");
@@ -1247,46 +1473,52 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
1247
1473
  }
1248
1474
  all() {
1249
1475
  return this.api.request({ url: `/api/groups` }).then((resp) => {
1250
- this.emit("all", resp || []);
1476
+ this.emit(pathedEvent("groups", "r"), resp || []);
1251
1477
  return resp;
1252
1478
  });
1253
1479
  }
1254
1480
  create(group) {
1481
+ if (!group.name) throw new Error("Cannot create group, missing name");
1255
1482
  return this.api.request({
1256
1483
  url: `/api/groups/${group.name}`,
1257
1484
  method: "POST",
1258
1485
  body: group
1259
1486
  }).then((resp) => {
1260
- this.emit("create", resp);
1487
+ this.emit(pathedEvent(["groups", group.name], "c"), resp);
1261
1488
  return resp;
1262
1489
  });
1263
1490
  }
1264
1491
  read(name) {
1265
- return this.api.request({ url: `/api/groups/${name}` }).then((resp) => {
1266
- this.emit("read", resp);
1492
+ if (!name) throw new Error("Cannot read group, missing name");
1493
+ return this.api.request({ url: `/api/` + pathedEvent(["groups", name]) }).then((resp) => {
1494
+ this.emit(pathedEvent(["groups", name], "r"), resp);
1267
1495
  return resp;
1268
1496
  });
1269
1497
  }
1270
1498
  update(group) {
1499
+ if (!group.name) throw new Error("Cannot update group, missing name");
1271
1500
  return this.api.request({
1272
- url: `/api/groups/${group.name}`,
1501
+ url: `/api/` + pathedEvent(["groups", group.name]),
1273
1502
  method: "PATCH",
1274
1503
  body: group
1275
1504
  }).then((resp) => {
1276
- this.emit("update", resp);
1505
+ this.emit(pathedEvent(["groups", group.name], "u"), resp);
1277
1506
  return resp;
1278
1507
  });
1279
1508
  }
1280
1509
  delete(name) {
1510
+ if (!name) throw new Error("Cannot delete group, missing name");
1281
1511
  return this.api.request({
1282
- url: `/api/groups/${name}`,
1512
+ url: `/api/` + pathedEvent(["groups", name]),
1283
1513
  method: "DELETE"
1284
- }).then(() => this.emit("delete", name));
1514
+ }).then(() => this.emit(pathedEvent(["groups", name], "d")));
1285
1515
  }
1286
1516
  }
1287
- class Logger {
1288
- constructor(api, logLevel) {
1517
+ class Logger extends PathedEventEmitter {
1518
+ constructor(api, namespace, logLevel) {
1519
+ super();
1289
1520
  __publicField(this, "api");
1521
+ this.namespace = namespace;
1290
1522
  this.api = typeof api == "string" ? new Api(api) : api;
1291
1523
  if (logLevel != null && logLevel != "NONE") {
1292
1524
  window.addEventListener("error", (event) => {
@@ -1317,47 +1549,44 @@ ${log}`;
1317
1549
  }
1318
1550
  };
1319
1551
  }
1320
- clearClientLogs() {
1321
- return this.api.request({ url: `/api/logs/client`, method: "DELETE" });
1552
+ createLog(log, namespace = this.namespace) {
1553
+ return this.api.request({ url: `/api/` + pathedEvent(["logs", namespace]), body: log }).then(() => this.emit(pathedEvent(["logs", namespace], "c"), log)).catch(() => {
1554
+ });
1555
+ }
1556
+ clearLogs(namespace = this.namespace) {
1557
+ return this.api.request({ url: `/api/` + pathedEvent(["logs", namespace]), method: "DELETE" }).then(() => this.emit(pathedEvent(["logs", namespace], "d")));
1322
1558
  }
1323
1559
  clearServerLogs() {
1324
- return this.api.request({ url: `/api/logs/server`, method: "DELETE" });
1560
+ return this.clearLogs("server");
1325
1561
  }
1326
- clientLogs(length, page) {
1562
+ getLogs(length, page, namespace = this.namespace) {
1563
+ if (!namespace) throw new Error("Cannot get logs, missing namespace");
1327
1564
  const query = [length ? `length=${length}` : void 0, page ? `page=${page}` : void 0].filter((v) => !!v).join("&");
1328
- return this.api.request({ url: `/api/logs/client${query ? `?${query}` : ""}` }).then((resp) => resp);
1565
+ return this.api.request({ url: `/api/` + pathedEvent(["logs", namespace]) + (query ? `?${query}` : "") }).then((logs) => {
1566
+ this.emit(pathedEvent(["logs", namespace], "r"), logs);
1567
+ return logs;
1568
+ });
1329
1569
  }
1330
- serverLogs(length, page) {
1331
- const query = [length ? `length=${length}` : void 0, page ? `page=${page}` : void 0].filter((v) => !!v).join("&");
1332
- return this.api.request({ url: `/api/logs/server${query ? `?${query}` : ""}` }).then((resp) => resp);
1570
+ getServerLogs(length, page) {
1571
+ return this.getLogs(length, page, "server");
1333
1572
  }
1334
- debug(...logs) {
1335
- return this.api.request({ url: `/api/logs/client`, body: this.buildLog(yt.DEBUG, logs) }).then(() => {
1336
- }).catch(() => {
1337
- });
1573
+ debug(log, namespace = this.namespace) {
1574
+ return this.createLog(this.buildLog(yt.DEBUG, log), namespace);
1338
1575
  }
1339
- log(...logs) {
1340
- return this.api.request({ url: `/api/logs/client`, body: this.buildLog(yt.LOG, logs) }).then(() => {
1341
- }).catch(() => {
1342
- });
1576
+ log(log, namespace = this.namespace) {
1577
+ return this.createLog(this.buildLog(yt.LOG, log), namespace);
1343
1578
  }
1344
- info(...logs) {
1345
- return this.api.request({ url: `/api/logs/client`, body: this.buildLog(yt.INFO, logs) }).then(() => {
1346
- }).catch(() => {
1347
- });
1579
+ info(log, namespace = this.namespace) {
1580
+ return this.createLog(this.buildLog(yt.INFO, log), namespace);
1348
1581
  }
1349
- warn(...logs) {
1350
- return this.api.request({ url: `/api/logs/client`, body: this.buildLog(yt.WARN, logs) }).then(() => {
1351
- }).catch(() => {
1352
- });
1582
+ warn(log, namespace = this.namespace) {
1583
+ return this.createLog(this.buildLog(yt.WARN, log), namespace);
1353
1584
  }
1354
- error(...logs) {
1355
- return this.api.request({ url: `/api/logs/client`, body: this.buildLog(yt.ERROR, logs) }).then(() => {
1356
- }).catch(() => {
1357
- });
1585
+ error(log, namespace = this.namespace) {
1586
+ return this.createLog(this.buildLog(yt.ERROR, log), namespace);
1358
1587
  }
1359
1588
  }
1360
- class Payments extends _ {
1589
+ class Payments extends PathedEventEmitter {
1361
1590
  constructor(api, secret) {
1362
1591
  super();
1363
1592
  __publicField(this, "api");
@@ -1375,11 +1604,12 @@ ${log}`;
1375
1604
  setup();
1376
1605
  }
1377
1606
  async create(amount, custom = {}) {
1607
+ if (!amount) throw new Error("Please specify a valid amount`");
1378
1608
  const request = await this.api.request({ url: "/api/payments", body: {
1379
1609
  amount,
1380
1610
  custom
1381
1611
  } });
1382
- this.emit("create", amount, custom, request.data.clientSecret);
1612
+ this.emit(pathedEvent("payments", "c"), amount, custom, request.data.clientSecret);
1383
1613
  return request.data.clientSecret;
1384
1614
  }
1385
1615
  async createForm(element, amount, custom) {
@@ -1393,35 +1623,42 @@ ${log}`;
1393
1623
  });
1394
1624
  }
1395
1625
  async history(username) {
1396
- const history = await this.api.request({ url: `/api/payments${username ? `/${username}` : ""}` });
1397
- this.emit("history", username || null, history);
1626
+ const history = await this.api.request({ url: `/api/` + pathedEvent("payments", username) });
1627
+ this.emit(pathedEvent(["payments", username], "r"), username, history);
1398
1628
  return history;
1399
1629
  }
1400
1630
  }
1401
- class Pdf extends _ {
1631
+ class Pdf extends PathedEventEmitter {
1402
1632
  constructor(api) {
1403
1633
  super();
1404
1634
  __publicField(this, "api");
1405
1635
  this.api = typeof api == "string" ? new Api(api) : api;
1406
1636
  }
1407
- async handleResponse(resp, fileName) {
1408
- const blob = await resp.blob();
1409
- if (fileName) {
1410
- const url = URL.createObjectURL(blob);
1411
- dt(url, fileName.endsWith(".pdf") ? fileName : fileName + ".pdf");
1412
- URL.revokeObjectURL(url);
1413
- }
1414
- this.emit("create", blob);
1415
- return blob;
1637
+ createPdf(body, options) {
1638
+ return this.api.request({ url: `/api/pdf`, body: { ...body, options }, decode: false }).then(async (resp) => {
1639
+ const blob = await resp.blob();
1640
+ if (options == null ? void 0 : options.download) {
1641
+ let filename = (options == null ? void 0 : options.filename) || qt();
1642
+ if (!filename.endsWith(".pdf")) filename += ".pdf";
1643
+ const url = URL.createObjectURL(blob);
1644
+ dt(url, filename);
1645
+ URL.revokeObjectURL(url);
1646
+ }
1647
+ this.emit(pathedEvent("pdf", "c"), body, options, blob);
1648
+ return blob;
1649
+ });
1416
1650
  }
1417
- fromHtml(content, opts = {}) {
1418
- return this.api.request({ url: `/api/pdf`, body: { html: content }, decode: false }).then((resp) => this.handleResponse(resp, opts.download ? opts.fileName || (/* @__PURE__ */ new Date()).toISOString() : void 0));
1651
+ fromHtml(html, options = {}) {
1652
+ if (!html) throw new Error("Cannot create PDF, missing HTML");
1653
+ return this.createPdf({ html }, options);
1419
1654
  }
1420
- fromTemplate(template, data, opts = {}) {
1421
- return this.api.request({ url: `/api/pdf${template}`, body: data, decode: false }).then((resp) => this.handleResponse(resp, opts.download ? opts.fileName || (/* @__PURE__ */ new Date()).toISOString() : void 0));
1655
+ fromTemplate(template, data, options = {}) {
1656
+ if (!template) throw new Error("Cannot create PDF, missing template");
1657
+ return this.createPdf({ template, data }, options);
1422
1658
  }
1423
- fromUrl(url, opts = {}) {
1424
- return this.api.request({ url: `/api/pdf`, body: { url }, decode: false }).then((resp) => this.handleResponse(resp, opts.download ? opts.fileName || (/* @__PURE__ */ new Date()).toISOString() : void 0));
1659
+ fromUrl(url, options = {}) {
1660
+ if (!url) throw new Error("Cannot create PDF, missing URL");
1661
+ return this.createPdf({ url }, options);
1425
1662
  }
1426
1663
  }
1427
1664
  const _Socket = class _Socket {
@@ -1432,7 +1669,7 @@ ${log}`;
1432
1669
  __publicField(this, "open", false);
1433
1670
  this.api = typeof api == "string" ? new Api(api) : api;
1434
1671
  this.url = this.api.url.replace("http", "ws");
1435
- this.api.on("token", () => this.connect());
1672
+ this.api.on("api/token", () => this.connect());
1436
1673
  this.connect();
1437
1674
  }
1438
1675
  close() {
@@ -1471,126 +1708,127 @@ ${log}`;
1471
1708
  };
1472
1709
  __publicField(_Socket, "timeout", 1e4);
1473
1710
  let Socket = _Socket;
1474
- class Storage extends _ {
1711
+ class Storage extends PathedEventEmitter {
1475
1712
  constructor(api) {
1476
1713
  super();
1477
1714
  __publicField(this, "api");
1478
1715
  this.api = typeof api == "string" ? new Api(api) : api;
1479
1716
  }
1480
- copy(path) {
1481
- const url = this.api.path(path.startsWith("/api/storage/") ? "" : "/api/storage/", path);
1482
- return this.api.request({ url, method: "PUT" }).then((resp) => {
1483
- this.emit("copy", path, resp);
1717
+ copy(source, destination) {
1718
+ if (!source || !destination) throw new Error("Cannot copy file or folder, missing source or destination");
1719
+ return this.api.request({ url: "/api/" + pathedEvent(["storage", destination]), body: { from: source } }).then((resp) => {
1720
+ this.emit(pathedEvent(["storage", destination], "c"), source, destination, resp);
1484
1721
  return resp;
1485
1722
  });
1486
1723
  }
1487
1724
  delete(path) {
1488
- const url = this.api.path(path.startsWith("/api/storage/") ? "" : "/api/storage/", path);
1489
- return this.api.request({ url, method: "DELETE" }).then(() => {
1490
- this.emit("delete", url);
1725
+ if (!path) throw new Error("Cannot delete file or folder, missing path");
1726
+ return this.api.request({ url: "/api/" + pathedEvent(["storage", path]), method: "DELETE" }).then(() => {
1727
+ this.emit(pathedEvent(["storage", path], "d"), path);
1491
1728
  });
1492
1729
  }
1493
1730
  download(path, opts = {}) {
1494
- const url = this.api.path(path.startsWith("/api/storage/") ? "" : "/api/storage/", path);
1495
- return this.api.request({ ...opts, url, decode: false }).then(async (response) => {
1731
+ if (!path) throw new Error("Cannot download file, missing path");
1732
+ return this.api.request({ ...opts, url: "/api/" + pathedEvent(["storage", path]), decode: false }).then(async (response) => {
1496
1733
  const blob = await response.blob();
1497
1734
  const name = opts.downloadAs || path.split("/").pop();
1498
- this.emit("download", path, blob);
1735
+ this.emit(pathedEvent(["storage", path], "r"), path, blob);
1499
1736
  Gt(blob, name);
1500
1737
  return response;
1501
1738
  });
1502
1739
  }
1503
1740
  list(path) {
1504
- const url = this.api.path(path.startsWith("/api/storage/") ? "" : "/api/storage/", path);
1505
- return this.api.request({ url: url + "?list" }).then((resp) => {
1506
- this.emit("list", path, resp);
1741
+ if (!path) path = "/";
1742
+ return this.api.request({ url: "/api/" + pathedEvent(["storage", path]) + "?list" }).then((resp) => {
1743
+ this.emit(pathedEvent(["storage", path], "r"), path, resp);
1507
1744
  return resp;
1508
1745
  });
1509
1746
  }
1510
1747
  open(path, target = "_blank") {
1511
- const url = this.api.path(path.startsWith("/api/storage/") ? "" : "/api/storage/", path);
1512
- const link = `${this.api.url}${url}${this.api.token ? `?token=${this.api.token}` : ""}`;
1748
+ if (!path) throw new Error("Cannot download file, missing path");
1749
+ const link = `${this.api.url}/api/${pathedEvent(["storage", path])}${this.api.token ? `?token=${this.api.token}` : ""}`;
1513
1750
  if (!target) return link;
1514
- this.emit("open", path);
1751
+ this.emit(pathedEvent(["storage", path], "r"), path);
1515
1752
  return window.open(link, target);
1516
1753
  }
1517
1754
  mkdir(path) {
1518
- const url = this.api.path(path.startsWith("/api/storage/") ? "" : "/api/storage/", path);
1519
- return this.api.request({ url: url + "?directory", method: "POST" }).then((resp) => {
1520
- this.emit("mkdir", path, resp);
1755
+ if (!path) throw new Error("Cannot make directory, missing path");
1756
+ return this.api.request({ url: "/api/" + pathedEvent(["storage", path]), body: { directory: true } }).then((resp) => {
1757
+ this.emit(pathedEvent(["storage", path], "c"), path, resp);
1521
1758
  return resp;
1522
1759
  });
1523
1760
  }
1524
- move(from, to) {
1525
- if (from == to) return this.list(to);
1526
- const url = this.api.path(from.startsWith("/api/storage/") ? "" : "/api/storage/", from);
1527
- return this.api.request({ url, method: "PATCH", body: { move: to } }).then((resp) => {
1528
- this.emit("move", from, to, resp);
1761
+ move(source, destination) {
1762
+ if (!source || !destination) throw new Error("Cannot move file or folder, missing source or destination");
1763
+ if (source == destination) return this.list(destination);
1764
+ return this.api.request({ url: "/api/" + pathedEvent(["storage", source]), method: "PATCH", body: { move: destination } }).then((resp) => {
1765
+ this.emit(pathedEvent(["storage", source], "u"), source, destination, resp);
1529
1766
  return resp;
1530
1767
  });
1531
1768
  }
1532
- upload(files, opts = "") {
1769
+ upload(files, opts) {
1533
1770
  return new E(async (res, rej, prog) => {
1534
1771
  if (!files) files = await Ut(typeof opts == "object" ? opts : void 0);
1535
1772
  if (!files || Array.isArray(files) && !files.length) return [];
1536
- const path = this.api.path("/api/storage/", typeof opts == "string" ? opts : opts.path || "");
1773
+ const path = (opts && typeof opts == "object" ? opts == null ? void 0 : opts.path : opts) || "/";
1537
1774
  return Ft({
1538
- url: `${this.api.url}${path}`,
1775
+ url: `${this.api.url}/api/${pathedEvent(["storage", path])}`,
1539
1776
  files: ft(files),
1540
1777
  headers: this.api.headers
1541
1778
  }).onProgress((p2) => {
1542
1779
  prog(p2);
1543
1780
  }).then((resp) => {
1544
- this.emit("upload", resp);
1781
+ this.emit(pathedEvent(["storage", path], "c"), resp);
1545
1782
  res(resp);
1546
1783
  }).catch((err) => rej(err));
1547
1784
  });
1548
1785
  }
1549
1786
  }
1550
- class Users extends _ {
1787
+ class Users extends PathedEventEmitter {
1551
1788
  constructor(api) {
1552
1789
  super();
1553
1790
  __publicField(this, "api");
1554
- __publicField(this, "listed", false);
1555
1791
  __publicField(this, "cache", new Dt("username"));
1556
1792
  this.api = typeof api == "string" ? new Api(api) : api;
1557
1793
  }
1558
1794
  delete(username) {
1795
+ if (!username) throw new Error("Cannot delete user, missing username");
1559
1796
  return this.api.request({
1560
- url: `/api/users/${username}`,
1797
+ url: "/api/" + pathedEvent(["users", username]),
1561
1798
  method: "DELETE"
1562
1799
  }).then(() => {
1563
1800
  this.cache.delete(username);
1564
- this.emit("delete", username);
1801
+ this.emit(pathedEvent(["users", username], "d"), username);
1565
1802
  });
1566
1803
  }
1567
1804
  async all(reload = false) {
1568
1805
  if (!reload && this.cache.complete) return this.cache.all();
1569
- return this.api.request({ url: `/api/users` }).then((resp) => {
1806
+ return this.api.request({ url: "/api/" + pathedEvent("users") }).then((resp) => {
1570
1807
  resp == null ? void 0 : resp.forEach((r) => {
1571
1808
  r.image = this.api.url + r.image + `?token=${this.api.token}`;
1572
1809
  return r;
1573
1810
  });
1574
1811
  this.cache.addAll(resp);
1575
- this.listed = true;
1576
- this.emit("all", resp || []);
1812
+ this.emit(pathedEvent("users", "r"), resp || []);
1577
1813
  return resp;
1578
1814
  });
1579
1815
  }
1580
1816
  async read(username, reload = false) {
1817
+ if (!username) throw new Error("Cannot read user, missing username");
1581
1818
  if (!reload && this.cache.get(username)) return this.cache.get(username);
1582
- return this.api.request({ url: `/api/users/${username}` }).then((resp) => {
1819
+ return this.api.request({ url: "/api/" + pathedEvent(["users", username]) }).then((resp) => {
1583
1820
  if (resp) {
1584
1821
  resp.image = this.api.url + resp.image + `?token=${this.api.token}`;
1585
1822
  this.cache.add(resp);
1586
1823
  }
1587
- this.emit("read", resp);
1824
+ this.emit(pathedEvent(["users", username], "r"), resp);
1588
1825
  return resp;
1589
1826
  });
1590
1827
  }
1591
1828
  update(user) {
1829
+ if (!user.username) throw new Error("Cannot update user, missing username");
1592
1830
  return this.api.request({
1593
- url: `/api/users/${user.username}`,
1831
+ url: `/api/` + pathedEvent(["users", user.username]),
1594
1832
  method: "PATCH",
1595
1833
  body: user
1596
1834
  }).then((resp) => {
@@ -1598,22 +1836,23 @@ ${log}`;
1598
1836
  resp.image = this.api.url + resp.image + `?token=${this.api.token}`;
1599
1837
  this.cache.add(resp);
1600
1838
  }
1601
- this.emit(resp._id ? "update" : "create", resp);
1839
+ this.emit(pathedEvent(["users", user.username], resp._id ? "u" : "c"), resp);
1602
1840
  return resp;
1603
1841
  });
1604
1842
  }
1605
1843
  uploadImage(username, file) {
1844
+ if (!username || !file) throw new Error("Cannot update user image, missing username or file");
1606
1845
  return Ft({
1607
- url: this.api.url + `/api/users/${username}/image`,
1846
+ url: this.api.url + `/api/` + pathedEvent(["users", username, "image"]),
1608
1847
  files: [file],
1609
1848
  headers: this.api.headers
1610
1849
  }).then((resp) => {
1611
- this.emit("image", username, file);
1850
+ this.emit(pathedEvent(["users", username, "image"], "u"), username, file);
1612
1851
  return resp;
1613
1852
  });
1614
1853
  }
1615
1854
  }
1616
- class Settings extends _ {
1855
+ class Settings extends PathedEventEmitter {
1617
1856
  constructor(api) {
1618
1857
  super();
1619
1858
  __publicField(this, "api");
@@ -1624,59 +1863,64 @@ ${log}`;
1624
1863
  if (!reload && !detailed && this.cache.complete) return this.cache;
1625
1864
  return this.api.request({ url: `/api/settings` + (detailed ? "?detailed" : "") }).then((resp) => {
1626
1865
  if (resp) Object.keys(resp).forEach((key) => this.cache.set(key, detailed ? resp[key].value : resp[key]));
1627
- this.emit("all", resp || []);
1866
+ this.emit(pathedEvent("settings", "r"), resp || []);
1628
1867
  return resp;
1629
1868
  });
1630
1869
  }
1631
1870
  delete(key) {
1632
- return this.api.request({ url: `/api/settings/${key}`, method: "DELETE" }).then(() => {
1871
+ if (!key) throw new Error("Cannot delete setting, missing key");
1872
+ return this.api.request({ url: `/api/` + pathedEvent(["settings", key]), method: "DELETE" }).then(() => {
1633
1873
  this.cache.delete(key);
1634
- this.emit("delete", key);
1874
+ this.emit(pathedEvent(["settings", key], "d"), key);
1635
1875
  });
1636
1876
  }
1637
1877
  read(key, reload = false) {
1878
+ if (!key) throw new Error("Cannot read setting, missing key");
1638
1879
  if (!reload && this.cache.get(key)) return this.cache.get(key);
1639
- return this.api.request({ url: `/api/settings/${key}` }).then((variable) => {
1880
+ return this.api.request({ url: `/api/` + pathedEvent(["settings", key]) }).then((variable) => {
1640
1881
  if (variable) this.cache.set(variable.key, variable.value);
1641
- this.emit("read", variable);
1882
+ this.emit(pathedEvent(["settings", key], "r"), variable);
1642
1883
  return variable;
1643
1884
  });
1644
1885
  }
1645
1886
  update(variable) {
1646
- return this.api.request({ url: `/api/settings/${variable.key}`, body: variable }).then((variable2) => {
1887
+ if (!variable.key) throw new Error("Cannot update setting, missing key");
1888
+ return this.api.request({ url: `/api/` + pathedEvent(["settings", variable.key]), body: variable }).then((variable2) => {
1647
1889
  if (variable2) this.cache.set(variable2.key, variable2.value);
1648
- this.emit("update", variable2);
1890
+ this.emit(`/api/` + pathedEvent(["settings", variable2.key], variable2._id ? "u" : "c"), variable2);
1649
1891
  return variable2;
1650
1892
  });
1651
1893
  }
1652
1894
  }
1653
- class Static extends _ {
1895
+ class Static extends PathedEventEmitter {
1654
1896
  constructor(api) {
1655
1897
  super();
1656
1898
  __publicField(this, "api");
1657
1899
  this.api = typeof api == "string" ? new Api(api) : api;
1658
1900
  }
1659
1901
  delete(path) {
1660
- return this.api.request({ url: `/api/static/${path}`, method: "DELETE" }).then(() => {
1661
- this.emit("delete", path);
1902
+ if (!path) throw new Error("Cannot delete static asset, missing path");
1903
+ return this.api.request({ url: `/api/` + pathedEvent(["static", path]), method: "DELETE" }).then(() => {
1904
+ this.emit(pathedEvent(["static", path], "d"), path);
1662
1905
  });
1663
1906
  }
1664
1907
  upload(files, path = "/") {
1908
+ if (!files) throw new Error("Cannot upload static assets, missing file");
1665
1909
  return new E(async (res, rej, prog) => {
1666
1910
  return Ft({
1667
- url: this.api.url + ("/api/static/" + path).replaceAll("//", "/"),
1911
+ url: this.api.url + "/api/" + pathedEvent(["static", path]),
1668
1912
  files: ft(files),
1669
1913
  headers: this.api.headers
1670
1914
  }).onProgress((p2) => {
1671
1915
  prog(p2);
1672
1916
  }).then((resp) => {
1673
- this.emit("upload", resp);
1917
+ this.emit(pathedEvent(["static", path], "c"), resp);
1674
1918
  res(resp);
1675
1919
  }).catch((err) => rej(err));
1676
1920
  });
1677
1921
  }
1678
1922
  }
1679
- class Momentum extends _ {
1923
+ class Momentum extends PathedEventEmitter {
1680
1924
  constructor(url, opts) {
1681
1925
  super();
1682
1926
  __publicField(this, "api");
@@ -1707,7 +1951,7 @@ ${log}`;
1707
1951
  this.data = new Data(this.api);
1708
1952
  this.email = new Email(this.api);
1709
1953
  this.groups = new Groups(this.api);
1710
- this.logger = new Logger(this.api, opts == null ? void 0 : opts.logLevel);
1954
+ this.logger = new Logger(this.api, "client", opts == null ? void 0 : opts.logLevel);
1711
1955
  if (opts == null ? void 0 : opts.stripeSecret) this.payments = new Payments(this.api, opts.stripeSecret);
1712
1956
  this.pdf = new Pdf(this.api);
1713
1957
  this.settings = new Settings(this.api);
@@ -1716,24 +1960,25 @@ ${log}`;
1716
1960
  this.storage = new Storage(this.api);
1717
1961
  this.client = new Client(this.settings);
1718
1962
  this.users = new Users(this.api);
1719
- this.api.on("*", (event, ...args) => this.emit(`Api:${event}`, ...args));
1720
- this.actions.on("*", (event, ...args) => this.emit(`Actions:${event}`, ...args));
1721
- this.auth.on("*", (event, ...args) => this.emit(`Auth:${event}`, ...args));
1722
- this.data.on("*", (event, ...args) => this.emit(`Data:${event}`, ...args));
1723
- this.email.on("*", (event, ...args) => this.emit(`Email:${event}`, ...args));
1724
- this.groups.on("*", (event, ...args) => this.emit(`Groups:${event}`, ...args));
1725
- if (this.payments) this.payments.on("*", (event, ...args) => this.emit(`Payments:${event}`, ...args));
1726
- this.pdf.on("*", (event, ...args) => this.emit(`Pdf:${event}`, ...args));
1727
- this.settings.on("*", (event, ...args) => this.emit(`Settings:${event}`, ...args));
1728
- this.static.on("*", (event, ...args) => this.emit(`Static:${event}`, ...args));
1729
- this.storage.on("*", (event, ...args) => this.emit(`Storage:${event}`, ...args));
1730
- this.users.on("*", (event, ...args) => this.emit(`Users:${event}`, ...args));
1731
- this.users.on("*", (event, ...args) => {
1732
- const u = ft(args[0]).find((u2) => {
1733
- var _a;
1734
- return (u2 == null ? void 0 : u2._id) == ((_a = this.auth.user) == null ? void 0 : _a._id);
1735
- });
1736
- if (u) this.auth.user = u;
1963
+ this.relayEvents(this.actions);
1964
+ this.relayEvents(this.ai);
1965
+ this.relayEvents(this.analytics);
1966
+ this.relayEvents(this.api);
1967
+ this.relayEvents(this.auth);
1968
+ this.relayEvents(this.client);
1969
+ this.relayEvents(this.data);
1970
+ this.relayEvents(this.email);
1971
+ this.relayEvents(this.groups);
1972
+ this.relayEvents(this.logger);
1973
+ if (this.payments) this.relayEvents(this.payments);
1974
+ this.relayEvents(this.pdf);
1975
+ this.relayEvents(this.settings);
1976
+ this.relayEvents(this.static);
1977
+ this.relayEvents(this.storage);
1978
+ this.relayEvents(this.users);
1979
+ this.users.on(`*`, () => {
1980
+ if (!this.auth.user) return;
1981
+ this.auth.user = this.users.cache.get(this.auth.user.username);
1737
1982
  });
1738
1983
  }
1739
1984
  }
@@ -1749,6 +1994,7 @@ ${log}`;
1749
1994
  exports2.Groups = Groups;
1750
1995
  exports2.Logger = Logger;
1751
1996
  exports2.Momentum = Momentum;
1997
+ exports2.PathedEventEmitter = PathedEventEmitter;
1752
1998
  exports2.Payments = Payments;
1753
1999
  exports2.Pdf = Pdf;
1754
2000
  exports2.Settings = Settings;
@@ -1757,5 +2003,10 @@ ${log}`;
1757
2003
  exports2.Storage = Storage;
1758
2004
  exports2.Totp = Totp;
1759
2005
  exports2.Users = Users;
2006
+ exports2.combinePathedEvents = combinePathedEvents;
2007
+ exports2.hasPath = hasPath;
2008
+ exports2.hasPathFatal = hasPathFatal;
2009
+ exports2.parsePathedEvent = parsePathedEvent;
2010
+ exports2.pathedEvent = pathedEvent;
1760
2011
  Object.defineProperty(exports2, Symbol.toStringTag, { value: "Module" });
1761
2012
  });