@ztimson/momentum 0.15.1 → 0.16.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/actions.d.ts CHANGED
@@ -1,7 +1,7 @@
1
- import { Meta } from './core';
2
- import { BehaviorSubject } from 'rxjs';
3
- import { TypedEmitter, XhrOptions, TypedEvents } from '@ztimson/utils';
4
1
  import { Api } from './api';
2
+ import { TypedEmitter, XhrOptions, TypedEvents } from '@ztimson/utils';
3
+ import { BehaviorSubject } from 'rxjs';
4
+ import { Meta } from './core';
5
5
 
6
6
  export type Action = Meta & {
7
7
  name: string;
package/dist/auth.d.ts CHANGED
@@ -1,7 +1,7 @@
1
- import { TypedEmitter, TypedEvents } from '@ztimson/utils';
2
- import { Meta } from './core';
3
- import { Api } from './api';
4
1
  import { BehaviorSubject } from 'rxjs';
2
+ import { Api } from './api';
3
+ import { Meta } from './core';
4
+ import { TypedEmitter, TypedEvents } from '@ztimson/utils';
5
5
 
6
6
  export type Group = Meta & {
7
7
  name: string;
package/dist/data.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- import { TypedEmitter, TypedEvents } from '@ztimson/utils';
2
- import { Meta } from './core';
3
1
  import { Api } from './api';
2
+ import { Meta } from './core';
3
+ import { TypedEmitter, TypedEvents } from '@ztimson/utils';
4
4
 
5
5
  export type DataEvents = TypedEvents & {
6
6
  DELETE: (collection: string, document: string) => any;
package/dist/email.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { TypedEmitter, TypedEvents } from '@ztimson/utils';
2
1
  import { Api } from './api';
2
+ import { TypedEmitter, TypedEvents } from '@ztimson/utils';
3
3
 
4
4
  export type MailTemplate = {
5
5
  template: string;
package/dist/groups.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- import { TypedEmitter, TypedEvents } from '@ztimson/utils';
2
- import { Group } from './auth';
3
1
  import { Api } from './api';
2
+ import { Group } from './auth';
3
+ import { TypedEmitter, TypedEvents } from '@ztimson/utils';
4
4
 
5
5
  export type GroupEvents = TypedEvents & {
6
6
  LIST: (users: Group[]) => any;
package/dist/logger.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { LOG_LEVEL } from '@ztimson/utils';
2
1
  import { Api } from './api';
2
+ import { LOG_LEVEL } from '@ztimson/utils';
3
3
 
4
4
  export type LogLevel = 'ERROR' | 'WARN' | 'INFO' | 'LOG' | 'DEBUG' | 'NONE';
5
5
  export type Log<T> = {
@@ -12,6 +12,8 @@ export type ClientLog = Log<{
12
12
  url: string;
13
13
  user: string;
14
14
  ip: string;
15
+ cores: number | 'Unknown';
16
+ mem: number | 'Unknown';
15
17
  res: [number, number];
16
18
  ua: string | {
17
19
  ua: string;
@@ -1 +1 @@
1
- {"version":3,"file":"logger.d.ts","sourceRoot":"","sources":["../src/logger.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,GAAG,EAAC,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAC,SAAS,EAAC,MAAM,gBAAgB,CAAC;AAEzC,MAAM,MAAM,QAAQ,GAAG,OAAO,GAAG,MAAM,GAAG,MAAM,GAAG,KAAK,GAAG,OAAO,GAAG,MAAM,CAAC;AAE5E,MAAM,MAAM,GAAG,CAAC,CAAC,IAAI;IACpB,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,SAAS,CAAC;IACjB,GAAG,EAAE,GAAG,EAAE,CAAC;IACX,GAAG,CAAC,EAAE,CAAC,CAAA;CACP,CAAA;AAED,MAAM,MAAM,SAAS,GAAG,GAAG,CAAC;IAC3B,GAAG,EAAE,MAAM,CAAC;IACZ,IAAI,EAAE,MAAM,CAAC;IACb,EAAE,EAAE,MAAM,CAAC;IACX,GAAG,EAAE,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACtB,EAAE,EAAE,MAAM,GAAG;QACZ,EAAE,EAAE,MAAM,CAAC;QACX,OAAO,EAAE;YAAC,IAAI,EAAE,MAAM,CAAC;YAAC,OAAO,EAAE,MAAM,CAAC;YAAC,KAAK,EAAE,MAAM,CAAA;SAAC,CAAC;QACxD,GAAG,EAAE;YAAC,YAAY,EAAE,MAAM,CAAA;SAAC,CAAC;QAC5B,MAAM,EAAE;YAAC,IAAI,CAAC,EAAE,MAAM,CAAC;YAAC,IAAI,CAAC,EAAE,MAAM,CAAA;SAAC,CAAC;QACvC,MAAM,EAAE;YAAC,IAAI,EAAE,MAAM,CAAC;YAAC,OAAO,EAAE,MAAM,CAAA;SAAC,CAAC;QACxC,EAAE,EAAE;YAAC,IAAI,EAAE,MAAM,CAAC;YAAC,OAAO,EAAE,MAAM,CAAA;SAAC,CAAC;KACpC,CAAA;CACD,CAAC,CAAC;AAEH,qBAAa,MAAM;IAClB,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAO;gBAEf,GAAG,EAAE,GAAG,GAAG,MAAM,EAAE,QAAQ,CAAC,EAAE,QAAQ,GAAG,IAAI;IASzD,OAAO,CAAC,QAAQ;IAYhB,eAAe;IAIf,eAAe;IAIf,UAAU,CAAC,MAAM,CAAC,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,SAAS,EAAE,CAAC;IAKhE,UAAU,CAAC,MAAM,CAAC,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC;IAK/D,KAAK,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE;IAIpB,GAAG,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE;IAIlB,IAAI,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE;IAInB,IAAI,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE;IAInB,KAAK,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE;CAGpB"}
1
+ {"version":3,"file":"logger.d.ts","sourceRoot":"","sources":["../src/logger.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,GAAG,EAAC,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAC,SAAS,EAAC,MAAM,gBAAgB,CAAC;AAEzC,MAAM,MAAM,QAAQ,GAAG,OAAO,GAAG,MAAM,GAAG,MAAM,GAAG,KAAK,GAAG,OAAO,GAAG,MAAM,CAAC;AAE5E,MAAM,MAAM,GAAG,CAAC,CAAC,IAAI;IACpB,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,SAAS,CAAC;IACjB,GAAG,EAAE,GAAG,EAAE,CAAC;IACX,GAAG,CAAC,EAAE,CAAC,CAAA;CACP,CAAA;AAED,MAAM,MAAM,SAAS,GAAG,GAAG,CAAC;IAC3B,GAAG,EAAE,MAAM,CAAC;IACZ,IAAI,EAAE,MAAM,CAAC;IACb,EAAE,EAAE,MAAM,CAAC;IACX,KAAK,EAAE,MAAM,GAAG,SAAS,CAAC;IAC1B,GAAG,EAAE,MAAM,GAAG,SAAS,CAAC;IACxB,GAAG,EAAE,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACtB,EAAE,EAAE,MAAM,GAAG;QACZ,EAAE,EAAE,MAAM,CAAC;QACX,OAAO,EAAE;YAAC,IAAI,EAAE,MAAM,CAAC;YAAC,OAAO,EAAE,MAAM,CAAC;YAAC,KAAK,EAAE,MAAM,CAAA;SAAC,CAAC;QACxD,GAAG,EAAE;YAAC,YAAY,EAAE,MAAM,CAAA;SAAC,CAAC;QAC5B,MAAM,EAAE;YAAC,IAAI,CAAC,EAAE,MAAM,CAAC;YAAC,IAAI,CAAC,EAAE,MAAM,CAAA;SAAC,CAAC;QACvC,MAAM,EAAE;YAAC,IAAI,EAAE,MAAM,CAAC;YAAC,OAAO,EAAE,MAAM,CAAA;SAAC,CAAC;QACxC,EAAE,EAAE;YAAC,IAAI,EAAE,MAAM,CAAC;YAAC,OAAO,EAAE,MAAM,CAAA;SAAC,CAAC;KACpC,CAAA;CACD,CAAC,CAAC;AAEH,qBAAa,MAAM;IAClB,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAO;gBAEf,GAAG,EAAE,GAAG,GAAG,MAAM,EAAE,QAAQ,CAAC,EAAE,QAAQ,GAAG,IAAI;IASzD,OAAO,CAAC,QAAQ;IAchB,eAAe;IAIf,eAAe;IAIf,UAAU,CAAC,MAAM,CAAC,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,SAAS,EAAE,CAAC;IAKhE,UAAU,CAAC,MAAM,CAAC,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC;IAK/D,KAAK,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE;IAIpB,GAAG,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE;IAIlB,IAAI,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE;IAInB,IAAI,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE;IAInB,KAAK,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE;CAGpB"}
package/dist/momentum.cjs CHANGED
@@ -1,4 +1,4 @@
1
- (function(h,p){typeof exports=="object"&&typeof module<"u"?p(exports):typeof define=="function"&&define.amd?define(["exports"],p):(h=typeof globalThis<"u"?globalThis:h||self,p(h.utils={}))})(this,function(h){"use strict";var Nt=Object.defineProperty;var Ht=(h,p,v)=>p in h?Nt(h,p,{enumerable:!0,configurable:!0,writable:!0,value:v}):h[p]=v;var a=(h,p,v)=>(Ht(h,typeof p!="symbol"?p+"":p,v),v);var p=Object.defineProperty,v=(i,e,t)=>e in i?p(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,l=(i,e,t)=>(v(i,typeof e!="symbol"?e+"":e,t),t);function At(i,e=!1){if(i==null)throw new Error("Cannot clean a NULL value");return Array.isArray(i)?i=i.filter(t=>t!=null):Object.entries(i).forEach(([t,r])=>{(e&&r===void 0||!e&&r==null)&&delete i[t]}),i}function K(i,e){const t=typeof i,r=typeof e;return t!="object"||i==null||r!="object"||e==null?t=="function"&&r=="function"?i.toString()==e.toString():i===e:Object.keys(i).length!=Object.keys(e).length?!1:Object.keys(i).every(s=>K(i[s],e[s]))}function _t(i,e){const t=document.createElement("a");t.href=i,t.download=e,document.body.appendChild(t),t.click(),document.body.removeChild(t)}class f{constructor(){l(this,"listeners",{})}static emit(e,...t){(this.listeners["*"]||[]).forEach(r=>r(e,...t)),(this.listeners[e.toString()]||[]).forEach(r=>r(...t))}static off(e,t){const r=e.toString();this.listeners[r]=(this.listeners[r]||[]).filter(s=>s===t)}static on(e,t){var r;const s=e.toString();return this.listeners[s]||(this.listeners[s]=[]),(r=this.listeners[s])==null||r.push(t),()=>this.off(e,t)}static once(e,t){return new Promise(r=>{const s=this.on(e,(...n)=>{r(n.length==1?n[0]:n),t&&t(...n),s()})})}emit(e,...t){(this.listeners["*"]||[]).forEach(r=>r(e,...t)),(this.listeners[e]||[]).forEach(r=>r(...t))}off(e,t){this.listeners[e]=(this.listeners[e]||[]).filter(r=>r===t)}on(e,t){var r;return this.listeners[e]||(this.listeners[e]=[]),(r=this.listeners[e])==null||r.push(t),()=>this.off(e,t)}once(e,t){return new Promise(r=>{const s=this.on(e,(...n)=>{r(n.length==1?n[0]:n),t&&t(...n),s()})})}}l(f,"listeners",{});const j=class L{constructor(e={}){l(this,"interceptors",{}),l(this,"headers",{}),this.opts=e,this.headers=e.headers||{},e.interceptors&&e.interceptors.forEach(t=>L.addInterceptor(t))}static addInterceptor(e){const t=Object.keys(L.interceptors).length.toString();return L.interceptors[t]=e,()=>{L.interceptors[t]=null}}addInterceptor(e){const t=Object.keys(this.interceptors).length.toString();return this.interceptors[t]=e,()=>{this.interceptors[t]=null}}async request(e={}){var t,r;if(!this.opts.url&&!e.url)throw new Error("URL needs to be set");const s=((t=e.url)!=null&&t.startsWith("http")?e.url:(this.opts.url||"")+(e.url||"")).replace(/([^:]\/)\/+/g,"$1"),n=At({"Content-Type":e.body&&!(e.body instanceof FormData)?"application/json":void 0,...L.headers,...this.headers,...e.headers});return fetch(s,{headers:n,method:e.method||(e.body?"POST":"GET"),body:(r=n["Content-Type"])!=null&&r.startsWith("application/json")&&e.body?JSON.stringify(e.body):e.body}).then(async o=>{var u,c;for(let E of[...Object.values(L.interceptors),...Object.values(this.interceptors)])await new Promise(O=>E(o,()=>O()));if(!o.ok)throw new Error(o.statusText);return!e.skipConverting&&(u=o.headers.get("Content-Type"))!=null&&u.startsWith("application/json")?await o.json():!e.skipConverting&&(c=o.headers.get("Content-Type"))!=null&&c.startsWith("text/plain")?await o.text():o})}};l(j,"interceptors",{}),l(j,"headers",{});let z=j;z.addInterceptor((i,e)=>{if(i.status==200)return e();throw i.status==400?new J(i.statusText):i.status==401?new Q(i.statusText):i.status==403?new X(i.statusText):i.status==404?new Z(i.statusText):i.status==500?new tt(i.statusText):new w(i.statusText,i.status)});class w extends Error{constructor(e,t){super(e),l(this,"_code"),t!=null&&(this._code=t)}get code(){return this._code||this.constructor.code}set code(e){this._code=e}static from(e){const t=Number(e.statusCode)??Number(e.code),r=new this(e.message||e.toString());return Object.assign(r,{stack:e.stack,...e,code:t??void 0})}static instanceof(e){return e.constructor.code!=null}toString(){return this.message||super.toString()}}l(w,"code",500);class J extends w{constructor(e="Bad Request"){super(e)}static instanceof(e){return e.constructor.code==this.code}}l(J,"code",400);class Q extends w{constructor(e="Unauthorized"){super(e)}static instanceof(e){return e.constructor.code==this.code}}l(Q,"code",401);class X extends w{constructor(e="Forbidden"){super(e)}static instanceof(e){return e.constructor.code==this.code}}l(X,"code",403);class Z extends w{constructor(e="Not Found"){super(e)}static instanceof(e){return e.constructor.code==this.code}}l(Z,"code",404);class tt extends w{constructor(e="Internal Server Error"){super(e)}static instanceof(e){return e.constructor.code==this.code}}l(tt,"code",500);const _={CLEAR:"\x1B[0m",BRIGHT:"\x1B[1m",DIM:"\x1B[2m",UNDERSCORE:"\x1B[4m",BLINK:"\x1B[5m",REVERSE:"\x1B[7m",HIDDEN:"\x1B[8m"},x={BLACK:"\x1B[30m",RED:"\x1B[31m",GREEN:"\x1B[32m",YELLOW:"\x1B[33m",BLUE:"\x1B[34m",MAGENTA:"\x1B[35m",CYAN:"\x1B[36m",LIGHT_GREY:"\x1B[37m",GREY:"\x1B[90m",LIGHT_RED:"\x1B[91m",LIGHT_GREEN:"\x1B[92m",LIGHT_YELLOW:"\x1B[93m",LIGHT_BLUE:"\x1B[94m",LIGHT_MAGENTA:"\x1B[95m",LIGHT_CYAN:"\x1B[96m",WHITE:"\x1B[97m"};var T=(i=>(i[i.ERROR=0]="ERROR",i[i.WARN=1]="WARN",i[i.INFO=2]="INFO",i[i.LOG=3]="LOG",i[i.DEBUG=4]="DEBUG",i))(T||{});l(class y extends f{constructor(e){super(),this.namespace=e}pad(e,t,r,s=!1){const n=e.toString(),o=t-n.length;if(o<=0)return n;const u=Array(~~(o/r.length)).fill(r).join("");return s?n+u:u+n}format(...e){const t=new Date;return`${`${t.getFullYear()}-${t.getMonth()+1}-${t.getDate()} ${this.pad(t.getHours().toString(),2,"0")}:${this.pad(t.getMinutes().toString(),2,"0")}:${this.pad(t.getSeconds().toString(),2,"0")}.${this.pad(t.getMilliseconds().toString(),3,"0",!0)}`}${this.namespace?` [${this.namespace}]`:""} ${e.join(" ")}`}debug(...e){if(y.LOG_LEVEL<4)return;const t=this.format(...e);y.emit(4,t),console.debug(x.LIGHT_GREY+t+_.CLEAR)}log(...e){if(y.LOG_LEVEL<3)return;const t=this.format(...e);y.emit(3,t),console.log(_.CLEAR+t)}info(...e){if(y.LOG_LEVEL<2)return;const t=this.format(...e);y.emit(2,t),console.info(x.BLUE+t+_.CLEAR)}warn(...e){if(y.LOG_LEVEL<1)return;const t=this.format(...e);y.emit(1,t),console.warn(x.YELLOW+t+_.CLEAR)}error(...e){if(y.LOG_LEVEL<0)return;const t=this.format(...e);y.emit(0,t),console.error(x.RED+t+_.CLEAR)}},"LOG_LEVEL",4);class $t extends Promise{constructor(e){super((t,r)=>e(s=>t(s),s=>r(s),s=>this.progress=s)),l(this,"listeners",[]),l(this,"_progress",0)}get progress(){return this._progress}set progress(e){e!=this._progress&&(this._progress=e,this.listeners.forEach(t=>t(e)))}onProgress(e){return this.listeners.push(e),this}}class m extends z{constructor(t=location.origin,r={}){r.url=t;super(r);a(this,"emitter",new f);a(this,"_token",null);a(this,"emit",this.emitter.emit.bind(this.emitter));a(this,"off",this.emitter.off.bind(this.emitter));a(this,"on",this.emitter.on.bind(this.emitter));a(this,"once",this.emitter.once.bind(this.emitter));this.url=t,this.opts=r}get token(){return this._token}set token(t){t!=this._token&&(this._token=t,this.headers.Authorization=`Bearer ${t}`,this.emit("TOKEN",t))}request(t){const r=super.request(t).then(s=>(this.emit("RESPONSE",s,t),s)).catch(s=>{throw this.emit("REJECTED",s,t),s});return this.emit("REQUEST",r,t),r}}var k=function(i,e){return k=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,r){t.__proto__=r}||function(t,r){for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(t[s]=r[s])},k(i,e)};function $(i,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");k(i,e);function t(){this.constructor=i}i.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}function G(i){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&i[e],r=0;if(t)return t.call(i);if(i&&typeof i.length=="number")return{next:function(){return i&&r>=i.length&&(i=void 0),{value:i&&i[r++],done:!i}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function N(i,e){var t=typeof Symbol=="function"&&i[Symbol.iterator];if(!t)return i;var r=t.call(i),s,n=[],o;try{for(;(e===void 0||e-- >0)&&!(s=r.next()).done;)n.push(s.value)}catch(u){o={error:u}}finally{try{s&&!s.done&&(t=r.return)&&t.call(r)}finally{if(o)throw o.error}}return n}function H(i,e,t){if(t||arguments.length===2)for(var r=0,s=e.length,n;r<s;r++)(n||!(r in e))&&(n||(n=Array.prototype.slice.call(e,0,r)),n[r]=e[r]);return i.concat(n||Array.prototype.slice.call(e))}typeof SuppressedError=="function"&&SuppressedError;function b(i){return typeof i=="function"}function et(i){var e=function(r){Error.call(r),r.stack=new Error().stack},t=i(e);return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}var W=et(function(i){return function(t){i(this),this.message=t?t.length+` errors occurred during unsubscription:
1
+ (function(h,p){typeof exports=="object"&&typeof module<"u"?p(exports):typeof define=="function"&&define.amd?define(["exports"],p):(h=typeof globalThis<"u"?globalThis:h||self,p(h.utils={}))})(this,function(h){"use strict";var Nt=Object.defineProperty;var Ht=(h,p,v)=>p in h?Nt(h,p,{enumerable:!0,configurable:!0,writable:!0,value:v}):h[p]=v;var a=(h,p,v)=>(Ht(h,typeof p!="symbol"?p+"":p,v),v);var p=Object.defineProperty,v=(i,e,t)=>e in i?p(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,l=(i,e,t)=>(v(i,typeof e!="symbol"?e+"":e,t),t);function At(i,e=!1){if(i==null)throw new Error("Cannot clean a NULL value");return Array.isArray(i)?i=i.filter(t=>t!=null):Object.entries(i).forEach(([t,r])=>{(e&&r===void 0||!e&&r==null)&&delete i[t]}),i}function K(i,e){const t=typeof i,r=typeof e;return t!="object"||i==null||r!="object"||e==null?t=="function"&&r=="function"?i.toString()==e.toString():i===e:Object.keys(i).length!=Object.keys(e).length?!1:Object.keys(i).every(s=>K(i[s],e[s]))}function _t(i,e){const t=document.createElement("a");t.href=i,t.download=e,document.body.appendChild(t),t.click(),document.body.removeChild(t)}class f{constructor(){l(this,"listeners",{})}static emit(e,...t){(this.listeners["*"]||[]).forEach(r=>r(e,...t)),(this.listeners[e.toString()]||[]).forEach(r=>r(...t))}static off(e,t){const r=e.toString();this.listeners[r]=(this.listeners[r]||[]).filter(s=>s===t)}static on(e,t){var r;const s=e.toString();return this.listeners[s]||(this.listeners[s]=[]),(r=this.listeners[s])==null||r.push(t),()=>this.off(e,t)}static once(e,t){return new Promise(r=>{const s=this.on(e,(...n)=>{r(n.length==1?n[0]:n),t&&t(...n),s()})})}emit(e,...t){(this.listeners["*"]||[]).forEach(r=>r(e,...t)),(this.listeners[e]||[]).forEach(r=>r(...t))}off(e,t){this.listeners[e]=(this.listeners[e]||[]).filter(r=>r===t)}on(e,t){var r;return this.listeners[e]||(this.listeners[e]=[]),(r=this.listeners[e])==null||r.push(t),()=>this.off(e,t)}once(e,t){return new Promise(r=>{const s=this.on(e,(...n)=>{r(n.length==1?n[0]:n),t&&t(...n),s()})})}}l(f,"listeners",{});const j=class L{constructor(e={}){l(this,"interceptors",{}),l(this,"headers",{}),this.opts=e,this.headers=e.headers||{},e.interceptors&&e.interceptors.forEach(t=>L.addInterceptor(t))}static addInterceptor(e){const t=Object.keys(L.interceptors).length.toString();return L.interceptors[t]=e,()=>{L.interceptors[t]=null}}addInterceptor(e){const t=Object.keys(this.interceptors).length.toString();return this.interceptors[t]=e,()=>{this.interceptors[t]=null}}async request(e={}){var t,r;if(!this.opts.url&&!e.url)throw new Error("URL needs to be set");const s=((t=e.url)!=null&&t.startsWith("http")?e.url:(this.opts.url||"")+(e.url||"")).replace(/([^:]\/)\/+/g,"$1"),n=At({"Content-Type":e.body&&!(e.body instanceof FormData)?"application/json":void 0,...L.headers,...this.headers,...e.headers});return fetch(s,{headers:n,method:e.method||(e.body?"POST":"GET"),body:(r=n["Content-Type"])!=null&&r.startsWith("application/json")&&e.body?JSON.stringify(e.body):e.body}).then(async o=>{var u,c;for(let y of[...Object.values(L.interceptors),...Object.values(this.interceptors)])await new Promise(O=>y(o,()=>O()));if(!o.ok)throw new Error(o.statusText);return!e.skipConverting&&(u=o.headers.get("Content-Type"))!=null&&u.startsWith("application/json")?await o.json():!e.skipConverting&&(c=o.headers.get("Content-Type"))!=null&&c.startsWith("text/plain")?await o.text():o})}};l(j,"interceptors",{}),l(j,"headers",{});let z=j;z.addInterceptor((i,e)=>{if(i.status==200)return e();throw i.status==400?new J(i.statusText):i.status==401?new Q(i.statusText):i.status==403?new X(i.statusText):i.status==404?new Z(i.statusText):i.status==500?new tt(i.statusText):new w(i.statusText,i.status)});class w extends Error{constructor(e,t){super(e),l(this,"_code"),t!=null&&(this._code=t)}get code(){return this._code||this.constructor.code}set code(e){this._code=e}static from(e){const t=Number(e.statusCode)??Number(e.code),r=new this(e.message||e.toString());return Object.assign(r,{stack:e.stack,...e,code:t??void 0})}static instanceof(e){return e.constructor.code!=null}toString(){return this.message||super.toString()}}l(w,"code",500);class J extends w{constructor(e="Bad Request"){super(e)}static instanceof(e){return e.constructor.code==this.code}}l(J,"code",400);class Q extends w{constructor(e="Unauthorized"){super(e)}static instanceof(e){return e.constructor.code==this.code}}l(Q,"code",401);class X extends w{constructor(e="Forbidden"){super(e)}static instanceof(e){return e.constructor.code==this.code}}l(X,"code",403);class Z extends w{constructor(e="Not Found"){super(e)}static instanceof(e){return e.constructor.code==this.code}}l(Z,"code",404);class tt extends w{constructor(e="Internal Server Error"){super(e)}static instanceof(e){return e.constructor.code==this.code}}l(tt,"code",500);const _={CLEAR:"\x1B[0m",BRIGHT:"\x1B[1m",DIM:"\x1B[2m",UNDERSCORE:"\x1B[4m",BLINK:"\x1B[5m",REVERSE:"\x1B[7m",HIDDEN:"\x1B[8m"},x={BLACK:"\x1B[30m",RED:"\x1B[31m",GREEN:"\x1B[32m",YELLOW:"\x1B[33m",BLUE:"\x1B[34m",MAGENTA:"\x1B[35m",CYAN:"\x1B[36m",LIGHT_GREY:"\x1B[37m",GREY:"\x1B[90m",LIGHT_RED:"\x1B[91m",LIGHT_GREEN:"\x1B[92m",LIGHT_YELLOW:"\x1B[93m",LIGHT_BLUE:"\x1B[94m",LIGHT_MAGENTA:"\x1B[95m",LIGHT_CYAN:"\x1B[96m",WHITE:"\x1B[97m"};var T=(i=>(i[i.ERROR=0]="ERROR",i[i.WARN=1]="WARN",i[i.INFO=2]="INFO",i[i.LOG=3]="LOG",i[i.DEBUG=4]="DEBUG",i))(T||{});l(class E extends f{constructor(e){super(),this.namespace=e}pad(e,t,r,s=!1){const n=e.toString(),o=t-n.length;if(o<=0)return n;const u=Array(~~(o/r.length)).fill(r).join("");return s?n+u:u+n}format(...e){const t=new Date;return`${`${t.getFullYear()}-${t.getMonth()+1}-${t.getDate()} ${this.pad(t.getHours().toString(),2,"0")}:${this.pad(t.getMinutes().toString(),2,"0")}:${this.pad(t.getSeconds().toString(),2,"0")}.${this.pad(t.getMilliseconds().toString(),3,"0",!0)}`}${this.namespace?` [${this.namespace}]`:""} ${e.join(" ")}`}debug(...e){if(E.LOG_LEVEL<4)return;const t=this.format(...e);E.emit(4,t),console.debug(x.LIGHT_GREY+t+_.CLEAR)}log(...e){if(E.LOG_LEVEL<3)return;const t=this.format(...e);E.emit(3,t),console.log(_.CLEAR+t)}info(...e){if(E.LOG_LEVEL<2)return;const t=this.format(...e);E.emit(2,t),console.info(x.BLUE+t+_.CLEAR)}warn(...e){if(E.LOG_LEVEL<1)return;const t=this.format(...e);E.emit(1,t),console.warn(x.YELLOW+t+_.CLEAR)}error(...e){if(E.LOG_LEVEL<0)return;const t=this.format(...e);E.emit(0,t),console.error(x.RED+t+_.CLEAR)}},"LOG_LEVEL",4);class $t extends Promise{constructor(e){super((t,r)=>e(s=>t(s),s=>r(s),s=>this.progress=s)),l(this,"listeners",[]),l(this,"_progress",0)}get progress(){return this._progress}set progress(e){e!=this._progress&&(this._progress=e,this.listeners.forEach(t=>t(e)))}onProgress(e){return this.listeners.push(e),this}}class m extends z{constructor(t=location.origin,r={}){r.url=t;super(r);a(this,"emitter",new f);a(this,"_token",null);a(this,"emit",this.emitter.emit.bind(this.emitter));a(this,"off",this.emitter.off.bind(this.emitter));a(this,"on",this.emitter.on.bind(this.emitter));a(this,"once",this.emitter.once.bind(this.emitter));this.url=t,this.opts=r}get token(){return this._token}set token(t){t!=this._token&&(this._token=t,this.headers.Authorization=`Bearer ${t}`,this.emit("TOKEN",t))}request(t){const r=super.request(t).then(s=>(this.emit("RESPONSE",s,t),s)).catch(s=>{throw this.emit("REJECTED",s,t),s});return this.emit("REQUEST",r,t),r}}var k=function(i,e){return k=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,r){t.__proto__=r}||function(t,r){for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(t[s]=r[s])},k(i,e)};function $(i,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");k(i,e);function t(){this.constructor=i}i.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}function G(i){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&i[e],r=0;if(t)return t.call(i);if(i&&typeof i.length=="number")return{next:function(){return i&&r>=i.length&&(i=void 0),{value:i&&i[r++],done:!i}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function N(i,e){var t=typeof Symbol=="function"&&i[Symbol.iterator];if(!t)return i;var r=t.call(i),s,n=[],o;try{for(;(e===void 0||e-- >0)&&!(s=r.next()).done;)n.push(s.value)}catch(u){o={error:u}}finally{try{s&&!s.done&&(t=r.return)&&t.call(r)}finally{if(o)throw o.error}}return n}function H(i,e,t){if(t||arguments.length===2)for(var r=0,s=e.length,n;r<s;r++)(n||!(r in e))&&(n||(n=Array.prototype.slice.call(e,0,r)),n[r]=e[r]);return i.concat(n||Array.prototype.slice.call(e))}typeof SuppressedError=="function"&&SuppressedError;function b(i){return typeof i=="function"}function et(i){var e=function(r){Error.call(r),r.stack=new Error().stack},t=i(e);return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}var M=et(function(i){return function(t){i(this),this.message=t?t.length+` errors occurred during unsubscription:
2
2
  `+t.map(function(r,s){return s+1+") "+r.toString()}).join(`
3
- `):"",this.name="UnsubscriptionError",this.errors=t}});function M(i,e){if(i){var t=i.indexOf(e);0<=t&&i.splice(t,1)}}var D=function(){function i(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return i.prototype.unsubscribe=function(){var e,t,r,s,n;if(!this.closed){this.closed=!0;var o=this._parentage;if(o)if(this._parentage=null,Array.isArray(o))try{for(var u=G(o),c=u.next();!c.done;c=u.next()){var E=c.value;E.remove(this)}}catch(d){e={error:d}}finally{try{c&&!c.done&&(t=u.return)&&t.call(u)}finally{if(e)throw e.error}}else o.remove(this);var O=this.initialTeardown;if(b(O))try{O()}catch(d){n=d instanceof W?d.errors:[d]}var R=this._finalizers;if(R){this._finalizers=null;try{for(var S=G(R),g=S.next();!g.done;g=S.next()){var C=g.value;try{st(C)}catch(d){n=n??[],d instanceof W?n=H(H([],N(n)),N(d.errors)):n.push(d)}}}catch(d){r={error:d}}finally{try{g&&!g.done&&(s=S.return)&&s.call(S)}finally{if(r)throw r.error}}}if(n)throw new W(n)}},i.prototype.add=function(e){var t;if(e&&e!==this)if(this.closed)st(e);else{if(e instanceof i){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=(t=this._finalizers)!==null&&t!==void 0?t:[]).push(e)}},i.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},i.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},i.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&M(t,e)},i.prototype.remove=function(e){var t=this._finalizers;t&&M(t,e),e instanceof i&&e._removeParent(this)},i.EMPTY=function(){var e=new i;return e.closed=!0,e}(),i}(),rt=D.EMPTY;function it(i){return i instanceof D||i&&"closed"in i&&b(i.remove)&&b(i.add)&&b(i.unsubscribe)}function st(i){b(i)?i():i.unsubscribe()}var nt={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1},ot={setTimeout:function(i,e){for(var t=[],r=2;r<arguments.length;r++)t[r-2]=arguments[r];return setTimeout.apply(void 0,H([i,e],N(t)))},clearTimeout:function(i){var e=ot.delegate;return((e==null?void 0:e.clearTimeout)||clearTimeout)(i)},delegate:void 0};function Rt(i){ot.setTimeout(function(){throw i})}function ut(){}function P(i){i()}var at=function(i){$(e,i);function e(t){var r=i.call(this)||this;return r.isStopped=!1,t?(r.destination=t,it(t)&&t.add(r)):r.destination=It,r}return e.create=function(t,r,s){return new Y(t,r,s)},e.prototype.next=function(t){this.isStopped||this._next(t)},e.prototype.error=function(t){this.isStopped||(this.isStopped=!0,this._error(t))},e.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},e.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,i.prototype.unsubscribe.call(this),this.destination=null)},e.prototype._next=function(t){this.destination.next(t)},e.prototype._error=function(t){try{this.destination.error(t)}finally{this.unsubscribe()}},e.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},e}(D),xt=Function.prototype.bind;function F(i,e){return xt.call(i,e)}var Dt=function(){function i(e){this.partialObserver=e}return i.prototype.next=function(e){var t=this.partialObserver;if(t.next)try{t.next(e)}catch(r){I(r)}},i.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(r){I(r)}else I(e)},i.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(t){I(t)}},i}(),Y=function(i){$(e,i);function e(t,r,s){var n=i.call(this)||this,o;if(b(t)||!t)o={next:t??void 0,error:r??void 0,complete:s??void 0};else{var u;n&&nt.useDeprecatedNextContext?(u=Object.create(t),u.unsubscribe=function(){return n.unsubscribe()},o={next:t.next&&F(t.next,u),error:t.error&&F(t.error,u),complete:t.complete&&F(t.complete,u)}):o=t}return n.destination=new Dt(o),n}return e}(at);function I(i){Rt(i)}function Pt(i){throw i}var It={closed:!0,next:ut,error:Pt,complete:ut},Ut=function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"}();function qt(i){return i}function Bt(i){return i.length===0?qt:i.length===1?i[0]:function(t){return i.reduce(function(r,s){return s(r)},t)}}var ct=function(){function i(e){e&&(this._subscribe=e)}return i.prototype.lift=function(e){var t=new i;return t.source=this,t.operator=e,t},i.prototype.subscribe=function(e,t,r){var s=this,n=jt(e)?e:new Y(e,t,r);return P(function(){var o=s,u=o.operator,c=o.source;n.add(u?u.call(n,c):c?s._subscribe(n):s._trySubscribe(n))}),n},i.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){e.error(t)}},i.prototype.forEach=function(e,t){var r=this;return t=ht(t),new t(function(s,n){var o=new Y({next:function(u){try{e(u)}catch(c){n(c),o.unsubscribe()}},error:n,complete:s});r.subscribe(o)})},i.prototype._subscribe=function(e){var t;return(t=this.source)===null||t===void 0?void 0:t.subscribe(e)},i.prototype[Ut]=function(){return this},i.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Bt(e)(this)},i.prototype.toPromise=function(e){var t=this;return e=ht(e),new e(function(r,s){var n;t.subscribe(function(o){return n=o},function(o){return s(o)},function(){return r(n)})})},i.create=function(e){return new i(e)},i}();function ht(i){var e;return(e=i??nt.Promise)!==null&&e!==void 0?e:Promise}function Ct(i){return i&&b(i.next)&&b(i.error)&&b(i.complete)}function jt(i){return i&&i instanceof at||Ct(i)&&it(i)}var kt=et(function(i){return function(){i(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),lt=function(i){$(e,i);function e(){var t=i.call(this)||this;return t.closed=!1,t.currentObservers=null,t.observers=[],t.isStopped=!1,t.hasError=!1,t.thrownError=null,t}return e.prototype.lift=function(t){var r=new dt(this,this);return r.operator=t,r},e.prototype._throwIfClosed=function(){if(this.closed)throw new kt},e.prototype.next=function(t){var r=this;P(function(){var s,n;if(r._throwIfClosed(),!r.isStopped){r.currentObservers||(r.currentObservers=Array.from(r.observers));try{for(var o=G(r.currentObservers),u=o.next();!u.done;u=o.next()){var c=u.value;c.next(t)}}catch(E){s={error:E}}finally{try{u&&!u.done&&(n=o.return)&&n.call(o)}finally{if(s)throw s.error}}}})},e.prototype.error=function(t){var r=this;P(function(){if(r._throwIfClosed(),!r.isStopped){r.hasError=r.isStopped=!0,r.thrownError=t;for(var s=r.observers;s.length;)s.shift().error(t)}})},e.prototype.complete=function(){var t=this;P(function(){if(t._throwIfClosed(),!t.isStopped){t.isStopped=!0;for(var r=t.observers;r.length;)r.shift().complete()}})},e.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(e.prototype,"observed",{get:function(){var t;return((t=this.observers)===null||t===void 0?void 0:t.length)>0},enumerable:!1,configurable:!0}),e.prototype._trySubscribe=function(t){return this._throwIfClosed(),i.prototype._trySubscribe.call(this,t)},e.prototype._subscribe=function(t){return this._throwIfClosed(),this._checkFinalizedStatuses(t),this._innerSubscribe(t)},e.prototype._innerSubscribe=function(t){var r=this,s=this,n=s.hasError,o=s.isStopped,u=s.observers;return n||o?rt:(this.currentObservers=null,u.push(t),new D(function(){r.currentObservers=null,M(u,t)}))},e.prototype._checkFinalizedStatuses=function(t){var r=this,s=r.hasError,n=r.thrownError,o=r.isStopped;s?t.error(n):o&&t.complete()},e.prototype.asObservable=function(){var t=new ct;return t.source=this,t},e.create=function(t,r){return new dt(t,r)},e}(ct),dt=function(i){$(e,i);function e(t,r){var s=i.call(this)||this;return s.destination=t,s.source=r,s}return e.prototype.next=function(t){var r,s;(s=(r=this.destination)===null||r===void 0?void 0:r.next)===null||s===void 0||s.call(r,t)},e.prototype.error=function(t){var r,s;(s=(r=this.destination)===null||r===void 0?void 0:r.error)===null||s===void 0||s.call(r,t)},e.prototype.complete=function(){var t,r;(r=(t=this.destination)===null||t===void 0?void 0:t.complete)===null||r===void 0||r.call(t)},e.prototype._subscribe=function(t){var r,s;return(s=(r=this.source)===null||r===void 0?void 0:r.subscribe(t))!==null&&s!==void 0?s:rt},e}(lt),U=function(i){$(e,i);function e(t){var r=i.call(this)||this;return r._value=t,r}return Object.defineProperty(e.prototype,"value",{get:function(){return this.getValue()},enumerable:!1,configurable:!0}),e.prototype._subscribe=function(t){var r=i.prototype._subscribe.call(this,t);return!r.closed&&t.next(this._value),r},e.prototype.getValue=function(){var t=this,r=t.hasError,s=t.thrownError,n=t._value;if(r)throw s;return this._throwIfClosed(),n},e.prototype.next=function(t){i.prototype.next.call(this,this._value=t)},e}(lt),pt=(i=>(i[i.DISABLED=0]="DISABLED",i[i.CRON=1]="CRON",i[i.EVENT=2]="EVENT",i[i.GET=3]="GET",i[i.POST=4]="POST",i[i.PATCH=5]="PATCH",i[i.PUT=6]="PUT",i[i.DELETE=7]="DELETE",i))(pt||{});class ft extends f{constructor(t){super();a(this,"api");a(this,"$cache",new U([]));this.api=typeof t=="string"?new m(t):t}get cache(){return this.$cache.value}set cache(t){this.$cache.next(t)}delete(t){return this.api.request({url:`/api/actions/${t}`,method:"DELETE"}).then(()=>{this.cache=this.cache.filter(r=>r._id!=t),this.emit("DELETE",t)})}list(){return this.api.request({url:"/api/actions"}).then(t=>(this.cache=t,this.emit("LIST",t),t))}read(t,r=!1){const s=this.cache.find(n=>n._id==t);return!r&&s?Promise.resolve(s):this.api.request({url:`/api/actions/${t}`}).then(n=>(n&&(this.cache=this.cache.filter(o=>o._id!=t).concat([n])),this.emit("READ",n),n))}run(t,r={}){return this.api.request({url:("/api/actions/run/"+t).replaceAll("//","/"),...r})}runById(t,r={}){const s=typeof t=="string"?t:t._id;return this.api.request({url:"/api/actions/run-by-id/"+s,...r})}update(t){return this.api.request({url:`/api/actions${t._id?`/${t._id}`:""}`,method:"POST",body:t}).then(r=>(r&&(this.cache=this.cache.filter(s=>s._id!=r._id).concat([r])),this.emit("UPDATE",r),r))}}class mt extends f{constructor(t,r){var s;super();a(this,"api");a(this,"storageKey");a(this,"$user",new U(void 0));if(this.opts=r,this.api=typeof t=="string"?new m(t):t,(s=this.opts)!=null&&s.loginUi||(this.opts={...this.opts,loginUi:this.api.url+"/ui/login"}),this.storageKey=`momentum:${new URL(this.api.url).host}`,this.api.on("TOKEN",n=>{var o;(o=this.opts)!=null&&o.persist&&(n?localStorage.setItem(this.storageKey,n):localStorage.removeItem(this.storageKey)),n?this.whoAmI(n,!0):this.user=null}),r!=null&&r.persist){const n=localStorage.getItem(this.storageKey);n?this.api.token=n:this.user=null}else this.user=null}get user(){return this.$user.value}set user(t){if(!K(this.user,t)){const r=t||null;this.$user.next(r),this.emit("USER",r)}}knownHost(t=location.origin){return t.startsWith("/")?Promise.resolve():this.api.request({url:`/api/auth/known-host?host=${encodeURI(new URL(t).origin)}`})}login(t,r){return this.api.request({url:"/api/auth/login",headers:{Authorization:void 0},body:{username:t,password:r}}).then(async s=>(this.api.token=s.token,await this.once("USER")))}loginRedirect(t=location.origin){return new Promise((r,s)=>{var o;const n=window.open(encodeURI(`${(o=this.opts)==null?void 0:o.loginUi}?redirect=postmessage&host=${t}`),"_blank");if(!n)return s("Unable to open login");n.addEventListener("message",u=>{var c;if(!((c=u==null?void 0:u.data)!=null&&c.token))return s("Unknown response from login");this.api.token=u.data.token,r(u.data.token),n.close()})})}logout(){this.api.token=null,this.user=null,this.emit("LOGOUT")}async register(t){const r=await this.api.request({url:"/api/auth/register",body:{...t}});return this.emit("REGISTER",t),r}async reset(t,r){await this.api.request({url:"/api/auth/reset",headers:{Authorization:r?`Bearer ${r}`:void 0},body:{email:r?void 0:t,password:r?t:void 0}}),this.emit(r?"RESET_COMPLETE":"RESET_REQUEST",r||t)}async whoAmI(t,r=!1){t||(t=this.api.token);const s=await this.api.request({url:"/api/auth/whoami",headers:t?{Authorization:`Bearer ${t}`}:void 0});return r&&(this.api.token=t,this.user=(s==null?void 0:s.user)||null,s&&this.emit("LOGIN",s.user)),s}}class Et extends f{constructor(t){super();a(this,"api");this.api=typeof t=="string"?new m(t):t}delete(t,r){return this.api.request({url:`/api/data/${t}/${r}`,method:"DELETE"}).then(()=>this.emit("DELETE",t,r))}get(t,r){return this.api.request({url:`/api/data/${t}${r?`/${r}`:""}`}).then(s=>(this.emit("GET",t,s),s))}raw(t,r,s,n){return this.api.request({url:`/api/data/${t}`,body:{operand:r,query:s,options:n}}).then(o=>(this.emit("RAW",t,o),o))}set(t,r,s=!1){return this.api.request({url:`/api/data/${t}/${r._id||""}`,method:s?"PATCH":"POST",body:r}).then(n=>(this.emit("SET",t,r),n))}}class yt extends f{constructor(t){super();a(this,"api");this.api=typeof t=="string"?new m(t):t}send(t){let r="/api/email/send";return typeof t.body=="object"&&(r+=`/${t.body.template}`),this.api.request({url:r,body:t}).then(s=>(this.emit("SENT",t),s))}}class gt extends f{constructor(t){super();a(this,"api");this.api=typeof t=="string"?new m(t):t}create(t){return this.api.request({url:`/api/groups/${t.name}`,method:"POST",body:t}).then(r=>(this.emit("CREATE",r),r))}list(){return this.api.request({url:"/api/groups"}).then(t=>(this.emit("LIST",t),t))}read(t){return this.api.request({url:`/api/groups/${t}`}).then(r=>(this.emit("READ",r),r))}update(t){return this.api.request({url:`/api/groups/${t.name}`,method:"PATCH",body:t}).then(r=>(this.emit("UPDATE",r),r))}delete(t){return this.api.request({url:`/api/groups/${t}`,method:"DELETE"}).then(()=>this.emit("DELETE",t))}}class bt{constructor(e,t){a(this,"api");this.api=typeof e=="string"?new m(e):e,t!=null&&t!="NONE"&&(window.addEventListener("error",r=>this.error(r.error.stack)),window.addEventListener("unhandledrejection",async r=>this.error(r.reason.stack)))}buildLog(e,t){return{time:new Date().getTime(),level:e,log:t,ctx:{url:location.href,res:[window.innerWidth,window.innerHeight]}}}clearClientLogs(){return this.api.request({url:"/api/logs/client",method:"DELETE"})}clearServerLogs(){return this.api.request({url:"/api/logs/server",method:"DELETE"})}clientLogs(e,t){const r=[e?`length=${e}`:void 0,t?`page=${t}`:void 0].filter(s=>!!s).join("&");return this.api.request({url:`/api/logs/client${r?`?${r}`:""}`})}serverLogs(e,t){const r=[e?`length=${e}`:void 0,t?`page=${t}`:void 0].filter(s=>!!s).join("&");return this.api.request({url:`/api/logs/server${r?`?${r}`:""}`})}debug(...e){return this.api.request({url:"/api/logs/client",body:this.buildLog(T.DEBUG,e)}).catch(()=>{})}log(...e){return this.api.request({url:"/api/logs/client",body:this.buildLog(T.LOG,e)}).catch(()=>{})}info(...e){return this.api.request({url:"/api/logs/client",body:this.buildLog(T.INFO,e)}).catch(()=>{})}warn(...e){return this.api.request({url:"/api/logs/client",body:this.buildLog(T.WARN,e)}).catch(()=>{})}error(...e){return this.api.request({url:"/api/logs/client",body:this.buildLog(T.ERROR,e)}).catch(()=>{})}}const B=class B{constructor(e){a(this,"api");a(this,"url");a(this,"connection");a(this,"open",!1);this.api=typeof e=="string"?new m(e):e,this.url=this.api.url.replace("http","ws"),this.api.on("TOKEN",()=>this.connect()),this.api.token||this.connect()}close(){console.debug("Disconnected from Momentum"),this.open=!1,this.connection.close()}connect(e=3){var r;((r=this.connection)==null?void 0:r.readyState)<2&&this.connection.close(),this.connection=new WebSocket(this.url+(this.api.token?`?token=${this.api.token}`:""));const t=setTimeout(()=>{this.open||(this.connection.close(),console.error("Momentum connection timeout"),e>0&&this.connect(e-1))},B.timeout);this.connection.onclose=()=>this.open=!1,this.connection.onmessage=this.handle,this.connection.onopen=()=>{this.open=!0,clearTimeout(t),console.debug("Connected to Momentum")}}handle(...e){console.log(e)}send(e,t){this.connection.send(JSON.stringify({token:this.api.token,channel:e,payload:t}))}};a(B,"timeout",1e4);let q=B;class vt extends f{constructor(t){super();a(this,"api");this.api=typeof t=="string"?new m(t):t}delete(t){const r=(t.startsWith("/api/storage/")?t:"/api/storage/"+t).replaceAll("//","/");return this.api.request({url:r,method:"DELETE"}).then(()=>{this.emit("DELETE",r)})}list(t){const r=(t.startsWith("/api/storage/")?t:"/api/storage/"+t).replaceAll("//","/");return this.api.request({url:r+"?list"}).then(s=>(this.emit("LIST",t,s),s))}open(t,r="_blank"){const s=(t.startsWith("/api/storage/")?t:"/api/storage/"+t).replaceAll(/\/{2,}/g,"/"),n=`${this.api.url}${s}${this.api.token?`?token=${this.api.token}`:""}`;return r?(this.emit("OPEN",t),window.open(n,r)):n}mkdir(t){const r=(t.startsWith("/api/storage/")?t:"/api/storage/"+t).replaceAll(/\/{2,}/g,"/");return this.api.request({url:r+"?directory",method:"POST"})}download(t,r={}){return new $t((s,n,o)=>{const u=("/api/storage/"+t).replaceAll("//","/");this.api.request({...r,url:u,skipConverting:!0}).then(c=>{var d;if(!c.ok)return n(c.statusText);const E=c.headers.get("Content-Length"),O=E?parseInt(E,10):0;let R=[],S=0;const g=(d=c.body)==null?void 0:d.getReader(),C=Tt=>{if(Tt.done){o(1);const A=new Blob(R),V=r.downloadAs||new URL(c.url).pathname.split("/").pop(),Ot=URL.createObjectURL(A);_t(Ot,V.includes(".")?V:V+".zip"),URL.revokeObjectURL(Ot),this.emit("DOWNLOAD",t,A),s(A)}else{const A=Tt.value;R.push(A),S+=A.length,o(S/O),g.read().then(C)}};g==null||g.read().then(C)})})}async upload(t,r=""){if(t||(t=await new Promise(u=>{const c=document.createElement("input");c.type="file",c.accept=(r==null?void 0:r.accept)||"*",c.style.display="none",c.multiple=!!(r!=null&&r.multiple),c.onblur=c.onchange=async()=>{u(Array.from(c.files)),c.remove()},document.body.appendChild(c),c.click()})),!t||Array.isArray(t)&&!t.length)return[];const n=new FormData,o=("/api/storage/"+(typeof r=="string"?r:r==null?void 0:r.path)).replaceAll("//","/");return(Array.isArray(t)?t:[t]).forEach(u=>n.append("file",u)),this.api.request({url:o,body:n}).then(u=>(this.emit("UPLOAD",u),u))}}class wt extends f{constructor(t){super();a(this,"api");a(this,"listed",!1);a(this,"$cache",new U([]));this.api=typeof t=="string"?new m(t):t}get cache(){return this.$cache.value}set cache(t){this.$cache.next(t)}delete(t){return this.api.request({url:`/api/users/${t}`,method:"DELETE"}).then(()=>{this.cache=this.cache.filter(r=>r.username!=t),this.emit("DELETE",t)})}list(t=!1){return!t&&this.listed?Promise.resolve(this.cache):this.api.request({url:"/api/users"}).then(r=>(this.cache=r,this.listed=!0,this.emit("LIST",r),r))}read(t,r=!1){if(!r){const s=this.cache.find(n=>n.username==t);if(s)return Promise.resolve(s)}return this.api.request({url:`/api/users/${t}`}).then(s=>(s&&(this.cache={...this.cache,[s.username]:s}),this.emit("READ",s),s))}update(t){return this.api.request({url:`/api/users/${t.username}`,method:"PATCH",body:t}).then(r=>(r&&(this.cache=this.cache.filter(s=>s.username!=t.username).concat([r])),this.emit("UPDATE",r),r))}}class St extends f{constructor(t){super();a(this,"api");a(this,"$cache",new U({}));this.api=typeof t=="string"?new m(t):t}get cache(){return this.$cache.value}set cache(t){this.$cache.next(t)}list(t=!1){return this.api.request({url:"/api/settings"+(t?"?detailed":"")}).then(r=>(this.cache=t?Object.values(r).reduce((s,n)=>({...s,[n.key]:n.value}),{}):r,this.emit("LIST",r),r))}delete(t){return this.api.request({url:`/api/settings/${t}`,method:"DELETE"}).then(()=>{this.cache={...this.cache,[t]:void 0},this.emit("DELETE",t)})}read(t,r=!1){return!r&&this.cache[t]?Promise.resolve(this.cache[t]):this.api.request({url:`/api/settings/${t}`}).then(s=>(s&&(this.cache={...this.cache,[s.key]:s}),this.emit("READ",s),s))}update(t){return this.api.request({url:`/api/settings/${t.key}`,body:t}).then(r=>(r&&(this.cache={...this.cache,[r.key]:r.value}),this.emit("UPDATE",r),r))}}class Lt extends f{constructor(t){super();a(this,"api");this.api=typeof t=="string"?new m(t):t}delete(t){return this.api.request({url:`/api/static/${t}`,method:"DELETE"}).then(()=>{this.emit("DELETE",t)})}list(t){const r=("/api/static/"+t).replaceAll("//","/");return this.api.request({url:r}).then(s=>(this.emit("LIST",t,s),s))}upload(t,r="/"){const s=new FormData;return(Array.isArray(t)?t:[t]).forEach(n=>s.append("file",n)),this.api.request({url:"/api/static"+r,body:s}).then(n=>(this.emit("UPLOAD",n),n))}}class Gt extends f{constructor(t,r){super();a(this,"api");a(this,"actions");a(this,"auth");a(this,"data");a(this,"email");a(this,"groups");a(this,"logger");a(this,"settings");a(this,"socket");a(this,"static");a(this,"storage");a(this,"users");this.api=new m(t,r==null?void 0:r.api),this.actions=new ft(this.api),this.auth=new mt(this.api,{persist:(r==null?void 0:r.persist)??!0,loginUi:r==null?void 0:r.loginUi}),this.data=new Et(this.api),this.email=new yt(this.api),this.groups=new gt(this.api),this.logger=new bt(this.api,r==null?void 0:r.logLevel),this.settings=new St(this.api),this.static=new Lt(this.api),this.storage=new vt(this.api),this.users=new wt(this.api),r!=null&&r.socket&&(this.socket=new q(this.api)),this.api.on("*",(s,...n)=>this.emit(`API::${s}`,...n)),this.actions.on("*",(s,...n)=>this.emit(`ACTIONS::${s}`,...n)),this.auth.on("*",(s,...n)=>this.emit(`AUTH::${s}`,...n)),this.data.on("*",(s,...n)=>this.emit(`DATA::${s}`,...n)),this.email.on("*",(s,...n)=>this.emit(`EMAIL::${s}`,...n)),this.groups.on("*",(s,...n)=>this.emit(`GROUPS::${s}`,...n)),this.settings.on("*",(s,...n)=>this.emit(`SETTINGS::${s}`,...n)),this.static.on("*",(s,...n)=>this.emit(`STATIC::${s}`,...n)),this.storage.on("*",(s,...n)=>this.emit(`STORAGE::${s}`,...n)),this.users.on("*",(s,...n)=>this.emit(`USERS::${s}`,...n)),this.users.on("*",(s,...n)=>{var o;if(Array.isArray(n[0])){const u=n[0].find(c=>{var E;return c._id==((E=this.auth.user)==null?void 0:E._id)});u&&(this.auth.user=u)}else n[0]._id==((o=this.auth.user)==null?void 0:o._id)&&(this.auth.user=n[0])})}}h.ActionType=pt,h.Actions=ft,h.Api=m,h.Auth=mt,h.Data=Et,h.Email=yt,h.Groups=gt,h.Logger=bt,h.Momentum=Gt,h.Settings=St,h.Socket=q,h.Static=Lt,h.Storage=vt,h.Users=wt,Object.defineProperty(h,Symbol.toStringTag,{value:"Module"})});
3
+ `):"",this.name="UnsubscriptionError",this.errors=t}});function W(i,e){if(i){var t=i.indexOf(e);0<=t&&i.splice(t,1)}}var D=function(){function i(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return i.prototype.unsubscribe=function(){var e,t,r,s,n;if(!this.closed){this.closed=!0;var o=this._parentage;if(o)if(this._parentage=null,Array.isArray(o))try{for(var u=G(o),c=u.next();!c.done;c=u.next()){var y=c.value;y.remove(this)}}catch(d){e={error:d}}finally{try{c&&!c.done&&(t=u.return)&&t.call(u)}finally{if(e)throw e.error}}else o.remove(this);var O=this.initialTeardown;if(b(O))try{O()}catch(d){n=d instanceof M?d.errors:[d]}var R=this._finalizers;if(R){this._finalizers=null;try{for(var S=G(R),g=S.next();!g.done;g=S.next()){var B=g.value;try{st(B)}catch(d){n=n??[],d instanceof M?n=H(H([],N(n)),N(d.errors)):n.push(d)}}}catch(d){r={error:d}}finally{try{g&&!g.done&&(s=S.return)&&s.call(S)}finally{if(r)throw r.error}}}if(n)throw new M(n)}},i.prototype.add=function(e){var t;if(e&&e!==this)if(this.closed)st(e);else{if(e instanceof i){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=(t=this._finalizers)!==null&&t!==void 0?t:[]).push(e)}},i.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},i.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},i.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&W(t,e)},i.prototype.remove=function(e){var t=this._finalizers;t&&W(t,e),e instanceof i&&e._removeParent(this)},i.EMPTY=function(){var e=new i;return e.closed=!0,e}(),i}(),rt=D.EMPTY;function it(i){return i instanceof D||i&&"closed"in i&&b(i.remove)&&b(i.add)&&b(i.unsubscribe)}function st(i){b(i)?i():i.unsubscribe()}var nt={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1},ot={setTimeout:function(i,e){for(var t=[],r=2;r<arguments.length;r++)t[r-2]=arguments[r];return setTimeout.apply(void 0,H([i,e],N(t)))},clearTimeout:function(i){var e=ot.delegate;return((e==null?void 0:e.clearTimeout)||clearTimeout)(i)},delegate:void 0};function Rt(i){ot.setTimeout(function(){throw i})}function ut(){}function P(i){i()}var at=function(i){$(e,i);function e(t){var r=i.call(this)||this;return r.isStopped=!1,t?(r.destination=t,it(t)&&t.add(r)):r.destination=It,r}return e.create=function(t,r,s){return new Y(t,r,s)},e.prototype.next=function(t){this.isStopped||this._next(t)},e.prototype.error=function(t){this.isStopped||(this.isStopped=!0,this._error(t))},e.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},e.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,i.prototype.unsubscribe.call(this),this.destination=null)},e.prototype._next=function(t){this.destination.next(t)},e.prototype._error=function(t){try{this.destination.error(t)}finally{this.unsubscribe()}},e.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},e}(D),xt=Function.prototype.bind;function F(i,e){return xt.call(i,e)}var Dt=function(){function i(e){this.partialObserver=e}return i.prototype.next=function(e){var t=this.partialObserver;if(t.next)try{t.next(e)}catch(r){I(r)}},i.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(r){I(r)}else I(e)},i.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(t){I(t)}},i}(),Y=function(i){$(e,i);function e(t,r,s){var n=i.call(this)||this,o;if(b(t)||!t)o={next:t??void 0,error:r??void 0,complete:s??void 0};else{var u;n&&nt.useDeprecatedNextContext?(u=Object.create(t),u.unsubscribe=function(){return n.unsubscribe()},o={next:t.next&&F(t.next,u),error:t.error&&F(t.error,u),complete:t.complete&&F(t.complete,u)}):o=t}return n.destination=new Dt(o),n}return e}(at);function I(i){Rt(i)}function Pt(i){throw i}var It={closed:!0,next:ut,error:Pt,complete:ut},Ut=function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"}();function qt(i){return i}function Ct(i){return i.length===0?qt:i.length===1?i[0]:function(t){return i.reduce(function(r,s){return s(r)},t)}}var ct=function(){function i(e){e&&(this._subscribe=e)}return i.prototype.lift=function(e){var t=new i;return t.source=this,t.operator=e,t},i.prototype.subscribe=function(e,t,r){var s=this,n=jt(e)?e:new Y(e,t,r);return P(function(){var o=s,u=o.operator,c=o.source;n.add(u?u.call(n,c):c?s._subscribe(n):s._trySubscribe(n))}),n},i.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){e.error(t)}},i.prototype.forEach=function(e,t){var r=this;return t=ht(t),new t(function(s,n){var o=new Y({next:function(u){try{e(u)}catch(c){n(c),o.unsubscribe()}},error:n,complete:s});r.subscribe(o)})},i.prototype._subscribe=function(e){var t;return(t=this.source)===null||t===void 0?void 0:t.subscribe(e)},i.prototype[Ut]=function(){return this},i.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Ct(e)(this)},i.prototype.toPromise=function(e){var t=this;return e=ht(e),new e(function(r,s){var n;t.subscribe(function(o){return n=o},function(o){return s(o)},function(){return r(n)})})},i.create=function(e){return new i(e)},i}();function ht(i){var e;return(e=i??nt.Promise)!==null&&e!==void 0?e:Promise}function Bt(i){return i&&b(i.next)&&b(i.error)&&b(i.complete)}function jt(i){return i&&i instanceof at||Bt(i)&&it(i)}var kt=et(function(i){return function(){i(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),lt=function(i){$(e,i);function e(){var t=i.call(this)||this;return t.closed=!1,t.currentObservers=null,t.observers=[],t.isStopped=!1,t.hasError=!1,t.thrownError=null,t}return e.prototype.lift=function(t){var r=new dt(this,this);return r.operator=t,r},e.prototype._throwIfClosed=function(){if(this.closed)throw new kt},e.prototype.next=function(t){var r=this;P(function(){var s,n;if(r._throwIfClosed(),!r.isStopped){r.currentObservers||(r.currentObservers=Array.from(r.observers));try{for(var o=G(r.currentObservers),u=o.next();!u.done;u=o.next()){var c=u.value;c.next(t)}}catch(y){s={error:y}}finally{try{u&&!u.done&&(n=o.return)&&n.call(o)}finally{if(s)throw s.error}}}})},e.prototype.error=function(t){var r=this;P(function(){if(r._throwIfClosed(),!r.isStopped){r.hasError=r.isStopped=!0,r.thrownError=t;for(var s=r.observers;s.length;)s.shift().error(t)}})},e.prototype.complete=function(){var t=this;P(function(){if(t._throwIfClosed(),!t.isStopped){t.isStopped=!0;for(var r=t.observers;r.length;)r.shift().complete()}})},e.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(e.prototype,"observed",{get:function(){var t;return((t=this.observers)===null||t===void 0?void 0:t.length)>0},enumerable:!1,configurable:!0}),e.prototype._trySubscribe=function(t){return this._throwIfClosed(),i.prototype._trySubscribe.call(this,t)},e.prototype._subscribe=function(t){return this._throwIfClosed(),this._checkFinalizedStatuses(t),this._innerSubscribe(t)},e.prototype._innerSubscribe=function(t){var r=this,s=this,n=s.hasError,o=s.isStopped,u=s.observers;return n||o?rt:(this.currentObservers=null,u.push(t),new D(function(){r.currentObservers=null,W(u,t)}))},e.prototype._checkFinalizedStatuses=function(t){var r=this,s=r.hasError,n=r.thrownError,o=r.isStopped;s?t.error(n):o&&t.complete()},e.prototype.asObservable=function(){var t=new ct;return t.source=this,t},e.create=function(t,r){return new dt(t,r)},e}(ct),dt=function(i){$(e,i);function e(t,r){var s=i.call(this)||this;return s.destination=t,s.source=r,s}return e.prototype.next=function(t){var r,s;(s=(r=this.destination)===null||r===void 0?void 0:r.next)===null||s===void 0||s.call(r,t)},e.prototype.error=function(t){var r,s;(s=(r=this.destination)===null||r===void 0?void 0:r.error)===null||s===void 0||s.call(r,t)},e.prototype.complete=function(){var t,r;(r=(t=this.destination)===null||t===void 0?void 0:t.complete)===null||r===void 0||r.call(t)},e.prototype._subscribe=function(t){var r,s;return(s=(r=this.source)===null||r===void 0?void 0:r.subscribe(t))!==null&&s!==void 0?s:rt},e}(lt),U=function(i){$(e,i);function e(t){var r=i.call(this)||this;return r._value=t,r}return Object.defineProperty(e.prototype,"value",{get:function(){return this.getValue()},enumerable:!1,configurable:!0}),e.prototype._subscribe=function(t){var r=i.prototype._subscribe.call(this,t);return!r.closed&&t.next(this._value),r},e.prototype.getValue=function(){var t=this,r=t.hasError,s=t.thrownError,n=t._value;if(r)throw s;return this._throwIfClosed(),n},e.prototype.next=function(t){i.prototype.next.call(this,this._value=t)},e}(lt),pt=(i=>(i[i.DISABLED=0]="DISABLED",i[i.CRON=1]="CRON",i[i.EVENT=2]="EVENT",i[i.GET=3]="GET",i[i.POST=4]="POST",i[i.PATCH=5]="PATCH",i[i.PUT=6]="PUT",i[i.DELETE=7]="DELETE",i))(pt||{});class ft extends f{constructor(t){super();a(this,"api");a(this,"$cache",new U([]));this.api=typeof t=="string"?new m(t):t}get cache(){return this.$cache.value}set cache(t){this.$cache.next(t)}delete(t){return this.api.request({url:`/api/actions/${t}`,method:"DELETE"}).then(()=>{this.cache=this.cache.filter(r=>r._id!=t),this.emit("DELETE",t)})}list(){return this.api.request({url:"/api/actions"}).then(t=>(this.cache=t,this.emit("LIST",t),t))}read(t,r=!1){const s=this.cache.find(n=>n._id==t);return!r&&s?Promise.resolve(s):this.api.request({url:`/api/actions/${t}`}).then(n=>(n&&(this.cache=this.cache.filter(o=>o._id!=t).concat([n])),this.emit("READ",n),n))}run(t,r={}){return this.api.request({url:("/api/actions/run/"+t).replaceAll("//","/"),...r})}runById(t,r={}){const s=typeof t=="string"?t:t._id;return this.api.request({url:"/api/actions/run-by-id/"+s,...r})}update(t){return this.api.request({url:`/api/actions${t._id?`/${t._id}`:""}`,method:"POST",body:t}).then(r=>(r&&(this.cache=this.cache.filter(s=>s._id!=r._id).concat([r])),this.emit("UPDATE",r),r))}}class mt extends f{constructor(t,r){var s;super();a(this,"api");a(this,"storageKey");a(this,"$user",new U(void 0));if(this.opts=r,this.api=typeof t=="string"?new m(t):t,(s=this.opts)!=null&&s.loginUi||(this.opts={...this.opts,loginUi:this.api.url+"/ui/login"}),this.storageKey=`momentum:${new URL(this.api.url).host}`,this.api.on("TOKEN",n=>{var o;(o=this.opts)!=null&&o.persist&&(n?localStorage.setItem(this.storageKey,n):localStorage.removeItem(this.storageKey)),n?this.whoAmI(n,!0):this.user=null}),r!=null&&r.persist){const n=localStorage.getItem(this.storageKey);n?this.api.token=n:this.user=null}else this.user=null}get user(){return this.$user.value}set user(t){if(!K(this.user,t)){const r=t||null;this.$user.next(r),this.emit("USER",r)}}knownHost(t=location.origin){return t.startsWith("/")?Promise.resolve():this.api.request({url:`/api/auth/known-host?host=${encodeURI(new URL(t).origin)}`})}login(t,r){return this.api.request({url:"/api/auth/login",headers:{Authorization:void 0},body:{username:t,password:r}}).then(async s=>(this.api.token=s.token,await this.once("USER")))}loginRedirect(t=location.origin){return new Promise((r,s)=>{var o;const n=window.open(encodeURI(`${(o=this.opts)==null?void 0:o.loginUi}?redirect=postmessage&host=${t}`),"_blank");if(!n)return s("Unable to open login");n.addEventListener("message",u=>{var c;if(!((c=u==null?void 0:u.data)!=null&&c.token))return s("Unknown response from login");this.api.token=u.data.token,r(u.data.token),n.close()})})}logout(){this.api.token=null,this.user=null,this.emit("LOGOUT")}async register(t){const r=await this.api.request({url:"/api/auth/register",body:{...t}});return this.emit("REGISTER",t),r}async reset(t,r){await this.api.request({url:"/api/auth/reset",headers:{Authorization:r?`Bearer ${r}`:void 0},body:{email:r?void 0:t,password:r?t:void 0}}),this.emit(r?"RESET_COMPLETE":"RESET_REQUEST",r||t)}async whoAmI(t,r=!1){t||(t=this.api.token);const s=await this.api.request({url:"/api/auth/whoami",headers:t?{Authorization:`Bearer ${t}`}:void 0});return r&&(this.api.token=t,this.user=(s==null?void 0:s.user)||null,s&&this.emit("LOGIN",s.user)),s}}class yt extends f{constructor(t){super();a(this,"api");this.api=typeof t=="string"?new m(t):t}delete(t,r){return this.api.request({url:`/api/data/${t}/${r}`,method:"DELETE"}).then(()=>this.emit("DELETE",t,r))}get(t,r){return this.api.request({url:`/api/data/${t}${r?`/${r}`:""}`}).then(s=>(this.emit("GET",t,s),s))}raw(t,r,s,n){return this.api.request({url:`/api/data/${t}`,body:{operand:r,query:s,options:n}}).then(o=>(this.emit("RAW",t,o),o))}set(t,r,s=!1){return this.api.request({url:`/api/data/${t}/${r._id||""}`,method:s?"PATCH":"POST",body:r}).then(n=>(this.emit("SET",t,r),n))}}class Et extends f{constructor(t){super();a(this,"api");this.api=typeof t=="string"?new m(t):t}send(t){let r="/api/email";return typeof t.body=="object"&&(r+=`/${t.body.template}`),this.api.request({url:r,body:t}).then(s=>(this.emit("SENT",t),s))}}class gt extends f{constructor(t){super();a(this,"api");this.api=typeof t=="string"?new m(t):t}create(t){return this.api.request({url:`/api/groups/${t.name}`,method:"POST",body:t}).then(r=>(this.emit("CREATE",r),r))}list(){return this.api.request({url:"/api/groups"}).then(t=>(this.emit("LIST",t),t))}read(t){return this.api.request({url:`/api/groups/${t}`}).then(r=>(this.emit("READ",r),r))}update(t){return this.api.request({url:`/api/groups/${t.name}`,method:"PATCH",body:t}).then(r=>(this.emit("UPDATE",r),r))}delete(t){return this.api.request({url:`/api/groups/${t}`,method:"DELETE"}).then(()=>this.emit("DELETE",t))}}class bt{constructor(e,t){a(this,"api");this.api=typeof e=="string"?new m(e):e,t!=null&&t!="NONE"&&(window.addEventListener("error",r=>this.error(r.error.stack)),window.addEventListener("unhandledrejection",async r=>this.error(r.reason.stack)))}buildLog(e,t){return{time:new Date().getTime(),level:e,log:t,ctx:{cores:navigator.hardwareConcurrency,mem:navigator==null?void 0:navigator.deviceMemory,res:[window.innerWidth,window.innerHeight],url:location.href}}}clearClientLogs(){return this.api.request({url:"/api/logs/client",method:"DELETE"})}clearServerLogs(){return this.api.request({url:"/api/logs/server",method:"DELETE"})}clientLogs(e,t){const r=[e?`length=${e}`:void 0,t?`page=${t}`:void 0].filter(s=>!!s).join("&");return this.api.request({url:`/api/logs/client${r?`?${r}`:""}`})}serverLogs(e,t){const r=[e?`length=${e}`:void 0,t?`page=${t}`:void 0].filter(s=>!!s).join("&");return this.api.request({url:`/api/logs/server${r?`?${r}`:""}`})}debug(...e){return this.api.request({url:"/api/logs/client",body:this.buildLog(T.DEBUG,e)}).catch(()=>{})}log(...e){return this.api.request({url:"/api/logs/client",body:this.buildLog(T.LOG,e)}).catch(()=>{})}info(...e){return this.api.request({url:"/api/logs/client",body:this.buildLog(T.INFO,e)}).catch(()=>{})}warn(...e){return this.api.request({url:"/api/logs/client",body:this.buildLog(T.WARN,e)}).catch(()=>{})}error(...e){return this.api.request({url:"/api/logs/client",body:this.buildLog(T.ERROR,e)}).catch(()=>{})}}const C=class C{constructor(e){a(this,"api");a(this,"url");a(this,"connection");a(this,"open",!1);this.api=typeof e=="string"?new m(e):e,this.url=this.api.url.replace("http","ws"),this.api.on("TOKEN",()=>this.connect()),this.api.token||this.connect()}close(){console.debug("Disconnected from Momentum"),this.open=!1,this.connection.close()}connect(e=3){var r;((r=this.connection)==null?void 0:r.readyState)<2&&this.connection.close(),this.connection=new WebSocket(this.url+(this.api.token?`?token=${this.api.token}`:""));const t=setTimeout(()=>{this.open||(this.connection.close(),console.error("Momentum connection timeout"),e>0&&this.connect(e-1))},C.timeout);this.connection.onclose=()=>this.open=!1,this.connection.onmessage=this.handle,this.connection.onopen=()=>{this.open=!0,clearTimeout(t),console.debug("Connected to Momentum")}}handle(...e){console.log(e)}send(e,t){this.connection.send(JSON.stringify({token:this.api.token,channel:e,payload:t}))}};a(C,"timeout",1e4);let q=C;class vt extends f{constructor(t){super();a(this,"api");this.api=typeof t=="string"?new m(t):t}delete(t){const r=(t.startsWith("/api/storage/")?t:"/api/storage/"+t).replaceAll("//","/");return this.api.request({url:r,method:"DELETE"}).then(()=>{this.emit("DELETE",r)})}list(t){const r=(t.startsWith("/api/storage/")?t:"/api/storage/"+t).replaceAll("//","/");return this.api.request({url:r+"?list"}).then(s=>(this.emit("LIST",t,s),s))}open(t,r="_blank"){const s=(t.startsWith("/api/storage/")?t:"/api/storage/"+t).replaceAll(/\/{2,}/g,"/"),n=`${this.api.url}${s}${this.api.token?`?token=${this.api.token}`:""}`;return r?(this.emit("OPEN",t),window.open(n,r)):n}mkdir(t){const r=(t.startsWith("/api/storage/")?t:"/api/storage/"+t).replaceAll(/\/{2,}/g,"/");return this.api.request({url:r+"?directory",method:"POST"})}download(t,r={}){return new $t((s,n,o)=>{const u=("/api/storage/"+t).replaceAll("//","/");this.api.request({...r,url:u,skipConverting:!0}).then(c=>{var d;if(!c.ok)return n(c.statusText);const y=c.headers.get("Content-Length"),O=y?parseInt(y,10):0;let R=[],S=0;const g=(d=c.body)==null?void 0:d.getReader(),B=Tt=>{if(Tt.done){o(1);const A=new Blob(R),V=r.downloadAs||new URL(c.url).pathname.split("/").pop(),Ot=URL.createObjectURL(A);_t(Ot,V.includes(".")?V:V+".zip"),URL.revokeObjectURL(Ot),this.emit("DOWNLOAD",t,A),s(A)}else{const A=Tt.value;R.push(A),S+=A.length,o(S/O),g.read().then(B)}};g==null||g.read().then(B)})})}async upload(t,r=""){if(t||(t=await new Promise(u=>{const c=document.createElement("input");c.type="file",c.accept=(r==null?void 0:r.accept)||"*",c.style.display="none",c.multiple=!!(r!=null&&r.multiple),c.onblur=c.onchange=async()=>{u(Array.from(c.files)),c.remove()},document.body.appendChild(c),c.click()})),!t||Array.isArray(t)&&!t.length)return[];const n=new FormData,o=("/api/storage/"+(typeof r=="string"?r:r==null?void 0:r.path)).replaceAll("//","/");return(Array.isArray(t)?t:[t]).forEach(u=>n.append("file",u)),this.api.request({url:o,body:n}).then(u=>(this.emit("UPLOAD",u),u))}}class wt extends f{constructor(t){super();a(this,"api");a(this,"listed",!1);a(this,"$cache",new U([]));this.api=typeof t=="string"?new m(t):t}get cache(){return this.$cache.value}set cache(t){this.$cache.next(t)}delete(t){return this.api.request({url:`/api/users/${t}`,method:"DELETE"}).then(()=>{this.cache=this.cache.filter(r=>r.username!=t),this.emit("DELETE",t)})}list(t=!1){return!t&&this.listed?Promise.resolve(this.cache):this.api.request({url:"/api/users"}).then(r=>(this.cache=r,this.listed=!0,this.emit("LIST",r),r))}read(t,r=!1){if(!r){const s=this.cache.find(n=>n.username==t);if(s)return Promise.resolve(s)}return this.api.request({url:`/api/users/${t}`}).then(s=>(s&&(this.cache={...this.cache,[s.username]:s}),this.emit("READ",s),s))}update(t){return this.api.request({url:`/api/users/${t.username}`,method:"PATCH",body:t}).then(r=>(r&&(this.cache=this.cache.filter(s=>s.username!=t.username).concat([r])),this.emit("UPDATE",r),r))}}class St extends f{constructor(t){super();a(this,"api");a(this,"$cache",new U({}));this.api=typeof t=="string"?new m(t):t}get cache(){return this.$cache.value}set cache(t){this.$cache.next(t)}list(t=!1){return this.api.request({url:"/api/settings"+(t?"?detailed":"")}).then(r=>(this.cache=t?Object.values(r).reduce((s,n)=>({...s,[n.key]:n.value}),{}):r,this.emit("LIST",r),r))}delete(t){return this.api.request({url:`/api/settings/${t}`,method:"DELETE"}).then(()=>{this.cache={...this.cache,[t]:void 0},this.emit("DELETE",t)})}read(t,r=!1){return!r&&this.cache[t]?Promise.resolve(this.cache[t]):this.api.request({url:`/api/settings/${t}`}).then(s=>(s&&(this.cache={...this.cache,[s.key]:s}),this.emit("READ",s),s))}update(t){return this.api.request({url:`/api/settings/${t.key}`,body:t}).then(r=>(r&&(this.cache={...this.cache,[r.key]:r.value}),this.emit("UPDATE",r),r))}}class Lt extends f{constructor(t){super();a(this,"api");this.api=typeof t=="string"?new m(t):t}delete(t){return this.api.request({url:`/api/static/${t}`,method:"DELETE"}).then(()=>{this.emit("DELETE",t)})}list(t){const r=("/api/static/"+t).replaceAll("//","/");return this.api.request({url:r}).then(s=>(this.emit("LIST",t,s),s))}upload(t,r="/"){const s=new FormData;return(Array.isArray(t)?t:[t]).forEach(n=>s.append("file",n)),this.api.request({url:"/api/static"+r,body:s}).then(n=>(this.emit("UPLOAD",n),n))}}class Gt extends f{constructor(t,r){super();a(this,"api");a(this,"actions");a(this,"auth");a(this,"data");a(this,"email");a(this,"groups");a(this,"logger");a(this,"settings");a(this,"socket");a(this,"static");a(this,"storage");a(this,"users");this.api=new m(t,r==null?void 0:r.api),this.actions=new ft(this.api),this.auth=new mt(this.api,{persist:(r==null?void 0:r.persist)??!0,loginUi:r==null?void 0:r.loginUi}),this.data=new yt(this.api),this.email=new Et(this.api),this.groups=new gt(this.api),this.logger=new bt(this.api,r==null?void 0:r.logLevel),this.settings=new St(this.api),this.static=new Lt(this.api),this.storage=new vt(this.api),this.users=new wt(this.api),r!=null&&r.socket&&(this.socket=new q(this.api)),this.api.on("*",(s,...n)=>this.emit(`API::${s}`,...n)),this.actions.on("*",(s,...n)=>this.emit(`ACTIONS::${s}`,...n)),this.auth.on("*",(s,...n)=>this.emit(`AUTH::${s}`,...n)),this.data.on("*",(s,...n)=>this.emit(`DATA::${s}`,...n)),this.email.on("*",(s,...n)=>this.emit(`EMAIL::${s}`,...n)),this.groups.on("*",(s,...n)=>this.emit(`GROUPS::${s}`,...n)),this.settings.on("*",(s,...n)=>this.emit(`SETTINGS::${s}`,...n)),this.static.on("*",(s,...n)=>this.emit(`STATIC::${s}`,...n)),this.storage.on("*",(s,...n)=>this.emit(`STORAGE::${s}`,...n)),this.users.on("*",(s,...n)=>this.emit(`USERS::${s}`,...n)),this.users.on("*",(s,...n)=>{var o;if(Array.isArray(n[0])){const u=n[0].find(c=>{var y;return c._id==((y=this.auth.user)==null?void 0:y._id)});u&&(this.auth.user=u)}else n[0]._id==((o=this.auth.user)==null?void 0:o._id)&&(this.auth.user=n[0])})}}h.ActionType=pt,h.Actions=ft,h.Api=m,h.Auth=mt,h.Data=yt,h.Email=Et,h.Groups=gt,h.Logger=bt,h.Momentum=Gt,h.Settings=St,h.Socket=q,h.Static=Lt,h.Storage=vt,h.Users=wt,Object.defineProperty(h,Symbol.toStringTag,{value:"Module"})});
4
4
  //# sourceMappingURL=momentum.cjs.map