@ztimson/momentum 0.27.1 → 0.27.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- var B=function(t,i=!1){if(t==null)throw new Error("Cannot clean a NULL value");return Array.isArray(t)?t=t.filter((e)=>e!=null):Object.entries(t).forEach(([e,n])=>{(i&&n===void 0||!i&&n==null)&&delete t[e]}),t};var Q=function(t,i){const e=typeof t,n=typeof i;return e!="object"||t==null||n!="object"||i==null?e=="function"&&n=="function"?t.toString()==i.toString():t===i:Object.keys(t).length!=Object.keys(i).length?!1:Object.keys(t).every((s)=>Q(t[s],i[s]))};var x=function(t,i){const e=document.createElement("a");e.href=t,e.download=i,document.body.appendChild(e),e.click(),document.body.removeChild(e)};var Mt=Object.defineProperty,St=(t,i,e)=>(i in t)?Mt(t,i,{enumerable:!0,configurable:!0,writable:!0,value:e}):t[i]=e,r=(t,i,e)=>(St(t,typeof i!="symbol"?i+"":i,e),e);class h{constructor(){r(this,"listeners",{})}static emit(t,...i){(this.listeners["*"]||[]).forEach((e)=>e(t,...i)),(this.listeners[t.toString()]||[]).forEach((e)=>e(...i))}static off(t,i){const e=t.toString();this.listeners[e]=(this.listeners[e]||[]).filter((n)=>n===i)}static on(t,i){var e;const n=t.toString();return this.listeners[n]||(this.listeners[n]=[]),(e=this.listeners[n])==null||e.push(i),()=>this.off(t,i)}static once(t,i){return new Promise((e)=>{const n=this.on(t,(...s)=>{e(s.length==1?s[0]:s),i&&i(...s),n()})})}emit(t,...i){(this.listeners["*"]||[]).forEach((e)=>e(t,...i)),(this.listeners[t]||[]).forEach((e)=>e(...i))}off(t,i){this.listeners[t]=(this.listeners[t]||[]).filter((e)=>e===i)}on(t,i){var e;return this.listeners[t]||(this.listeners[t]=[]),(e=this.listeners[t])==null||e.push(i),()=>this.off(t,i)}once(t,i){return new Promise((e)=>{const n=this.on(t,(...s)=>{e(s.length==1?s[0]:s),i&&i(...s),n()})})}}r(h,"listeners",{});class w extends Error{constructor(t,i){super(t);r(this,"_code"),i!=null&&(this._code=i)}get code(){return this._code||this.constructor.code}set code(t){this._code=t}static from(t){const i=Number(t.statusCode)??Number(t.code),e=new this(t.message||t.toString());return Object.assign(e,{stack:t.stack,...t,code:i??void 0})}static instanceof(t){return t.constructor.code!=null}toString(){return this.message||super.toString()}}r(w,"code",500);class ft extends w{constructor(t="Bad Request"){super(t)}static instanceof(t){return t.constructor.code==this.code}}r(ft,"code",400);class mt extends w{constructor(t="Unauthorized"){super(t)}static instanceof(t){return t.constructor.code==this.code}}r(mt,"code",401);class ct extends w{constructor(t="Forbidden"){super(t)}static instanceof(t){return t.constructor.code==this.code}}r(ct,"code",403);class dt extends w{constructor(t="Not Found"){super(t)}static instanceof(t){return t.constructor.code==this.code}}r(dt,"code",404);class gt extends w{constructor(t="Internal Server Error"){super(t)}static instanceof(t){return t.constructor.code==this.code}}r(gt,"code",500);var U={CLEAR:"\x1B[0m",BRIGHT:"\x1B[1m",DIM:"\x1B[2m",UNDERSCORE:"\x1B[4m",BLINK:"\x1B[5m",REVERSE:"\x1B[7m",HIDDEN:"\x1B[8m"},k={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 P=((t)=>(t[t.ERROR=0]="ERROR",t[t.WARN=1]="WARN",t[t.INFO=2]="INFO",t[t.LOG=3]="LOG",t[t.DEBUG=4]="DEBUG",t))(P||{}),kt=class t extends h{constructor(i){super(),this.namespace=i}pad(i,e,n,s=!1){const o=i.toString(),a=e-o.length;if(a<=0)return o;const u=Array(~~(a/n.length)).fill(n).join("");return s?o+u:u+o}format(...i){const e=new Date;return`${`${e.getFullYear()}-${e.getMonth()+1}-${e.getDate()} ${this.pad(e.getHours().toString(),2,"0")}:${this.pad(e.getMinutes().toString(),2,"0")}:${this.pad(e.getSeconds().toString(),2,"0")}.${this.pad(e.getMilliseconds().toString(),3,"0",!0)}`}${this.namespace?` [${this.namespace}]`:""} ${i.join(" ")}`}debug(...i){if(t.LOG_LEVEL<4)return;const e=this.format(...i);t.emit(4,e),console.debug(k.LIGHT_GREY+e+U.CLEAR)}log(...i){if(t.LOG_LEVEL<3)return;const e=this.format(...i);t.emit(3,e),console.log(U.CLEAR+e)}info(...i){if(t.LOG_LEVEL<2)return;const e=this.format(...i);t.emit(2,e),console.info(k.BLUE+e+U.CLEAR)}warn(...i){if(t.LOG_LEVEL<1)return;const e=this.format(...i);t.emit(1,e),console.warn(k.YELLOW+e+U.CLEAR)}error(...i){if(t.LOG_LEVEL<0)return;const e=this.format(...i);t.emit(0,e),console.error(k.RED+e+U.CLEAR)}};r(kt,"LOG_LEVEL",4);var xt="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",Wt="0123456789",Ht="~`!@#$%^&*()_-+={[}]|\\:;\"'<,>.?/",Ct=xt+Wt+Ht;class J extends Promise{constructor(t){super((i,e)=>t((n)=>i(n),(n)=>e(n),(n)=>this.progress=n));r(this,"listeners",[]),r(this,"_progress",0)}get progress(){return this._progress}set progress(t){t!=this._progress&&(this._progress=t,this.listeners.forEach((i)=>i(t)))}onProgress(t){return this.listeners.push(t),this}}var X=class t{constructor(i={}){r(this,"interceptors",{}),r(this,"headers",{}),this.opts=i,this.headers=i.headers||{},i.interceptors&&i.interceptors.forEach((e)=>t.addInterceptor(e))}static addInterceptor(i){const e=Object.keys(t.interceptors).length.toString();return t.interceptors[e]=i,()=>{t.interceptors[e]=null}}addInterceptor(i){const e=Object.keys(this.interceptors).length.toString();return this.interceptors[e]=i,()=>{this.interceptors[e]=null}}async request(i={}){var e,n;if(!this.opts.url&&!i.url)throw new Error("URL needs to be set");let s=((e=i.url)!=null&&e.startsWith("http")?i.url:(this.opts.url||"")+(i.url||"")).replace(/([^:]\/)\/+/g,"$1");if(i.fragment&&(s.includes("#")?s.replace(/#.*(\?|\n)/g,(a,u)=>`#${i.fragment}${u}`):s+="#"+i.fragment),i.query){const a=Array.isArray(i.query)?i.query:Object.keys(i.query).map((u)=>({key:u,value:i.query[u]}));s+=(s.includes("?")?"&":"?")+a.map((u)=>`${u.key}=${u.value}`).join("&")}const o=B({"Content-Type":i.body&&!(i.body instanceof FormData)?"application/json":void 0,...t.headers,...this.headers,...i.headers});return fetch(s,{headers:o,method:i.method||(i.body?"POST":"GET"),body:(n=o["Content-Type"])!=null&&n.startsWith("application/json")&&i.body?JSON.stringify(i.body):i.body}).then(async(a)=>{for(let l of[...Object.values(t.interceptors),...Object.values(this.interceptors)])await new Promise((m)=>l(a,()=>m()));const u=await(async()=>{var l,m;return!i.skipConverting&&((l=a.headers.get("Content-Type"))!=null&&l.startsWith("application/json"))?await a.json():!i.skipConverting&&((m=a.headers.get("Content-Type"))!=null&&m.startsWith("text/plain"))?await a.text():a})();if(a.ok)return u;throw Object.assign(new Error(typeof u=="string"?u:a.statusText),typeof u=="object"?u:{})})}};r(X,"interceptors",{}),r(X,"headers",{});var Et=X;class p extends Et{t;i;emitter=new h;_token=null;get token(){return this._token}set token(t){if(t==this._token)return;this._token=t,this.headers.Authorization=t?`Bearer ${t}`:void 0,this.emit("TOKEN",t)}constructor(t=location.origin,i={}){i.url=t;super(i);this.url=t;this.opts=i}emit=this.emitter.emit.bind(this.emitter);off=this.emitter.off.bind(this.emitter);on=this.emitter.on.bind(this.emitter);once=this.emitter.once.bind(this.emitter);request(t){const i=super.request(t).then((e)=>{return this.emit("RESPONSE",e,t),e}).catch((e)=>{throw this.emit("REJECTED",e,t),e});return this.emit("REQUEST",i,t),i}}function T(t,i){if(typeof i!=="function"&&i!==null)throw new TypeError("Class extends value "+String(i)+" is not a constructor or null");C(t,i);function e(){this.constructor=t}t.prototype=i===null?Object.create(i):(e.prototype=i.prototype,new e)}function M(t){var i=typeof Symbol==="function"&&Symbol.iterator,e=i&&t[i],n=0;if(e)return e.call(t);if(t&&typeof t.length==="number")return{next:function(){if(t&&n>=t.length)t=void 0;return{value:t&&t[n++],done:!t}}};throw new TypeError(i?"Object is not iterable.":"Symbol.iterator is not defined.")}function D(t,i){var e=typeof Symbol==="function"&&t[Symbol.iterator];if(!e)return t;var n=e.call(t),s,o=[],a;try{while((i===void 0||i-- >0)&&!(s=n.next()).done)o.push(s.value)}catch(u){a={error:u}}finally{try{if(s&&!s.done&&(e=n.return))e.call(n)}finally{if(a)throw a.error}}return o}function R(t,i,e){if(e||arguments.length===2){for(var n=0,s=i.length,o;n<s;n++)if(o||!(n in i)){if(!o)o=Array.prototype.slice.call(i,0,n);o[n]=i[n]}}return t.concat(o||Array.prototype.slice.call(i))}var C=function(t,i){return C=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,n){e.__proto__=n}||function(e,n){for(var s in n)if(Object.prototype.hasOwnProperty.call(n,s))e[s]=n[s]},C(t,i)};function f(t){return typeof t==="function"}function W(t){var i=function(n){Error.call(n),n.stack=new Error().stack},e=t(i);return e.prototype=Object.create(Error.prototype),e.prototype.constructor=e,e}var H=W(function(t){return function i(e){t(this),this.message=e?e.length+" errors occurred during unsubscription:\n"+e.map(function(n,s){return s+1+") "+n.toString()}).join("\n "):"",this.name="UnsubscriptionError",this.errors=e}});function S(t,i){if(t){var e=t.indexOf(i);0<=e&&t.splice(e,1)}}function F(t){return t instanceof $||t&&"closed"in t&&f(t.remove)&&f(t.add)&&f(t.unsubscribe)}var Tt=function(t){if(f(t))t();else t.unsubscribe()},$=function(){function t(i){this.initialTeardown=i,this.closed=!1,this._parentage=null,this._finalizers=null}return t.prototype.unsubscribe=function(){var i,e,n,s,o;if(!this.closed){this.closed=!0;var a=this._parentage;if(a)if(this._parentage=null,Array.isArray(a))try{for(var u=M(a),l=u.next();!l.done;l=u.next()){var m=l.value;m.remove(this)}}catch(y){i={error:y}}finally{try{if(l&&!l.done&&(e=u.return))e.call(u)}finally{if(i)throw i.error}}else a.remove(this);var I=this.initialTeardown;if(f(I))try{I()}catch(y){o=y instanceof H?y.errors:[y]}var G=this._finalizers;if(G){this._finalizers=null;try{for(var A=M(G),g=A.next();!g.done;g=A.next()){var E=g.value;try{Tt(E)}catch(y){if(o=o!==null&&o!==void 0?o:[],y instanceof H)o=R(R([],D(o)),D(y.errors));else o.push(y)}}}catch(y){n={error:y}}finally{try{if(g&&!g.done&&(s=A.return))s.call(A)}finally{if(n)throw n.error}}}if(o)throw new H(o)}},t.prototype.add=function(i){var e;if(i&&i!==this)if(this.closed)Tt(i);else{if(i instanceof t){if(i.closed||i._hasParent(this))return;i._addParent(this)}(this._finalizers=(e=this._finalizers)!==null&&e!==void 0?e:[]).push(i)}},t.prototype._hasParent=function(i){var e=this._parentage;return e===i||Array.isArray(e)&&e.includes(i)},t.prototype._addParent=function(i){var e=this._parentage;this._parentage=Array.isArray(e)?(e.push(i),e):e?[e,i]:i},t.prototype._removeParent=function(i){var e=this._parentage;if(e===i)this._parentage=null;else if(Array.isArray(e))S(e,i)},t.prototype.remove=function(i){var e=this._finalizers;if(e&&S(e,i),i instanceof t)i._removeParent(this)},t.EMPTY=function(){var i=new t;return i.closed=!0,i}(),t}();var Z=$.EMPTY;var c={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1};var O={setTimeout:function(t,i){var e=[];for(var n=2;n<arguments.length;n++)e[n-2]=arguments[n];var s=O.delegate;if(s===null||s===void 0?void 0:s.setTimeout)return s.setTimeout.apply(s,R([t,i],D(e)));return setTimeout.apply(void 0,R([t,i],D(e)))},clearTimeout:function(t){var i=O.delegate;return((i===null||i===void 0?void 0:i.clearTimeout)||clearTimeout)(t)},delegate:void 0};function At(t){O.setTimeout(function(){var i=c.onUnhandledError;if(i)i(t);else throw t})}function Y(){}function Pt(t){return v("E",void 0,t)}function Lt(t){return v("N",t,void 0)}function v(t,i,e){return{kind:t,value:i,error:e}}var wt=function(){return v("C",void 0,void 0)}();function q(t){if(c.useDeprecatedSynchronousErrorHandling){var i=!L;if(i)L={errorThrown:!1,error:null};if(t(),i){var e=L,n=e.errorThrown,s=e.error;if(L=null,n)throw s}}else t()}function Dt(t){if(c.useDeprecatedSynchronousErrorHandling&&L)L.errorThrown=!0,L.error=t}var L=null;var j=function(t,i){return Ft.call(t,i)},K=function(t){if(c.useDeprecatedSynchronousErrorHandling)Dt(t);else At(t)},Nt=function(t){throw t},z=function(t,i){var e=c.onStoppedNotification;e&&O.setTimeout(function(){return e(t,i)})},b=function(t){T(i,t);function i(e){var n=t.call(this)||this;if(n.isStopped=!1,e){if(n.destination=e,F(e))e.add(n)}else n.destination=Vt;return n}return i.create=function(e,n,s){return new N(e,n,s)},i.prototype.next=function(e){if(this.isStopped)z(Lt(e),this);else this._next(e)},i.prototype.error=function(e){if(this.isStopped)z(Pt(e),this);else this.isStopped=!0,this._error(e)},i.prototype.complete=function(){if(this.isStopped)z(wt,this);else this.isStopped=!0,this._complete()},i.prototype.unsubscribe=function(){if(!this.closed)this.isStopped=!0,t.prototype.unsubscribe.call(this),this.destination=null},i.prototype._next=function(e){this.destination.next(e)},i.prototype._error=function(e){try{this.destination.error(e)}finally{this.unsubscribe()}},i.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},i}($);var Ft=Function.prototype.bind,Kt=function(){function t(i){this.partialObserver=i}return t.prototype.next=function(i){var e=this.partialObserver;if(e.next)try{e.next(i)}catch(n){K(n)}},t.prototype.error=function(i){var e=this.partialObserver;if(e.error)try{e.error(i)}catch(n){K(n)}else K(i)},t.prototype.complete=function(){var i=this.partialObserver;if(i.complete)try{i.complete()}catch(e){K(e)}},t}(),N=function(t){T(i,t);function i(e,n,s){var o=t.call(this)||this,a;if(f(e)||!e)a={next:e!==null&&e!==void 0?e:void 0,error:n!==null&&n!==void 0?n:void 0,complete:s!==null&&s!==void 0?s:void 0};else{var u;if(o&&c.useDeprecatedNextContext)u=Object.create(e),u.unsubscribe=function(){return o.unsubscribe()},a={next:e.next&&j(e.next,u),error:e.error&&j(e.error,u),complete:e.complete&&j(e.complete,u)};else a=e}return o.destination=new Kt(a),o}return i}(b);var Vt={closed:!0,next:Y,error:Nt,complete:Y};var Rt=function(){return typeof Symbol==="function"&&Symbol.observable||"@@observable"}();function $t(t){return t}function Ot(t){if(t.length===0)return $t;if(t.length===1)return t[0];return function i(e){return t.reduce(function(n,s){return s(n)},e)}}var qt=function(t){var i;return(i=t!==null&&t!==void 0?t:c.Promise)!==null&&i!==void 0?i:Promise},Xt=function(t){return t&&f(t.next)&&f(t.error)&&f(t.complete)},Bt=function(t){return t&&t instanceof b||Xt(t)&&F(t)},_=function(){function t(i){if(i)this._subscribe=i}return t.prototype.lift=function(i){var e=new t;return e.source=this,e.operator=i,e},t.prototype.subscribe=function(i,e,n){var s=this,o=Bt(i)?i:new N(i,e,n);return q(function(){var a=s,u=a.operator,l=a.source;o.add(u?u.call(o,l):l?s._subscribe(o):s._trySubscribe(o))}),o},t.prototype._trySubscribe=function(i){try{return this._subscribe(i)}catch(e){i.error(e)}},t.prototype.forEach=function(i,e){var n=this;return e=qt(e),new e(function(s,o){var a=new N({next:function(u){try{i(u)}catch(l){o(l),a.unsubscribe()}},error:o,complete:s});n.subscribe(a)})},t.prototype._subscribe=function(i){var e;return(e=this.source)===null||e===void 0?void 0:e.subscribe(i)},t.prototype[Rt]=function(){return this},t.prototype.pipe=function(){var i=[];for(var e=0;e<arguments.length;e++)i[e]=arguments[e];return Ot(i)(this)},t.prototype.toPromise=function(i){var e=this;return i=qt(i),new i(function(n,s){var o;e.subscribe(function(a){return o=a},function(a){return s(a)},function(){return n(o)})})},t.create=function(i){return new t(i)},t}();var It=W(function(t){return function i(){t(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}});var tt=function(t){T(i,t);function i(){var e=t.call(this)||this;return e.closed=!1,e.currentObservers=null,e.observers=[],e.isStopped=!1,e.hasError=!1,e.thrownError=null,e}return i.prototype.lift=function(e){var n=new Gt(this,this);return n.operator=e,n},i.prototype._throwIfClosed=function(){if(this.closed)throw new It},i.prototype.next=function(e){var n=this;q(function(){var s,o;if(n._throwIfClosed(),!n.isStopped){if(!n.currentObservers)n.currentObservers=Array.from(n.observers);try{for(var a=M(n.currentObservers),u=a.next();!u.done;u=a.next()){var l=u.value;l.next(e)}}catch(m){s={error:m}}finally{try{if(u&&!u.done&&(o=a.return))o.call(a)}finally{if(s)throw s.error}}}})},i.prototype.error=function(e){var n=this;q(function(){if(n._throwIfClosed(),!n.isStopped){n.hasError=n.isStopped=!0,n.thrownError=e;var s=n.observers;while(s.length)s.shift().error(e)}})},i.prototype.complete=function(){var e=this;q(function(){if(e._throwIfClosed(),!e.isStopped){e.isStopped=!0;var n=e.observers;while(n.length)n.shift().complete()}})},i.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(i.prototype,"observed",{get:function(){var e;return((e=this.observers)===null||e===void 0?void 0:e.length)>0},enumerable:!1,configurable:!0}),i.prototype._trySubscribe=function(e){return this._throwIfClosed(),t.prototype._trySubscribe.call(this,e)},i.prototype._subscribe=function(e){return this._throwIfClosed(),this._checkFinalizedStatuses(e),this._innerSubscribe(e)},i.prototype._innerSubscribe=function(e){var n=this,s=this,o=s.hasError,a=s.isStopped,u=s.observers;if(o||a)return Z;return this.currentObservers=null,u.push(e),new $(function(){n.currentObservers=null,S(u,e)})},i.prototype._checkFinalizedStatuses=function(e){var n=this,s=n.hasError,o=n.thrownError,a=n.isStopped;if(s)e.error(o);else if(a)e.complete()},i.prototype.asObservable=function(){var e=new _;return e.source=this,e},i.create=function(e,n){return new Gt(e,n)},i}(_);var Gt=function(t){T(i,t);function i(e,n){var s=t.call(this)||this;return s.destination=e,s.source=n,s}return i.prototype.next=function(e){var n,s;(s=(n=this.destination)===null||n===void 0?void 0:n.next)===null||s===void 0||s.call(n,e)},i.prototype.error=function(e){var n,s;(s=(n=this.destination)===null||n===void 0?void 0:n.error)===null||s===void 0||s.call(n,e)},i.prototype.complete=function(){var e,n;(n=(e=this.destination)===null||e===void 0?void 0:e.complete)===null||n===void 0||n.call(e)},i.prototype._subscribe=function(e){var n,s;return(s=(n=this.source)===null||n===void 0?void 0:n.subscribe(e))!==null&&s!==void 0?s:Z},i}(tt);var d=function(t){T(i,t);function i(e){var n=t.call(this)||this;return n._value=e,n}return Object.defineProperty(i.prototype,"value",{get:function(){return this.getValue()},enumerable:!1,configurable:!0}),i.prototype._subscribe=function(e){var n=t.prototype._subscribe.call(this,e);return!n.closed&&e.next(this._value),n},i.prototype.getValue=function(){var e=this,n=e.hasError,s=e.thrownError,o=e._value;if(n)throw s;return this._throwIfClosed(),o},i.prototype.next=function(e){t.prototype.next.call(this,this._value=e)},i}(tt);var Qt;((u)=>{u[u.CRON=0]="CRON";u[u.EVENT=1]="EVENT";u[u.DELETE=2]="DELETE";u[u.GET=3]="GET";u[u.PATCH=4]="PATCH";u[u.POST=5]="POST";u[u.PUT=6]="PUT"})(Qt||={});class it extends h{api;$cache=new d([]);get cache(){return this.$cache.value}set cache(t){this.$cache.next(t)}constructor(t){super();this.api=typeof t=="string"?new p(t):t}delete(t){return this.api.request({url:`/api/actions/${t}`,method:"DELETE"}).then(()=>{this.cache=this.cache.filter((i)=>i._id!=t),this.emit("DELETE",t)})}list(){return this.api.request({url:"/api/actions"}).then((t)=>{return this.cache=t,this.emit("LIST",t),t})}read(t,i=!1){const e=this.cache.find((n)=>n._id==t);if(!i&&e)return Promise.resolve(e);return this.api.request({url:`/api/actions/${t}`}).then((n)=>{if(n)this.cache=this.cache.filter((s)=>s._id!=t).concat([n]);return this.emit("READ",n),n})}run(t,i={}){return this.api.request({url:("/api/actions/run/"+t).replaceAll("//","/"),...i})}runById(t,i={}){const e=typeof t=="string"?t:t._id;return this.api.request({url:"/api/actions/run-by-id/"+e,method:"POST",...i})}update(t){return this.api.request({url:`/api/actions${t._id?`/${t._id}`:""}`,method:"POST",body:t}).then((i)=>{if(i)this.cache=this.cache.filter((e)=>e._id!=i._id).concat([i]);return this.emit("UPDATE",i),i})}}class Ut{t;constructor(t){this.api=t}disable(t){return this.api.request({url:`/api/auth/totp/${t}`,method:"DELETE"})}enable=this.reset;reset(t){return this.api.request({url:`/api/auth/totp/${t}`,method:"POST"})}setup(t,i="app",e){return this.api.request({url:`/api/auth/totp/${t}`,body:B({method:i,totp:e})})}}class et extends h{i;api;storageKey;totp;$user=new d(void 0);get user(){return this.$user.value}set user(t){if(!Q(this.user,t)){const i=t?t:null;this.$user.next(i),this.emit("USER",i)}}constructor(t,i){super();this.opts=i;if(this.api=typeof t=="string"?new p(t):t,this.totp=new Ut(this.api),!this.opts?.loginUi)this.opts={...this.opts,loginUi:this.api.url+"/ui/login"};if(this.storageKey=`momentum:${new URL(this.api.url).host}`,this.api.addInterceptor((e,n)=>{const s=["/api/auth/login","/api/auth/password","/api/auth/totp"];if(e.status==401&&!s.find((o)=>e.url.includes(o)))this.emit("SESSION_EXPIRED");n()}),this.api.on("TOKEN",(e)=>{if(this.opts?.persist)if(e)localStorage.setItem(this.storageKey,e);else localStorage.removeItem(this.storageKey);if(e)this.session(e,!0).catch(()=>{});else this.user=null}),i?.persist){const e=localStorage.getItem(this.storageKey);if(e)this.api.token=e;else this.user=null}else this.user=null}knownHost(t=location.origin){if(t.startsWith("/"))return Promise.resolve();return this.api.request({url:`/api/auth/known-host?host=${encodeURI(new URL(t).origin)}`})}login(t,i,e){return this.api.request({url:"/api/auth/login",headers:{Authorization:void 0},body:{username:t.trim(),password:i.trim(),totp:e}}).then(async(n)=>{return this.api.token=n.token,await this.once("USER")})}loginRedirect(t=location.origin){return new Promise((i,e)=>{const n=window.open(encodeURI(`${this.opts?.loginUi}?redirect=postmessage&host=${t}`),"_blank");if(!n)return e("Unable to open login");n.addEventListener("message",(s)=>{if(!s?.data?.token)return e("Unknown response from login");this.api.token=s.data.token,i(s.data.token),n.close()})})}logout(){this.api.token=null,this.user=null,this.emit("LOGOUT")}async register(t){const i=await this.api.request({url:"/api/auth/register",body:{...t}});if(i.image.startsWith("/"))i.image=`${this.api.url}${i.image}?token=${this.api.token}`;return this.emit("REGISTER",i),i}reset(t,i){return this.api.request({url:"/api/auth/reset",headers:{Authorization:i?`Bearer ${i}`:void 0},body:{email:i?void 0:t,password:i?t:void 0}})}async session(t,i=!1){if(!t)t=this.api.token;const e=await this.api.request({url:"/api/auth/session",headers:t?{Authorization:`Bearer ${t}`}:void 0});if(i){if(this.api.token=t,e?.user)e.user.image=`${this.api.url}${e.user.image}?token=${this.api.token}`;if(this.user=e?.user||null,e)this.emit("LOGIN",e.user)}return e}async updatePassword(t,i,e){return this.api.request({url:"/api/auth/password",body:{username:t,password:i,oldPassword:e}}).then((n)=>{if(n?.token)this.api.token=n.token})}}class nt extends h{api;constructor(t){super();this.api=typeof t=="string"?new p(t):t}delete(t,i){return this.api.request({url:`/api/data/${t}/${i}`,method:"DELETE"}).then(()=>this.emit("DELETE",t,i))}get(t,i){return this.api.request({url:`/api/data/${t}${i?`/${i}`:""}`}).then((e)=>{return this.emit("GET",t,e),e})}raw(t,i,e,n){return this.api.request({url:`/api/data/${t}`,body:{operand:i,query:e,options:n}}).then((s)=>{return this.emit("RAW",t,s),s})}set(t,i,e=!1){return this.api.request({url:`/api/data/${t}/${i._id||""}`,method:e?"PATCH":"POST",body:i}).then((n)=>{return this.emit("SET",t,i),n})}}class st extends h{api;constructor(t){super();this.api=typeof t=="string"?new p(t):t}send(t){let i="/api/email";if(typeof t.body=="object")i+=`/${t.body.template}`;return this.api.request({url:i,body:t}).then((e)=>{return this.emit("SENT",t),e})}}class ot extends h{api;constructor(t){super();this.api=typeof t=="string"?new p(t):t}create(t){return this.api.request({url:`/api/groups/${t.name}`,method:"POST",body:t}).then((i)=>{return this.emit("CREATE",i),i})}list(){return this.api.request({url:"/api/groups"}).then((t)=>{return this.emit("LIST",t),t})}read(t){return this.api.request({url:`/api/groups/${t}`}).then((i)=>{return this.emit("READ",i),i})}update(t){return this.api.request({url:`/api/groups/${t.name}`,method:"PATCH",body:t}).then((i)=>{return this.emit("UPDATE",i),i})}delete(t){return this.api.request({url:`/api/groups/${t}`,method:"DELETE"}).then(()=>this.emit("DELETE",t))}}class at{api;constructor(t,i){if(this.api=typeof t=="string"?new p(t):t,i!=null&&i!="NONE")window.addEventListener("error",(e)=>this.error(e.error.stack)),window.addEventListener("unhandledrejection",async(e)=>this.error(e.reason.stack))}buildLog(t,i){return{time:(new Date()).getTime(),level:t,log:i,ctx:{cores:navigator.hardwareConcurrency,mem: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(t,i){const e=[t?`length=${t}`:void 0,i?`page=${i}`:void 0].filter((n)=>!!n).join("&");return this.api.request({url:`/api/logs/client${e?`?${e}`:""}`})}serverLogs(t,i){const e=[t?`length=${t}`:void 0,i?`page=${i}`:void 0].filter((n)=>!!n).join("&");return this.api.request({url:`/api/logs/server${e?`?${e}`:""}`})}debug(...t){return this.api.request({url:"/api/logs/client",body:this.buildLog(P.DEBUG,t)}).catch(()=>{})}log(...t){return this.api.request({url:"/api/logs/client",body:this.buildLog(P.LOG,t)}).catch(()=>{})}info(...t){return this.api.request({url:"/api/logs/client",body:this.buildLog(P.INFO,t)}).catch(()=>{})}warn(...t){return this.api.request({url:"/api/logs/client",body:this.buildLog(P.WARN,t)}).catch(()=>{})}error(...t){return this.api.request({url:"/api/logs/client",body:this.buildLog(P.ERROR,t)}).catch(()=>{})}}class ut extends h{api;constructor(t){super();this.api=typeof t=="string"?new p(t):t}async handleResponse(t,i){const e=await t.blob();if(i){const n=URL.createObjectURL(e);x(n,i.endsWith(".pdf")?i:i+".pdf"),URL.revokeObjectURL(n)}return this.emit("CREATE",e),e}generate(t,i={}){const e=t?.template;return this.api.request({url:`/api/pdf${e?`/${e}`:""}`,body:e?t?.data:{html:t}}).then((n)=>this.handleResponse(n,i.download?i.fileName||(new Date()).toISOString():void 0))}fromUrl(t,i={}){return this.api.request({url:`/api/pdf?url=${t}`}).then((e)=>this.handleResponse(e,i.download?i.fileName||(new Date()).toISOString():void 0))}}class V{static timeout=1e4;api;url;connection;open=!1;constructor(t){if(this.api=typeof t=="string"?new p(t):t,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(t=3){if(this.connection?.readyState<2)this.connection.close();this.connection=new WebSocket(this.url+(this.api.token?`?token=${this.api.token}`:""));const i=setTimeout(()=>{if(this.open)return;if(this.connection.close(),console.error("Momentum connection timeout"),t>0)this.connect(t-1)},V.timeout);this.connection.onclose=()=>this.open=!1,this.connection.onmessage=this.handle,this.connection.onopen=()=>{this.open=!0,clearTimeout(i),console.debug("Connected to Momentum")}}handle(...t){console.log(t)}send(t,i){this.connection.send(JSON.stringify({token:this.api.token,channel:t,payload:i}))}}class ht extends h{api;constructor(t){super();this.api=typeof t=="string"?new p(t):t}delete(t){const i=(t.startsWith("/api/storage/")?t:"/api/storage/"+t).replaceAll("//","/");return this.api.request({url:i,method:"DELETE"}).then(()=>{this.emit("DELETE",i)})}list(t){const i=(t.startsWith("/api/storage/")?t:"/api/storage/"+t).replaceAll("//","/");return this.api.request({url:i+"?list"}).then((e)=>{return this.emit("LIST",t,e),e})}open(t,i="_blank"){const e=(t.startsWith("/api/storage/")?t:"/api/storage/"+t).replaceAll(/\/{2,}/g,"/"),n=`${this.api.url}${e}${this.api.token?`?token=${this.api.token}`:""}`;if(!i)return n;return this.emit("OPEN",t),window.open(n,i)}mkdir(t){const i=(t.startsWith("/api/storage/")?t:"/api/storage/"+t).replaceAll(/\/{2,}/g,"/");return this.api.request({url:i+"?directory",method:"POST"})}download(t,i={}){return new J((e,n,s)=>{const o=("/api/storage/"+t).replaceAll("//","/");this.api.request({...i,url:o,skipConverting:!0}).then((a)=>{if(!a.ok)return n(a.statusText);const u=a.headers.get("Content-Length"),l=u?parseInt(u,10):0;let m=[],I=0;const G=a.body?.getReader(),A=(g)=>{if(g.done){s(1);const E=new Blob(m),y=i.downloadAs||new URL(a.url).pathname.split("/").pop(),yt=URL.createObjectURL(E);x(yt,y.includes(".")?y:y+".zip"),URL.revokeObjectURL(yt),this.emit("DOWNLOAD",t,E),e(E)}else{const E=g.value;m.push(E),I+=E.length,s(I/l),G.read().then(A)}};G?.read().then(A)})})}async upload(t,i=""){const e=()=>{return new Promise((o)=>{const a=document.createElement("input");a.type="file",a.accept=i?.accept||"*",a.style.display="none",a.multiple=!!i?.multiple,a.onblur=a.onchange=async()=>{o(Array.from(a.files)),a.remove()},document.body.appendChild(a),a.click()})};if(!t)t=await e();if(!t||Array.isArray(t)&&!t.length)return[];const n=new FormData,s=("/api/storage/"+(typeof i=="string"?i:i?.path)).replaceAll("//","/");return(Array.isArray(t)?t:[t]).forEach((o)=>n.append("file",o)),this.api.request({url:s,body:n}).then((o)=>{return this.emit("UPLOAD",o),o})}}class pt extends h{api;listed=!1;$cache=new d([]);get cache(){return this.$cache.value}set cache(t){this.$cache.next(t)}constructor(t){super();this.api=typeof t=="string"?new p(t):t}delete(t){return this.api.request({url:`/api/users/${t}`,method:"DELETE"}).then(()=>{this.cache=this.cache.filter((i)=>i.username!=t),this.emit("DELETE",t)})}list(t=!1){if(!t&&this.listed)return Promise.resolve(this.cache);return this.api.request({url:"/api/users"}).then((i)=>{return i.map((e)=>{return e.image=this.api.url+e.image+`?token=${this.api.token}`,e}),this.cache=i,this.listed=!0,this.emit("LIST",i),i})}read(t,i=!1){if(!i){const e=this.cache.find((n)=>n.username==t);if(e)return Promise.resolve(e)}return this.api.request({url:`/api/users/${t}`}).then((e)=>{if(e.image=this.api.url+e.image+`?token=${this.api.token}`,e)this.cache=[...this.cache.filter((n)=>n.username!=t),e];return this.emit("READ",e),e})}update(t){return this.api.request({url:`/api/users/${t.username}`,method:"PATCH",body:t}).then((i)=>{if(i.image=this.api.url+i.image+`?token=${this.api.token}`,i)this.cache=this.cache.filter((e)=>e.username!=t.username).concat([i]);return this.emit("UPDATE",i),i})}uploadImage(t,i){const e=new FormData;return e.append("file",i),this.api.request({url:`/api/users/${t}/image`,body:e}).then((n)=>{return this.emit("UPLOAD_IMAGE",i),n})}}class lt extends h{api;$cache=new d({});get cache(){return this.$cache.value}set cache(t){this.$cache.next(t)}constructor(t){super();this.api=typeof t=="string"?new p(t):t}list(t=!1){return this.api.request({url:"/api/settings"+(t?"?detailed":"")}).then((i)=>{return this.cache=!t?i:Object.values(i).reduce((e,n)=>({...e,[n.key]:n.value}),{}),this.emit("LIST",i),i})}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,i=!1){if(!i&&this.cache[t])return Promise.resolve(this.cache[t]);return this.api.request({url:`/api/settings/${t}`}).then((e)=>{if(e)this.cache={...this.cache,[e.key]:e};return this.emit("READ",e),e})}update(t){return this.api.request({url:`/api/settings/${t.key}`,body:t}).then((i)=>{if(i)this.cache={...this.cache,[i.key]:i.value};return this.emit("UPDATE",i),i})}}class rt extends h{api;constructor(t){super();this.api=typeof t=="string"?new p(t):t}delete(t){return this.api.request({url:`/api/static/${t}`,method:"DELETE"}).then(()=>{this.emit("DELETE",t)})}list(t){const i=("/api/static/"+t).replaceAll("//","/");return this.api.request({url:i}).then((e)=>{return this.emit("LIST",t,e),e})}upload(t,i="/"){const e=new FormData;return(Array.isArray(t)?t:[t]).forEach((n)=>e.append("file",n)),this.api.request({url:"/api/static"+i,body:e}).then((n)=>{return this.emit("UPLOAD",n),n})}}class Jt extends h{api;actions;auth;data;email;groups;logger;pdf;settings;socket;static;storage;users;constructor(t,i){super();if(this.api=new p(t,i?.api),this.actions=new it(this.api),this.auth=new et(this.api,{persist:i?.persist??!0,loginUi:i?.loginUi}),this.data=new nt(this.api),this.email=new st(this.api),this.groups=new ot(this.api),this.logger=new at(this.api,i?.logLevel),this.pdf=new ut(this.api),this.settings=new lt(this.api),this.static=new rt(this.api),this.storage=new ht(this.api),this.users=new pt(this.api),i?.socket)this.socket=new V(this.api);this.api.on("*",(e,...n)=>this.emit(`API::${e}`,...n)),this.actions.on("*",(e,...n)=>this.emit(`ACTIONS::${e}`,...n)),this.auth.on("*",(e,...n)=>this.emit(`AUTH::${e}`,...n)),this.data.on("*",(e,...n)=>this.emit(`DATA::${e}`,...n)),this.email.on("*",(e,...n)=>this.emit(`EMAIL::${e}`,...n)),this.groups.on("*",(e,...n)=>this.emit(`GROUPS::${e}`,...n)),this.pdf.on("*",(e,...n)=>this.emit(`PDF::${e}`,...n)),this.settings.on("*",(e,...n)=>this.emit(`SETTINGS::${e}`,...n)),this.static.on("*",(e,...n)=>this.emit(`STATIC::${e}`,...n)),this.storage.on("*",(e,...n)=>this.emit(`STORAGE::${e}`,...n)),this.users.on("*",(e,...n)=>this.emit(`USERS::${e}`,...n)),this.users.on("*",(e,...n)=>{if(Array.isArray(n[0])){const s=n[0].find((o)=>o._id==this.auth.user?._id);if(s)this.auth.user=s}else if(n[0]._id==this.auth.user?._id)this.auth.user=n[0]})}}export{pt as Users,Ut as Totp,ht as Storage,rt as Static,V as Socket,lt as Settings,ut as Pdf,Jt as Momentum,at as Logger,ot as Groups,st as Email,nt as Data,et as Auth,p as Api,it as Actions,Qt as ActionType};
1
+ var B=function(t,i=!1){if(t==null)throw new Error("Cannot clean a NULL value");return Array.isArray(t)?t=t.filter((e)=>e!=null):Object.entries(t).forEach(([e,n])=>{(i&&n===void 0||!i&&n==null)&&delete t[e]}),t};var Q=function(t,i){const e=typeof t,n=typeof i;return e!="object"||t==null||n!="object"||i==null?e=="function"&&n=="function"?t.toString()==i.toString():t===i:Object.keys(t).length!=Object.keys(i).length?!1:Object.keys(t).every((s)=>Q(t[s],i[s]))};var x=function(t,i){const e=document.createElement("a");e.href=t,e.download=i,document.body.appendChild(e),e.click(),document.body.removeChild(e)};var St=Object.defineProperty,Mt=(t,i,e)=>(i in t)?St(t,i,{enumerable:!0,configurable:!0,writable:!0,value:e}):t[i]=e,r=(t,i,e)=>(Mt(t,typeof i!="symbol"?i+"":i,e),e);class a{constructor(){r(this,"listeners",{})}static emit(t,...i){(this.listeners["*"]||[]).forEach((e)=>e(t,...i)),(this.listeners[t.toString()]||[]).forEach((e)=>e(...i))}static off(t,i){const e=t.toString();this.listeners[e]=(this.listeners[e]||[]).filter((n)=>n===i)}static on(t,i){var e;const n=t.toString();return this.listeners[n]||(this.listeners[n]=[]),(e=this.listeners[n])==null||e.push(i),()=>this.off(t,i)}static once(t,i){return new Promise((e)=>{const n=this.on(t,(...s)=>{e(s.length==1?s[0]:s),i&&i(...s),n()})})}emit(t,...i){(this.listeners["*"]||[]).forEach((e)=>e(t,...i)),(this.listeners[t]||[]).forEach((e)=>e(...i))}off(t,i){this.listeners[t]=(this.listeners[t]||[]).filter((e)=>e===i)}on(t,i){var e;return this.listeners[t]||(this.listeners[t]=[]),(e=this.listeners[t])==null||e.push(i),()=>this.off(t,i)}once(t,i){return new Promise((e)=>{const n=this.on(t,(...s)=>{e(s.length==1?s[0]:s),i&&i(...s),n()})})}}r(a,"listeners",{});class w extends Error{constructor(t,i){super(t);r(this,"_code"),i!=null&&(this._code=i)}get code(){return this._code||this.constructor.code}set code(t){this._code=t}static from(t){const i=Number(t.statusCode)??Number(t.code),e=new this(t.message||t.toString());return Object.assign(e,{stack:t.stack,...t,code:i??void 0})}static instanceof(t){return t.constructor.code!=null}toString(){return this.message||super.toString()}}r(w,"code",500);class yt extends w{constructor(t="Bad Request"){super(t)}static instanceof(t){return t.constructor.code==this.code}}r(yt,"code",400);class mt extends w{constructor(t="Unauthorized"){super(t)}static instanceof(t){return t.constructor.code==this.code}}r(mt,"code",401);class ct extends w{constructor(t="Forbidden"){super(t)}static instanceof(t){return t.constructor.code==this.code}}r(ct,"code",403);class dt extends w{constructor(t="Not Found"){super(t)}static instanceof(t){return t.constructor.code==this.code}}r(dt,"code",404);class gt extends w{constructor(t="Internal Server Error"){super(t)}static instanceof(t){return t.constructor.code==this.code}}r(gt,"code",500);var U={CLEAR:"\x1B[0m",BRIGHT:"\x1B[1m",DIM:"\x1B[2m",UNDERSCORE:"\x1B[4m",BLINK:"\x1B[5m",REVERSE:"\x1B[7m",HIDDEN:"\x1B[8m"},k={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 P=((t)=>(t[t.ERROR=0]="ERROR",t[t.WARN=1]="WARN",t[t.INFO=2]="INFO",t[t.LOG=3]="LOG",t[t.DEBUG=4]="DEBUG",t))(P||{}),kt=class t extends a{constructor(i){super(),this.namespace=i}pad(i,e,n,s=!1){const o=i.toString(),u=e-o.length;if(u<=0)return o;const h=Array(~~(u/n.length)).fill(n).join("");return s?o+h:h+o}format(...i){const e=new Date;return`${`${e.getFullYear()}-${e.getMonth()+1}-${e.getDate()} ${this.pad(e.getHours().toString(),2,"0")}:${this.pad(e.getMinutes().toString(),2,"0")}:${this.pad(e.getSeconds().toString(),2,"0")}.${this.pad(e.getMilliseconds().toString(),3,"0",!0)}`}${this.namespace?` [${this.namespace}]`:""} ${i.join(" ")}`}debug(...i){if(t.LOG_LEVEL<4)return;const e=this.format(...i);t.emit(4,e),console.debug(k.LIGHT_GREY+e+U.CLEAR)}log(...i){if(t.LOG_LEVEL<3)return;const e=this.format(...i);t.emit(3,e),console.log(U.CLEAR+e)}info(...i){if(t.LOG_LEVEL<2)return;const e=this.format(...i);t.emit(2,e),console.info(k.BLUE+e+U.CLEAR)}warn(...i){if(t.LOG_LEVEL<1)return;const e=this.format(...i);t.emit(1,e),console.warn(k.YELLOW+e+U.CLEAR)}error(...i){if(t.LOG_LEVEL<0)return;const e=this.format(...i);t.emit(0,e),console.error(k.RED+e+U.CLEAR)}};r(kt,"LOG_LEVEL",4);var xt="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",Wt="0123456789",Ht="~`!@#$%^&*()_-+={[}]|\\:;\"'<,>.?/",Ct=xt+Wt+Ht;class J extends Promise{constructor(t){super((i,e)=>t((n)=>i(n),(n)=>e(n),(n)=>this.progress=n));r(this,"listeners",[]),r(this,"_progress",0)}get progress(){return this._progress}set progress(t){t!=this._progress&&(this._progress=t,this.listeners.forEach((i)=>i(t)))}onProgress(t){return this.listeners.push(t),this}}var X=class t{constructor(i={}){r(this,"interceptors",{}),r(this,"headers",{}),this.opts=i,this.headers=i.headers||{},i.interceptors&&i.interceptors.forEach((e)=>t.addInterceptor(e))}static addInterceptor(i){const e=Object.keys(t.interceptors).length.toString();return t.interceptors[e]=i,()=>{t.interceptors[e]=null}}addInterceptor(i){const e=Object.keys(this.interceptors).length.toString();return this.interceptors[e]=i,()=>{this.interceptors[e]=null}}async request(i={}){var e,n;if(!this.opts.url&&!i.url)throw new Error("URL needs to be set");let s=((e=i.url)!=null&&e.startsWith("http")?i.url:(this.opts.url||"")+(i.url||"")).replace(/([^:]\/)\/+/g,"$1");if(i.fragment&&(s.includes("#")?s.replace(/#.*(\?|\n)/g,(u,h)=>`#${i.fragment}${h}`):s+="#"+i.fragment),i.query){const u=Array.isArray(i.query)?i.query:Object.keys(i.query).map((h)=>({key:h,value:i.query[h]}));s+=(s.includes("?")?"&":"?")+u.map((h)=>`${h.key}=${h.value}`).join("&")}const o=B({"Content-Type":i.body&&!(i.body instanceof FormData)?"application/json":void 0,...t.headers,...this.headers,...i.headers});return fetch(s,{headers:o,method:i.method||(i.body?"POST":"GET"),body:(n=o["Content-Type"])!=null&&n.startsWith("application/json")&&i.body?JSON.stringify(i.body):i.body}).then(async(u)=>{for(let l of[...Object.values(t.interceptors),...Object.values(this.interceptors)])await new Promise((m)=>l(u,()=>m()));const h=await(async()=>{var l,m;return!i.skipConverting&&((l=u.headers.get("Content-Type"))!=null&&l.startsWith("application/json"))?await u.json():!i.skipConverting&&((m=u.headers.get("Content-Type"))!=null&&m.startsWith("text/plain"))?await u.text():u})();if(u.ok)return h;throw Object.assign(new Error(typeof h=="string"?h:u.statusText),typeof h=="object"?h:{})})}};r(X,"interceptors",{}),r(X,"headers",{});var Et=X;class p extends Et{t;i;emitter=new a;_token=null;get token(){return this._token}set token(t){if(t==this._token)return;this._token=t,this.headers.Authorization=t?`Bearer ${t}`:void 0,this.emit("TOKEN",t)}constructor(t=location.origin,i={}){i.url=t;super(i);this.url=t;this.opts=i}emit=this.emitter.emit.bind(this.emitter);off=this.emitter.off.bind(this.emitter);on=this.emitter.on.bind(this.emitter);once=this.emitter.once.bind(this.emitter);request(t){const i=super.request(t).then((e)=>{return this.emit("RESPONSE",e,t),e}).catch((e)=>{throw this.emit("REJECTED",e,t),e});return this.emit("REQUEST",i,t),i}}function T(t,i){if(typeof i!=="function"&&i!==null)throw new TypeError("Class extends value "+String(i)+" is not a constructor or null");C(t,i);function e(){this.constructor=t}t.prototype=i===null?Object.create(i):(e.prototype=i.prototype,new e)}function S(t){var i=typeof Symbol==="function"&&Symbol.iterator,e=i&&t[i],n=0;if(e)return e.call(t);if(t&&typeof t.length==="number")return{next:function(){if(t&&n>=t.length)t=void 0;return{value:t&&t[n++],done:!t}}};throw new TypeError(i?"Object is not iterable.":"Symbol.iterator is not defined.")}function L(t,i){var e=typeof Symbol==="function"&&t[Symbol.iterator];if(!e)return t;var n=e.call(t),s,o=[],u;try{while((i===void 0||i-- >0)&&!(s=n.next()).done)o.push(s.value)}catch(h){u={error:h}}finally{try{if(s&&!s.done&&(e=n.return))e.call(n)}finally{if(u)throw u.error}}return o}function R(t,i,e){if(e||arguments.length===2){for(var n=0,s=i.length,o;n<s;n++)if(o||!(n in i)){if(!o)o=Array.prototype.slice.call(i,0,n);o[n]=i[n]}}return t.concat(o||Array.prototype.slice.call(i))}var C=function(t,i){return C=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,n){e.__proto__=n}||function(e,n){for(var s in n)if(Object.prototype.hasOwnProperty.call(n,s))e[s]=n[s]},C(t,i)};function y(t){return typeof t==="function"}function W(t){var i=function(n){Error.call(n),n.stack=new Error().stack},e=t(i);return e.prototype=Object.create(Error.prototype),e.prototype.constructor=e,e}var H=W(function(t){return function i(e){t(this),this.message=e?e.length+" errors occurred during unsubscription:\n"+e.map(function(n,s){return s+1+") "+n.toString()}).join("\n "):"",this.name="UnsubscriptionError",this.errors=e}});function M(t,i){if(t){var e=t.indexOf(i);0<=e&&t.splice(e,1)}}function F(t){return t instanceof $||t&&"closed"in t&&y(t.remove)&&y(t.add)&&y(t.unsubscribe)}var Tt=function(t){if(y(t))t();else t.unsubscribe()},$=function(){function t(i){this.initialTeardown=i,this.closed=!1,this._parentage=null,this._finalizers=null}return t.prototype.unsubscribe=function(){var i,e,n,s,o;if(!this.closed){this.closed=!0;var u=this._parentage;if(u)if(this._parentage=null,Array.isArray(u))try{for(var h=S(u),l=h.next();!l.done;l=h.next()){var m=l.value;m.remove(this)}}catch(f){i={error:f}}finally{try{if(l&&!l.done&&(e=h.return))e.call(h)}finally{if(i)throw i.error}}else u.remove(this);var I=this.initialTeardown;if(y(I))try{I()}catch(f){o=f instanceof H?f.errors:[f]}var G=this._finalizers;if(G){this._finalizers=null;try{for(var A=S(G),g=A.next();!g.done;g=A.next()){var E=g.value;try{Tt(E)}catch(f){if(o=o!==null&&o!==void 0?o:[],f instanceof H)o=R(R([],L(o)),L(f.errors));else o.push(f)}}}catch(f){n={error:f}}finally{try{if(g&&!g.done&&(s=A.return))s.call(A)}finally{if(n)throw n.error}}}if(o)throw new H(o)}},t.prototype.add=function(i){var e;if(i&&i!==this)if(this.closed)Tt(i);else{if(i instanceof t){if(i.closed||i._hasParent(this))return;i._addParent(this)}(this._finalizers=(e=this._finalizers)!==null&&e!==void 0?e:[]).push(i)}},t.prototype._hasParent=function(i){var e=this._parentage;return e===i||Array.isArray(e)&&e.includes(i)},t.prototype._addParent=function(i){var e=this._parentage;this._parentage=Array.isArray(e)?(e.push(i),e):e?[e,i]:i},t.prototype._removeParent=function(i){var e=this._parentage;if(e===i)this._parentage=null;else if(Array.isArray(e))M(e,i)},t.prototype.remove=function(i){var e=this._finalizers;if(e&&M(e,i),i instanceof t)i._removeParent(this)},t.EMPTY=function(){var i=new t;return i.closed=!0,i}(),t}();var Z=$.EMPTY;var c={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1};var O={setTimeout:function(t,i){var e=[];for(var n=2;n<arguments.length;n++)e[n-2]=arguments[n];var s=O.delegate;if(s===null||s===void 0?void 0:s.setTimeout)return s.setTimeout.apply(s,R([t,i],L(e)));return setTimeout.apply(void 0,R([t,i],L(e)))},clearTimeout:function(t){var i=O.delegate;return((i===null||i===void 0?void 0:i.clearTimeout)||clearTimeout)(t)},delegate:void 0};function At(t){O.setTimeout(function(){var i=c.onUnhandledError;if(i)i(t);else throw t})}function Y(){}function Pt(t){return v("E",void 0,t)}function Dt(t){return v("N",t,void 0)}function v(t,i,e){return{kind:t,value:i,error:e}}var wt=function(){return v("C",void 0,void 0)}();function q(t){if(c.useDeprecatedSynchronousErrorHandling){var i=!D;if(i)D={errorThrown:!1,error:null};if(t(),i){var e=D,n=e.errorThrown,s=e.error;if(D=null,n)throw s}}else t()}function Lt(t){if(c.useDeprecatedSynchronousErrorHandling&&D)D.errorThrown=!0,D.error=t}var D=null;var j=function(t,i){return Ft.call(t,i)},K=function(t){if(c.useDeprecatedSynchronousErrorHandling)Lt(t);else At(t)},Nt=function(t){throw t},z=function(t,i){var e=c.onStoppedNotification;e&&O.setTimeout(function(){return e(t,i)})},b=function(t){T(i,t);function i(e){var n=t.call(this)||this;if(n.isStopped=!1,e){if(n.destination=e,F(e))e.add(n)}else n.destination=Vt;return n}return i.create=function(e,n,s){return new N(e,n,s)},i.prototype.next=function(e){if(this.isStopped)z(Dt(e),this);else this._next(e)},i.prototype.error=function(e){if(this.isStopped)z(Pt(e),this);else this.isStopped=!0,this._error(e)},i.prototype.complete=function(){if(this.isStopped)z(wt,this);else this.isStopped=!0,this._complete()},i.prototype.unsubscribe=function(){if(!this.closed)this.isStopped=!0,t.prototype.unsubscribe.call(this),this.destination=null},i.prototype._next=function(e){this.destination.next(e)},i.prototype._error=function(e){try{this.destination.error(e)}finally{this.unsubscribe()}},i.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},i}($);var Ft=Function.prototype.bind,Kt=function(){function t(i){this.partialObserver=i}return t.prototype.next=function(i){var e=this.partialObserver;if(e.next)try{e.next(i)}catch(n){K(n)}},t.prototype.error=function(i){var e=this.partialObserver;if(e.error)try{e.error(i)}catch(n){K(n)}else K(i)},t.prototype.complete=function(){var i=this.partialObserver;if(i.complete)try{i.complete()}catch(e){K(e)}},t}(),N=function(t){T(i,t);function i(e,n,s){var o=t.call(this)||this,u;if(y(e)||!e)u={next:e!==null&&e!==void 0?e:void 0,error:n!==null&&n!==void 0?n:void 0,complete:s!==null&&s!==void 0?s:void 0};else{var h;if(o&&c.useDeprecatedNextContext)h=Object.create(e),h.unsubscribe=function(){return o.unsubscribe()},u={next:e.next&&j(e.next,h),error:e.error&&j(e.error,h),complete:e.complete&&j(e.complete,h)};else u=e}return o.destination=new Kt(u),o}return i}(b);var Vt={closed:!0,next:Y,error:Nt,complete:Y};var Rt=function(){return typeof Symbol==="function"&&Symbol.observable||"@@observable"}();function $t(t){return t}function Ot(t){if(t.length===0)return $t;if(t.length===1)return t[0];return function i(e){return t.reduce(function(n,s){return s(n)},e)}}var qt=function(t){var i;return(i=t!==null&&t!==void 0?t:c.Promise)!==null&&i!==void 0?i:Promise},Xt=function(t){return t&&y(t.next)&&y(t.error)&&y(t.complete)},Bt=function(t){return t&&t instanceof b||Xt(t)&&F(t)},_=function(){function t(i){if(i)this._subscribe=i}return t.prototype.lift=function(i){var e=new t;return e.source=this,e.operator=i,e},t.prototype.subscribe=function(i,e,n){var s=this,o=Bt(i)?i:new N(i,e,n);return q(function(){var u=s,h=u.operator,l=u.source;o.add(h?h.call(o,l):l?s._subscribe(o):s._trySubscribe(o))}),o},t.prototype._trySubscribe=function(i){try{return this._subscribe(i)}catch(e){i.error(e)}},t.prototype.forEach=function(i,e){var n=this;return e=qt(e),new e(function(s,o){var u=new N({next:function(h){try{i(h)}catch(l){o(l),u.unsubscribe()}},error:o,complete:s});n.subscribe(u)})},t.prototype._subscribe=function(i){var e;return(e=this.source)===null||e===void 0?void 0:e.subscribe(i)},t.prototype[Rt]=function(){return this},t.prototype.pipe=function(){var i=[];for(var e=0;e<arguments.length;e++)i[e]=arguments[e];return Ot(i)(this)},t.prototype.toPromise=function(i){var e=this;return i=qt(i),new i(function(n,s){var o;e.subscribe(function(u){return o=u},function(u){return s(u)},function(){return n(o)})})},t.create=function(i){return new t(i)},t}();var It=W(function(t){return function i(){t(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}});var tt=function(t){T(i,t);function i(){var e=t.call(this)||this;return e.closed=!1,e.currentObservers=null,e.observers=[],e.isStopped=!1,e.hasError=!1,e.thrownError=null,e}return i.prototype.lift=function(e){var n=new Gt(this,this);return n.operator=e,n},i.prototype._throwIfClosed=function(){if(this.closed)throw new It},i.prototype.next=function(e){var n=this;q(function(){var s,o;if(n._throwIfClosed(),!n.isStopped){if(!n.currentObservers)n.currentObservers=Array.from(n.observers);try{for(var u=S(n.currentObservers),h=u.next();!h.done;h=u.next()){var l=h.value;l.next(e)}}catch(m){s={error:m}}finally{try{if(h&&!h.done&&(o=u.return))o.call(u)}finally{if(s)throw s.error}}}})},i.prototype.error=function(e){var n=this;q(function(){if(n._throwIfClosed(),!n.isStopped){n.hasError=n.isStopped=!0,n.thrownError=e;var s=n.observers;while(s.length)s.shift().error(e)}})},i.prototype.complete=function(){var e=this;q(function(){if(e._throwIfClosed(),!e.isStopped){e.isStopped=!0;var n=e.observers;while(n.length)n.shift().complete()}})},i.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(i.prototype,"observed",{get:function(){var e;return((e=this.observers)===null||e===void 0?void 0:e.length)>0},enumerable:!1,configurable:!0}),i.prototype._trySubscribe=function(e){return this._throwIfClosed(),t.prototype._trySubscribe.call(this,e)},i.prototype._subscribe=function(e){return this._throwIfClosed(),this._checkFinalizedStatuses(e),this._innerSubscribe(e)},i.prototype._innerSubscribe=function(e){var n=this,s=this,o=s.hasError,u=s.isStopped,h=s.observers;if(o||u)return Z;return this.currentObservers=null,h.push(e),new $(function(){n.currentObservers=null,M(h,e)})},i.prototype._checkFinalizedStatuses=function(e){var n=this,s=n.hasError,o=n.thrownError,u=n.isStopped;if(s)e.error(o);else if(u)e.complete()},i.prototype.asObservable=function(){var e=new _;return e.source=this,e},i.create=function(e,n){return new Gt(e,n)},i}(_);var Gt=function(t){T(i,t);function i(e,n){var s=t.call(this)||this;return s.destination=e,s.source=n,s}return i.prototype.next=function(e){var n,s;(s=(n=this.destination)===null||n===void 0?void 0:n.next)===null||s===void 0||s.call(n,e)},i.prototype.error=function(e){var n,s;(s=(n=this.destination)===null||n===void 0?void 0:n.error)===null||s===void 0||s.call(n,e)},i.prototype.complete=function(){var e,n;(n=(e=this.destination)===null||e===void 0?void 0:e.complete)===null||n===void 0||n.call(e)},i.prototype._subscribe=function(e){var n,s;return(s=(n=this.source)===null||n===void 0?void 0:n.subscribe(e))!==null&&s!==void 0?s:Z},i}(tt);var d=function(t){T(i,t);function i(e){var n=t.call(this)||this;return n._value=e,n}return Object.defineProperty(i.prototype,"value",{get:function(){return this.getValue()},enumerable:!1,configurable:!0}),i.prototype._subscribe=function(e){var n=t.prototype._subscribe.call(this,e);return!n.closed&&e.next(this._value),n},i.prototype.getValue=function(){var e=this,n=e.hasError,s=e.thrownError,o=e._value;if(n)throw s;return this._throwIfClosed(),o},i.prototype.next=function(e){t.prototype.next.call(this,this._value=e)},i}(tt);var Qt;((h)=>{h[h.CRON=0]="CRON";h[h.EVENT=1]="EVENT";h[h.DELETE=2]="DELETE";h[h.GET=3]="GET";h[h.PATCH=4]="PATCH";h[h.POST=5]="POST";h[h.PUT=6]="PUT"})(Qt||={});class it extends a{api;$cache=new d([]);get cache(){return this.$cache.value}set cache(t){this.$cache.next(t)}constructor(t){super();this.api=typeof t=="string"?new p(t):t}delete(t){return this.api.request({url:`/api/actions/${t}`,method:"DELETE"}).then(()=>{this.cache=this.cache.filter((i)=>i._id!=t),this.emit("DELETE",t)})}list(){return this.api.request({url:"/api/actions"}).then((t)=>{return this.cache=t,this.emit("LIST",t),t})}read(t,i=!1){const e=this.cache.find((n)=>n._id==t);if(!i&&e)return Promise.resolve(e);return this.api.request({url:`/api/actions/${t}`}).then((n)=>{if(n)this.cache=this.cache.filter((s)=>s._id!=t).concat([n]);return this.emit("READ",n),n})}run(t,i={}){return this.api.request({url:("/api/actions/run/"+t).replaceAll("//","/"),...i})}runById(t,i={}){const e=typeof t=="string"?t:t._id;return this.api.request({url:"/api/actions/run-by-id/"+e,method:"POST",...i})}update(t){return this.api.request({url:`/api/actions${t._id?`/${t._id}`:""}`,method:"POST",body:t}).then((i)=>{if(i)this.cache=this.cache.filter((e)=>e._id!=i._id).concat([i]);return this.emit("UPDATE",i),i})}}class Ut{t;constructor(t){this.api=t}disable(t){return this.api.request({url:`/api/auth/totp/${t}`,method:"DELETE"})}enable=this.reset;reset(t){return this.api.request({url:`/api/auth/totp/${t}`,method:"POST"})}setup(t,i="app",e){return this.api.request({url:`/api/auth/totp/${t}`,body:B({method:i,totp:e})})}}class et extends a{i;api;storageKey;totp;$user=new d(void 0);get user(){return this.$user.value}set user(t){if(!Q(this.user,t)){const i=t?t:null;this.$user.next(i),this.emit("USER",i)}}constructor(t,i){super();this.opts=i;if(this.api=typeof t=="string"?new p(t):t,this.totp=new Ut(this.api),!this.opts?.loginUi)this.opts={...this.opts,loginUi:this.api.url+"/ui/login"};if(this.storageKey=`momentum:${new URL(this.api.url).host}`,this.api.addInterceptor((e,n)=>{const s=["/api/auth/login","/api/auth/password","/api/auth/totp"];if(e.status==401&&!s.find((o)=>e.url.includes(o)))this.emit("SESSION_EXPIRED");n()}),this.api.on("TOKEN",(e)=>{if(this.opts?.persist)if(e)localStorage.setItem(this.storageKey,e);else localStorage.removeItem(this.storageKey);if(e)this.session(e,!0).catch(()=>{});else this.user=null}),i?.persist){const e=localStorage.getItem(this.storageKey);if(e)this.api.token=e;else this.user=null}else this.user=null}knownHost(t=location.origin){if(t.startsWith("/"))return Promise.resolve();return this.api.request({url:`/api/auth/known-host?host=${encodeURI(new URL(t).origin)}`})}login(t,i,e){return this.api.request({url:"/api/auth/login",headers:{Authorization:void 0},body:{username:t.trim(),password:i.trim(),totp:e}}).then(async(n)=>{return this.api.token=n.token,await this.once("USER")})}loginRedirect(t=location.origin){return new Promise((i,e)=>{const n=window.open(encodeURI(`${this.opts?.loginUi}?redirect=postmessage&host=${t}`),"_blank");if(!n)return e("Unable to open login");n.addEventListener("message",(s)=>{if(!s?.data?.token)return e("Unknown response from login");this.api.token=s.data.token,i(s.data.token),n.close()})})}logout(){this.api.token=null,this.user=null,this.emit("LOGOUT")}async register(t){const i=await this.api.request({url:"/api/auth/register",body:{...t}});if(i.image.startsWith("/"))i.image=`${this.api.url}${i.image}?token=${this.api.token}`;return this.emit("REGISTER",i),i}reset(t,i){return this.api.request({url:"/api/auth/reset",headers:{Authorization:i?`Bearer ${i}`:void 0},body:{email:i?void 0:t,password:i?t:void 0}})}async session(t,i=!1){if(!t)t=this.api.token;const e=await this.api.request({url:"/api/auth/session",headers:t?{Authorization:`Bearer ${t}`}:void 0});if(i){if(this.api.token=t,e?.user)e.user.image=`${this.api.url}${e.user.image}?token=${this.api.token}`;if(this.user=e?.user||null,e)this.emit("LOGIN",e.user)}return e}async updatePassword(t,i,e){return this.api.request({url:"/api/auth/password",body:{username:t,password:i,oldPassword:e}}).then((n)=>{if(n?.token)this.api.token=n.token})}}class nt extends a{api;constructor(t){super();this.api=typeof t=="string"?new p(t):t}delete(t,i){return this.api.request({url:`/api/data/${t}/${i}`,method:"DELETE"}).then(()=>this.emit("DELETE",t,i))}get(t,i){return this.api.request({url:`/api/data/${t}${i?`/${i}`:""}`}).then((e)=>{return this.emit("GET",t,e),e})}raw(t,i,e,n){return this.api.request({url:`/api/data/${t}`,body:{operand:i,query:e,options:n}}).then((s)=>{return this.emit("RAW",t,s),s})}set(t,i,e=!1){return this.api.request({url:`/api/data/${t}/${i._id||""}`,method:e?"PATCH":"POST",body:i}).then((n)=>{return this.emit("SET",t,i),n})}}class st extends a{api;constructor(t){super();this.api=typeof t=="string"?new p(t):t}send(t){let i="/api/email";if(typeof t.body=="object")i+=`/${t.body.template}`;return this.api.request({url:i,body:t}).then((e)=>{return this.emit("SENT",t),e})}}class ot extends a{api;constructor(t){super();this.api=typeof t=="string"?new p(t):t}create(t){return this.api.request({url:`/api/groups/${t.name}`,method:"POST",body:t}).then((i)=>{return this.emit("CREATE",i),i})}list(){return this.api.request({url:"/api/groups"}).then((t)=>{return this.emit("LIST",t),t})}read(t){return this.api.request({url:`/api/groups/${t}`}).then((i)=>{return this.emit("READ",i),i})}update(t){return this.api.request({url:`/api/groups/${t.name}`,method:"PATCH",body:t}).then((i)=>{return this.emit("UPDATE",i),i})}delete(t){return this.api.request({url:`/api/groups/${t}`,method:"DELETE"}).then(()=>this.emit("DELETE",t))}}class ut{api;constructor(t,i){if(this.api=typeof t=="string"?new p(t):t,i!=null&&i!="NONE")window.addEventListener("error",(e)=>this.error(e.error.stack)),window.addEventListener("unhandledrejection",async(e)=>this.error(e.reason.stack))}buildLog(t,i){return{time:(new Date()).getTime(),level:t,log:i,ctx:{cores:navigator.hardwareConcurrency,mem: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(t,i){const e=[t?`length=${t}`:void 0,i?`page=${i}`:void 0].filter((n)=>!!n).join("&");return this.api.request({url:`/api/logs/client${e?`?${e}`:""}`})}serverLogs(t,i){const e=[t?`length=${t}`:void 0,i?`page=${i}`:void 0].filter((n)=>!!n).join("&");return this.api.request({url:`/api/logs/server${e?`?${e}`:""}`})}debug(...t){return this.api.request({url:"/api/logs/client",body:this.buildLog(P.DEBUG,t)}).catch(()=>{})}log(...t){return this.api.request({url:"/api/logs/client",body:this.buildLog(P.LOG,t)}).catch(()=>{})}info(...t){return this.api.request({url:"/api/logs/client",body:this.buildLog(P.INFO,t)}).catch(()=>{})}warn(...t){return this.api.request({url:"/api/logs/client",body:this.buildLog(P.WARN,t)}).catch(()=>{})}error(...t){return this.api.request({url:"/api/logs/client",body:this.buildLog(P.ERROR,t)}).catch(()=>{})}}class ht extends a{api;constructor(t){super();this.api=typeof t=="string"?new p(t):t}async handleResponse(t,i){const e=await t.blob();if(i){const n=URL.createObjectURL(e);x(n,i.endsWith(".pdf")?i:i+".pdf"),URL.revokeObjectURL(n)}return this.emit("CREATE",e),e}fromHtml(t,i={}){return this.api.request({url:"/api/pdf",body:{html:t}}).then((e)=>this.handleResponse(e,i.download?i.fileName||(new Date()).toISOString():void 0))}fromTemplate(t,i,e={}){return this.api.request({url:`/api/pdf${t}`,body:i}).then((n)=>this.handleResponse(n,e.download?e.fileName||(new Date()).toISOString():void 0))}fromUrl(t,i={}){return this.api.request({url:`/api/pdf?url=${t}`}).then((e)=>this.handleResponse(e,i.download?i.fileName||(new Date()).toISOString():void 0))}}class V{static timeout=1e4;api;url;connection;open=!1;constructor(t){if(this.api=typeof t=="string"?new p(t):t,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(t=3){if(this.connection?.readyState<2)this.connection.close();this.connection=new WebSocket(this.url+(this.api.token?`?token=${this.api.token}`:""));const i=setTimeout(()=>{if(this.open)return;if(this.connection.close(),console.error("Momentum connection timeout"),t>0)this.connect(t-1)},V.timeout);this.connection.onclose=()=>this.open=!1,this.connection.onmessage=this.handle,this.connection.onopen=()=>{this.open=!0,clearTimeout(i),console.debug("Connected to Momentum")}}handle(...t){console.log(t)}send(t,i){this.connection.send(JSON.stringify({token:this.api.token,channel:t,payload:i}))}}class at extends a{api;constructor(t){super();this.api=typeof t=="string"?new p(t):t}delete(t){const i=(t.startsWith("/api/storage/")?t:"/api/storage/"+t).replaceAll("//","/");return this.api.request({url:i,method:"DELETE"}).then(()=>{this.emit("DELETE",i)})}list(t){const i=(t.startsWith("/api/storage/")?t:"/api/storage/"+t).replaceAll("//","/");return this.api.request({url:i+"?list"}).then((e)=>{return this.emit("LIST",t,e),e})}open(t,i="_blank"){const e=(t.startsWith("/api/storage/")?t:"/api/storage/"+t).replaceAll(/\/{2,}/g,"/"),n=`${this.api.url}${e}${this.api.token?`?token=${this.api.token}`:""}`;if(!i)return n;return this.emit("OPEN",t),window.open(n,i)}mkdir(t){const i=(t.startsWith("/api/storage/")?t:"/api/storage/"+t).replaceAll(/\/{2,}/g,"/");return this.api.request({url:i+"?directory",method:"POST"})}download(t,i={}){return new J((e,n,s)=>{const o=("/api/storage/"+t).replaceAll("//","/");this.api.request({...i,url:o,skipConverting:!0}).then((u)=>{if(!u.ok)return n(u.statusText);const h=u.headers.get("Content-Length"),l=h?parseInt(h,10):0;let m=[],I=0;const G=u.body?.getReader(),A=(g)=>{if(g.done){s(1);const E=new Blob(m),f=i.downloadAs||new URL(u.url).pathname.split("/").pop(),ft=URL.createObjectURL(E);x(ft,f.includes(".")?f:f+".zip"),URL.revokeObjectURL(ft),this.emit("DOWNLOAD",t,E),e(E)}else{const E=g.value;m.push(E),I+=E.length,s(I/l),G.read().then(A)}};G?.read().then(A)})})}async upload(t,i=""){const e=()=>{return new Promise((o)=>{const u=document.createElement("input");u.type="file",u.accept=i?.accept||"*",u.style.display="none",u.multiple=!!i?.multiple,u.onblur=u.onchange=async()=>{o(Array.from(u.files)),u.remove()},document.body.appendChild(u),u.click()})};if(!t)t=await e();if(!t||Array.isArray(t)&&!t.length)return[];const n=new FormData,s=("/api/storage/"+(typeof i=="string"?i:i?.path)).replaceAll("//","/");return(Array.isArray(t)?t:[t]).forEach((o)=>n.append("file",o)),this.api.request({url:s,body:n}).then((o)=>{return this.emit("UPLOAD",o),o})}}class pt extends a{api;listed=!1;$cache=new d([]);get cache(){return this.$cache.value}set cache(t){this.$cache.next(t)}constructor(t){super();this.api=typeof t=="string"?new p(t):t}delete(t){return this.api.request({url:`/api/users/${t}`,method:"DELETE"}).then(()=>{this.cache=this.cache.filter((i)=>i.username!=t),this.emit("DELETE",t)})}list(t=!1){if(!t&&this.listed)return Promise.resolve(this.cache);return this.api.request({url:"/api/users"}).then((i)=>{return i.map((e)=>{return e.image=this.api.url+e.image+`?token=${this.api.token}`,e}),this.cache=i,this.listed=!0,this.emit("LIST",i),i})}read(t,i=!1){if(!i){const e=this.cache.find((n)=>n.username==t);if(e)return Promise.resolve(e)}return this.api.request({url:`/api/users/${t}`}).then((e)=>{if(e.image=this.api.url+e.image+`?token=${this.api.token}`,e)this.cache=[...this.cache.filter((n)=>n.username!=t),e];return this.emit("READ",e),e})}update(t){return this.api.request({url:`/api/users/${t.username}`,method:"PATCH",body:t}).then((i)=>{if(i.image=this.api.url+i.image+`?token=${this.api.token}`,i)this.cache=this.cache.filter((e)=>e.username!=t.username).concat([i]);return this.emit("UPDATE",i),i})}uploadImage(t,i){const e=new FormData;return e.append("file",i),this.api.request({url:`/api/users/${t}/image`,body:e}).then((n)=>{return this.emit("UPLOAD_IMAGE",i),n})}}class lt extends a{api;$cache=new d({});get cache(){return this.$cache.value}set cache(t){this.$cache.next(t)}constructor(t){super();this.api=typeof t=="string"?new p(t):t}list(t=!1){return this.api.request({url:"/api/settings"+(t?"?detailed":"")}).then((i)=>{return this.cache=!t?i:Object.values(i).reduce((e,n)=>({...e,[n.key]:n.value}),{}),this.emit("LIST",i),i})}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,i=!1){if(!i&&this.cache[t])return Promise.resolve(this.cache[t]);return this.api.request({url:`/api/settings/${t}`}).then((e)=>{if(e)this.cache={...this.cache,[e.key]:e};return this.emit("READ",e),e})}update(t){return this.api.request({url:`/api/settings/${t.key}`,body:t}).then((i)=>{if(i)this.cache={...this.cache,[i.key]:i.value};return this.emit("UPDATE",i),i})}}class rt extends a{api;constructor(t){super();this.api=typeof t=="string"?new p(t):t}delete(t){return this.api.request({url:`/api/static/${t}`,method:"DELETE"}).then(()=>{this.emit("DELETE",t)})}list(t){const i=("/api/static/"+t).replaceAll("//","/");return this.api.request({url:i}).then((e)=>{return this.emit("LIST",t,e),e})}upload(t,i="/"){const e=new FormData;return(Array.isArray(t)?t:[t]).forEach((n)=>e.append("file",n)),this.api.request({url:"/api/static"+i,body:e}).then((n)=>{return this.emit("UPLOAD",n),n})}}class Jt extends a{api;actions;auth;data;email;groups;logger;pdf;settings;socket;static;storage;users;constructor(t,i){super();if(this.api=new p(t,i?.api),this.actions=new it(this.api),this.auth=new et(this.api,{persist:i?.persist??!0,loginUi:i?.loginUi}),this.data=new nt(this.api),this.email=new st(this.api),this.groups=new ot(this.api),this.logger=new ut(this.api,i?.logLevel),this.pdf=new ht(this.api),this.settings=new lt(this.api),this.static=new rt(this.api),this.storage=new at(this.api),this.users=new pt(this.api),i?.socket)this.socket=new V(this.api);this.api.on("*",(e,...n)=>this.emit(`API::${e}`,...n)),this.actions.on("*",(e,...n)=>this.emit(`ACTIONS::${e}`,...n)),this.auth.on("*",(e,...n)=>this.emit(`AUTH::${e}`,...n)),this.data.on("*",(e,...n)=>this.emit(`DATA::${e}`,...n)),this.email.on("*",(e,...n)=>this.emit(`EMAIL::${e}`,...n)),this.groups.on("*",(e,...n)=>this.emit(`GROUPS::${e}`,...n)),this.pdf.on("*",(e,...n)=>this.emit(`PDF::${e}`,...n)),this.settings.on("*",(e,...n)=>this.emit(`SETTINGS::${e}`,...n)),this.static.on("*",(e,...n)=>this.emit(`STATIC::${e}`,...n)),this.storage.on("*",(e,...n)=>this.emit(`STORAGE::${e}`,...n)),this.users.on("*",(e,...n)=>this.emit(`USERS::${e}`,...n)),this.users.on("*",(e,...n)=>{if(Array.isArray(n[0])){const s=n[0].find((o)=>o._id==this.auth.user?._id);if(s)this.auth.user=s}else if(n[0]._id==this.auth.user?._id)this.auth.user=n[0]})}}export{pt as Users,Ut as Totp,at as Storage,rt as Static,V as Socket,lt as Settings,ht as Pdf,Jt as Momentum,ut as Logger,ot as Groups,st as Email,nt as Data,et as Auth,p as Api,it as Actions,Qt as ActionType};
package/dist/pdf.d.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  import { Api } from './api';
2
2
  import { TypedEmitter, type TypedEvents } from '@ztimson/utils';
3
- export type PdfTemplate = {
4
- template: string;
5
- data: any;
3
+ export type PdfOptions = {
4
+ download?: boolean;
5
+ fileName?: string;
6
6
  };
7
7
  export type PdfEvents = TypedEvents & {
8
8
  CREATE: (pdf: Blob) => any;
@@ -11,13 +11,8 @@ export declare class Pdf extends TypedEmitter<PdfEvents> {
11
11
  private readonly api;
12
12
  constructor(api: Api | string);
13
13
  private handleResponse;
14
- generate(content: string | PdfTemplate, opts?: {
15
- download?: boolean;
16
- 'fileName'?: string;
17
- }): Promise<Blob>;
18
- fromUrl(url: string, opts?: {
19
- download?: boolean;
20
- 'fileName'?: string;
21
- }): Promise<Blob>;
14
+ fromHtml(content: string, opts?: PdfOptions): Promise<Blob>;
15
+ fromTemplate(template: string, data: object, opts?: PdfOptions): Promise<Blob>;
16
+ fromUrl(url: string, opts?: PdfOptions): Promise<Blob>;
22
17
  }
23
18
  //# sourceMappingURL=pdf.d.ts.map
package/dist/pdf.d.ts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"pdf.d.ts","sourceRoot":"","sources":["../src/pdf.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,GAAG,EAAC,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAW,YAAY,EAAE,KAAK,WAAW,EAAC,MAAM,gBAAgB,CAAC;AAExE,MAAM,MAAM,WAAW,GAAG;IAAC,QAAQ,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,GAAG,CAAA;CAAC,CAAC;AAExD,MAAM,MAAM,SAAS,GAAG,WAAW,GAAG;IACrC,MAAM,EAAE,CAAC,GAAG,EAAE,IAAI,KAAK,GAAG,CAAC;CAC3B,CAAA;AAED,qBAAa,GAAI,SAAQ,YAAY,CAAC,SAAS,CAAC;IAC/C,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAO;gBAEf,GAAG,EAAE,GAAG,GAAG,MAAM;YAKf,cAAc;IAW5B,QAAQ,CAAC,OAAO,EAAE,MAAM,GAAG,WAAW,EAAE,IAAI,GAAE;QAAC,QAAQ,CAAC,EAAE,OAAO,CAAC;QAAC,UAAU,CAAC,EAAE,MAAM,CAAA;KAAM;IAQ5F,OAAO,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,GAAE;QAAC,QAAQ,CAAC,EAAE,OAAO,CAAC;QAAC,UAAU,CAAC,EAAE,MAAM,CAAA;KAAM;CAIzE"}
1
+ {"version":3,"file":"pdf.d.ts","sourceRoot":"","sources":["../src/pdf.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,GAAG,EAAC,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAW,YAAY,EAAE,KAAK,WAAW,EAAC,MAAM,gBAAgB,CAAC;AAExE,MAAM,MAAM,UAAU,GAAG;IACxB,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,QAAQ,CAAC,EAAE,MAAM,CAAA;CACjB,CAAA;AAED,MAAM,MAAM,SAAS,GAAG,WAAW,GAAG;IACrC,MAAM,EAAE,CAAC,GAAG,EAAE,IAAI,KAAK,GAAG,CAAC;CAC3B,CAAA;AAED,qBAAa,GAAI,SAAQ,YAAY,CAAC,SAAS,CAAC;IAC/C,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAO;gBAEf,GAAG,EAAE,GAAG,GAAG,MAAM;YAKf,cAAc;IAW5B,QAAQ,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,GAAE,UAAe;IAK/C,YAAY,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,GAAE,UAAe;IAKlE,OAAO,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,GAAE,UAAe;CAI1C"}
package/dist/pdf.js CHANGED
@@ -19,12 +19,13 @@ class Pdf extends utils_1.TypedEmitter {
19
19
  this.emit('CREATE', blob);
20
20
  return blob;
21
21
  }
22
- generate(content, opts = {}) {
23
- const template = content?.template;
24
- return this.api.request({
25
- url: `/api/pdf${template ? `/${template}` : ''}`,
26
- body: template ? content?.data : { html: content }
27
- }).then((resp) => this.handleResponse(resp, opts.download ? (opts.fileName || new Date().toISOString()) : undefined));
22
+ fromHtml(content, opts = {}) {
23
+ return this.api.request({ url: `/api/pdf`, body: { html: content } })
24
+ .then((resp) => this.handleResponse(resp, opts.download ? (opts.fileName || new Date().toISOString()) : undefined));
25
+ }
26
+ fromTemplate(template, data, opts = {}) {
27
+ return this.api.request({ url: `/api/pdf${template}`, body: data })
28
+ .then((resp) => this.handleResponse(resp, opts.download ? (opts.fileName || new Date().toISOString()) : undefined));
28
29
  }
29
30
  fromUrl(url, opts = {}) {
30
31
  return this.api.request({ url: `/api/pdf?url=${url}` }).then((resp) => this.handleResponse(resp, opts.download ? (opts.fileName || new Date().toISOString()) : undefined));
@@ -1 +1 @@
1
- {"version":3,"file":"users.d.ts","sourceRoot":"","sources":["../src/users.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,GAAG,EAAC,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAC,YAAY,EAAE,KAAK,WAAW,EAAC,MAAM,gBAAgB,CAAC;AAC9D,OAAO,EAAC,eAAe,EAAC,MAAM,MAAM,CAAC;AACrC,OAAO,KAAK,EAAC,IAAI,EAAC,MAAM,QAAQ,CAAC;AAEjC,MAAM,MAAM,IAAI,GAAG,IAAI,GAAG;IACzB,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,MAAM,EAAE,MAAM,EAAE,CAAC;IACjB,WAAW,EAAE,MAAM,EAAE,CAAC;IACtB,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,CAAC,EAAE,GAAG,CAAC;IACb,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B,IAAI,CAAC,EAAE,KAAK,GAAG,KAAK,GAAG,OAAO,GAAG,OAAO,CAAC;CACzC,CAAA;AAED,MAAM,MAAM,UAAU,GAAG,WAAW,GAAG;IACtC,IAAI,EAAE,CAAC,KAAK,EAAE,IAAI,EAAE,KAAK,GAAG,CAAC;IAC7B,IAAI,EAAE,CAAC,IAAI,EAAE,IAAI,KAAK,GAAG,CAAC;IAC1B,MAAM,EAAE,CAAC,IAAI,EAAE,IAAI,KAAK,GAAG,CAAC;IAC5B,MAAM,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,GAAG,CAAC;IAClC,YAAY,EAAE,CAAC,IAAI,EAAE,IAAI,KAAK,GAAG,CAAC;CAClC,CAAC;AAEF,qBAAa,KAAM,SAAQ,YAAY,CAAC,UAAU,CAAC;IAClD,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAO;IAC3B,OAAO,CAAC,MAAM,CAAS;IAEvB,MAAM,0BAAkC;IACxC,IAAI,KAAK,WAAgC;IACzC,IAAI,KAAK,CAAC,GAAG,QAAA,EAA4B;gBAE7B,GAAG,EAAE,GAAG,GAAG,MAAM;IAK7B,MAAM,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAUvC,IAAI,CAAC,MAAM,UAAM,GAAG,OAAO,CAAC,IAAI,EAAE,CAAC;IAcnC,IAAI,CAAC,QAAQ,EAAE,MAAM,EAAE,MAAM,UAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAanD,MAAM,CAAC,IAAI,EAAE,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;IAajC,WAAW,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI;CAQxC"}
1
+ {"version":3,"file":"users.d.ts","sourceRoot":"","sources":["../src/users.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,GAAG,EAAC,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAC,YAAY,EAAE,KAAK,WAAW,EAAC,MAAM,gBAAgB,CAAC;AAC9D,OAAO,EAAC,eAAe,EAAC,MAAM,MAAM,CAAC;AACrC,OAAO,KAAK,EAAC,IAAI,EAAC,MAAM,QAAQ,CAAC;AAEjC,MAAM,MAAM,IAAI,GAAG,IAAI,GAAG;IACzB,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,MAAM,EAAE,MAAM,EAAE,CAAC;IACjB,WAAW,EAAE,MAAM,EAAE,CAAC;IACtB,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,CAAC,EAAE,GAAG,CAAC;IAGb,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B,IAAI,CAAC,EAAE,KAAK,GAAG,KAAK,GAAG,OAAO,GAAG,OAAO,CAAC;CACzC,CAAA;AAED,MAAM,MAAM,UAAU,GAAG,WAAW,GAAG;IACtC,IAAI,EAAE,CAAC,KAAK,EAAE,IAAI,EAAE,KAAK,GAAG,CAAC;IAC7B,IAAI,EAAE,CAAC,IAAI,EAAE,IAAI,KAAK,GAAG,CAAC;IAC1B,MAAM,EAAE,CAAC,IAAI,EAAE,IAAI,KAAK,GAAG,CAAC;IAC5B,MAAM,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,GAAG,CAAC;IAClC,YAAY,EAAE,CAAC,IAAI,EAAE,IAAI,KAAK,GAAG,CAAC;CAClC,CAAC;AAEF,qBAAa,KAAM,SAAQ,YAAY,CAAC,UAAU,CAAC;IAClD,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAO;IAC3B,OAAO,CAAC,MAAM,CAAS;IAEvB,MAAM,0BAAkC;IACxC,IAAI,KAAK,WAAgC;IACzC,IAAI,KAAK,CAAC,GAAG,QAAA,EAA4B;gBAE7B,GAAG,EAAE,GAAG,GAAG,MAAM;IAK7B,MAAM,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAUvC,IAAI,CAAC,MAAM,UAAM,GAAG,OAAO,CAAC,IAAI,EAAE,CAAC;IAcnC,IAAI,CAAC,QAAQ,EAAE,MAAM,EAAE,MAAM,UAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAanD,MAAM,CAAC,IAAI,EAAE,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;IAajC,WAAW,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI;CAQxC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ztimson/momentum",
3
- "version": "0.27.1",
3
+ "version": "0.27.2",
4
4
  "description": "Client library for momentum",
5
5
  "keywords": [
6
6
  "Momentum"