@ztimson/momentum 0.27.3 → 0.28.1

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,1846 @@
1
- var v=function(t,e=!1){if(t==null)throw new Error("Cannot clean a NULL value");return Array.isArray(t)?t=t.filter((i)=>i!=null):Object.entries(t).forEach(([i,n])=>{(e&&n===void 0||!e&&n==null)&&delete t[i]}),t};var j=function(t,e){const i=typeof t,n=typeof e;return i!="object"||t==null||n!="object"||e==null?i=="function"&&n=="function"?t.toString()==e.toString():t===e:Object.keys(t).length!=Object.keys(e).length?!1:Object.keys(t).every((s)=>j(t[s],e[s]))};var z=function(t,e){const i=document.createElement("a");i.href=t,i.download=e,document.body.appendChild(i),i.click(),document.body.removeChild(i)},Tt=function(t,e){const i=URL.createObjectURL(t);z(i,e),URL.revokeObjectURL(i)},At=function(t={}){return new Promise((e)=>{const i=document.createElement("input");i.type="file",i.accept=t.accept||"*",i.style.display="none",i.multiple=!!t.multiple,i.onblur=i.onchange=async()=>{e(Array.from(i.files)),i.remove()},document.body.appendChild(i),i.click()})},V=function(t){return new E((e,i,n)=>{const s=new XMLHttpRequest,a=new FormData;t.files.forEach((o)=>a.append("file",o)),s.withCredentials=!!t.withCredentials,s.upload.addEventListener("progress",(o)=>o.lengthComputable?n(o.loaded/o.total):null),s.upload.addEventListener("load",(o)=>e(o)),s.upload.addEventListener("error",(o)=>i(o)),s.open("POST",t.url),Object.entries(t.headers||{}).forEach(([o,p])=>s.setRequestHeader(o,p)),s.send(a)})};var Nt=Object.defineProperty,Vt=(t,e,i)=>(e in t)?Nt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,l=(t,e,i)=>(Vt(t,typeof e!="symbol"?e+"":e,i),i);class E extends Promise{constructor(t){super((e,i)=>t((n)=>e(n),(n)=>i(n),(n)=>this.progress=n));l(this,"listeners",[]),l(this,"_progress",0)}get progress(){return this._progress}set progress(t){t!=this._progress&&(this._progress=t,this.listeners.forEach((e)=>e(t)))}static from(t){return t instanceof E?t:new E((e,i)=>t.then((...n)=>e(...n)).catch((...n)=>i(...n)))}from(t){const e=E.from(t);return this.onProgress((i)=>e.progress=i),e}onProgress(t){return this.listeners.push(t),this}then(t,e){const i=super.then(t,e);return this.from(i)}catch(t){return this.from(super.catch(t))}finally(t){return this.from(super.finally(t))}}class h{constructor(){l(this,"listeners",{})}static emit(t,...e){(this.listeners["*"]||[]).forEach((i)=>i(t,...e)),(this.listeners[t.toString()]||[]).forEach((i)=>i(...e))}static off(t,e){const i=t.toString();this.listeners[i]=(this.listeners[i]||[]).filter((n)=>n===e)}static on(t,e){var i;const n=t.toString();return this.listeners[n]||(this.listeners[n]=[]),(i=this.listeners[n])==null||i.push(e),()=>this.off(t,e)}static once(t,e){return new Promise((i)=>{const n=this.on(t,(...s)=>{i(s.length==1?s[0]:s),e&&e(...s),n()})})}emit(t,...e){(this.listeners["*"]||[]).forEach((i)=>i(t,...e)),(this.listeners[t]||[]).forEach((i)=>i(...e))}off(t,e){this.listeners[t]=(this.listeners[t]||[]).filter((i)=>i===e)}on(t,e){var i;return this.listeners[t]||(this.listeners[t]=[]),(i=this.listeners[t])==null||i.push(e),()=>this.off(t,e)}once(t,e){return new Promise((i)=>{const n=this.on(t,(...s)=>{i(s.length==1?s[0]:s),e&&e(...s),n()})})}}l(h,"listeners",{});class A extends Error{constructor(t,e){super(t);l(this,"_code"),e!=null&&(this._code=e)}get code(){return this._code||this.constructor.code}set code(t){this._code=t}static from(t){const e=Number(t.statusCode)??Number(t.code),i=new this(t.message||t.toString());return Object.assign(i,{stack:t.stack,...t,code:e??void 0})}static instanceof(t){return t.constructor.code!=null}toString(){return this.message||super.toString()}}l(A,"code",500);class wt extends A{constructor(t="Bad Request"){super(t)}static instanceof(t){return t.constructor.code==this.code}}l(wt,"code",400);class Pt extends A{constructor(t="Unauthorized"){super(t)}static instanceof(t){return t.constructor.code==this.code}}l(Pt,"code",401);class Dt extends A{constructor(t="Forbidden"){super(t)}static instanceof(t){return t.constructor.code==this.code}}l(Dt,"code",403);class Lt extends A{constructor(t="Not Found"){super(t)}static instanceof(t){return t.constructor.code==this.code}}l(Lt,"code",404);class Rt extends A{constructor(t="Internal Server Error"){super(t)}static instanceof(t){return t.constructor.code==this.code}}l(Rt,"code",500);var Y=class t{constructor(e={}){l(this,"interceptors",{}),l(this,"headers",{}),l(this,"url"),this.url=e.url??null,this.headers=e.headers||{},e.interceptors&&e.interceptors.forEach((i)=>t.addInterceptor(i))}static addInterceptor(e){const i=Object.keys(t.interceptors).length.toString();return t.interceptors[i]=e,()=>{t.interceptors[i]=null}}addInterceptor(e){const i=Object.keys(this.interceptors).length.toString();return this.interceptors[i]=e,()=>{this.interceptors[i]=null}}request(e={}){var i;if(!this.url&&!e.url)throw new Error("URL needs to be set");let n=((i=e.url)!=null&&i.startsWith("http")?e.url:(this.url||"")+(e.url||"")).replace(/([^:]\/)\/+/g,"$1");if(e.fragment&&(n.includes("#")?n.replace(/#.*(\?|\n)/g,(a,o)=>`#${e.fragment}${o}`):n+="#"+e.fragment),e.query){const a=Array.isArray(e.query)?e.query:Object.keys(e.query).map((o)=>({key:o,value:e.query[o]}));n+=(n.includes("?")?"&":"?")+a.map((o)=>`${o.key}=${o.value}`).join("&")}const s=v({"Content-Type":e.body?e.body instanceof FormData?"multipart/form-data":"application/json":void 0,...t.headers,...this.headers,...e.headers});return typeof e.body=="object"&&e.body!=null&&s["Content-Type"]=="application/json"&&(e.body=JSON.stringify(e.body)),new E((a,o,p)=>{fetch(n,{headers:s,method:e.method||(e.body?"POST":"GET"),body:e.body}).then(async(u)=>{var D,S;for(let U of[...Object.values(t.interceptors),...Object.values(this.interceptors)])await new Promise((K)=>U(u,()=>K()));const G=u.headers.get("Content-Length"),L=G?parseInt(G,10):0;let g=0;const W=(D=u.body)==null?void 0:D.getReader(),y=new ReadableStream({start(U){function K(){W==null||W.read().then((H)=>{if(H.done)return U.close();g+=H.value.byteLength,p(g/L),U.enqueue(H.value),K()}).catch((H)=>U.error(H))}K()}}),F=new Response(y),c=(S=u.headers.get("Content-Type"))==null?void 0:S.toLowerCase();c!=null&&c.includes("json")?u.data=await F.json():c!=null&&c.includes("text")?u.data=await F.text():c!=null&&c.includes("form")?u.data=await F.formData():c!=null&&c.includes("application")?u.data=await F.blob():u.data=null,u.ok?a(u):o(u)})})}};l(Y,"interceptors",{}),l(Y,"headers",{});var $t=Y,M={CLEAR:"\x1B[0m",BRIGHT:"\x1B[1m",DIM:"\x1B[2m",UNDERSCORE:"\x1B[4m",BLINK:"\x1B[5m",REVERSE:"\x1B[7m",HIDDEN:"\x1B[8m"},N={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 w=((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))(w||{}),Ct=class t extends h{constructor(e){super(),this.namespace=e}pad(e,i,n,s=!1){const a=e.toString(),o=i-a.length;if(o<=0)return a;const p=Array(~~(o/n.length)).fill(n).join("");return s?a+p:p+a}format(...e){const i=new Date;return`${`${i.getFullYear()}-${i.getMonth()+1}-${i.getDate()} ${this.pad(i.getHours().toString(),2,"0")}:${this.pad(i.getMinutes().toString(),2,"0")}:${this.pad(i.getSeconds().toString(),2,"0")}.${this.pad(i.getMilliseconds().toString(),3,"0",!0)}`}${this.namespace?` [${this.namespace}]`:""} ${e.join(" ")}`}debug(...e){if(t.LOG_LEVEL<4)return;const i=this.format(...e);t.emit(4,i),console.debug(N.LIGHT_GREY+i+M.CLEAR)}log(...e){if(t.LOG_LEVEL<3)return;const i=this.format(...e);t.emit(3,i),console.log(M.CLEAR+i)}info(...e){if(t.LOG_LEVEL<2)return;const i=this.format(...e);t.emit(2,i),console.info(N.BLUE+i+M.CLEAR)}warn(...e){if(t.LOG_LEVEL<1)return;const i=this.format(...e);t.emit(1,i),console.warn(N.YELLOW+i+M.CLEAR)}error(...e){if(t.LOG_LEVEL<0)return;const i=this.format(...e);t.emit(0,i),console.error(N.RED+i+M.CLEAR)}};l(Ct,"LOG_LEVEL",4);var Bt="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",Jt="0123456789",Xt="~`!@#$%^&*()_-+={[}]|\\:;\"'<,>.?/",ti=Bt+Jt+Xt;class r extends $t{t;e;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,e={}){e.url=t;super(e);this.url=t;this.opts=e}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 e=super.request(t).then((i)=>{return this.emit("RESPONSE",i,t),i}).catch((i)=>{throw this.emit("REJECTED",i,t),i});return this.emit("REQUEST",e,t),e}}function T(t,e){if(typeof e!=="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");b(t,e);function i(){this.constructor=t}t.prototype=e===null?Object.create(e):(i.prototype=e.prototype,new i)}function x(t){var e=typeof Symbol==="function"&&Symbol.iterator,i=e&&t[e],n=0;if(i)return i.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(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function R(t,e){var i=typeof Symbol==="function"&&t[Symbol.iterator];if(!i)return t;var n=i.call(t),s,a=[],o;try{while((e===void 0||e-- >0)&&!(s=n.next()).done)a.push(s.value)}catch(p){o={error:p}}finally{try{if(s&&!s.done&&(i=n.return))i.call(n)}finally{if(o)throw o.error}}return a}function $(t,e,i){if(i||arguments.length===2){for(var n=0,s=e.length,a;n<s;n++)if(a||!(n in e)){if(!a)a=Array.prototype.slice.call(e,0,n);a[n]=e[n]}}return t.concat(a||Array.prototype.slice.call(e))}var b=function(t,e){return b=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(i,n){i.__proto__=n}||function(i,n){for(var s in n)if(Object.prototype.hasOwnProperty.call(n,s))i[s]=n[s]},b(t,e)};function d(t){return typeof t==="function"}function C(t){var e=function(n){Error.call(n),n.stack=new Error().stack},i=t(e);return i.prototype=Object.create(Error.prototype),i.prototype.constructor=i,i}var B=C(function(t){return function e(i){t(this),this.message=i?i.length+" errors occurred during unsubscription:\n"+i.map(function(n,s){return s+1+") "+n.toString()}).join("\n "):"",this.name="UnsubscriptionError",this.errors=i}});function k(t,e){if(t){var i=t.indexOf(e);0<=i&&t.splice(i,1)}}function J(t){return t instanceof O||t&&"closed"in t&&d(t.remove)&&d(t.add)&&d(t.unsubscribe)}var Ot=function(t){if(d(t))t();else t.unsubscribe()},O=function(){function t(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return t.prototype.unsubscribe=function(){var e,i,n,s,a;if(!this.closed){this.closed=!0;var o=this._parentage;if(o)if(this._parentage=null,Array.isArray(o))try{for(var p=x(o),u=p.next();!u.done;u=p.next()){var D=u.value;D.remove(this)}}catch(y){e={error:y}}finally{try{if(u&&!u.done&&(i=p.return))i.call(p)}finally{if(e)throw e.error}}else o.remove(this);var S=this.initialTeardown;if(d(S))try{S()}catch(y){a=y instanceof B?y.errors:[y]}var G=this._finalizers;if(G){this._finalizers=null;try{for(var L=x(G),g=L.next();!g.done;g=L.next()){var W=g.value;try{Ot(W)}catch(y){if(a=a!==null&&a!==void 0?a:[],y instanceof B)a=$($([],R(a)),R(y.errors));else a.push(y)}}}catch(y){n={error:y}}finally{try{if(g&&!g.done&&(s=L.return))s.call(L)}finally{if(n)throw n.error}}}if(a)throw new B(a)}},t.prototype.add=function(e){var i;if(e&&e!==this)if(this.closed)Ot(e);else{if(e instanceof t){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=(i=this._finalizers)!==null&&i!==void 0?i:[]).push(e)}},t.prototype._hasParent=function(e){var i=this._parentage;return i===e||Array.isArray(i)&&i.includes(e)},t.prototype._addParent=function(e){var i=this._parentage;this._parentage=Array.isArray(i)?(i.push(e),i):i?[i,e]:e},t.prototype._removeParent=function(e){var i=this._parentage;if(i===e)this._parentage=null;else if(Array.isArray(i))k(i,e)},t.prototype.remove=function(e){var i=this._finalizers;if(i&&k(i,e),e instanceof t)e._removeParent(this)},t.EMPTY=function(){var e=new t;return e.closed=!0,e}(),t}();var _=O.EMPTY;var f={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1};var q={setTimeout:function(t,e){var i=[];for(var n=2;n<arguments.length;n++)i[n-2]=arguments[n];var s=q.delegate;if(s===null||s===void 0?void 0:s.setTimeout)return s.setTimeout.apply(s,$([t,e],R(i)));return setTimeout.apply(void 0,$([t,e],R(i)))},clearTimeout:function(t){var e=q.delegate;return((e===null||e===void 0?void 0:e.clearTimeout)||clearTimeout)(t)},delegate:void 0};function qt(t){q.setTimeout(function(){var e=f.onUnhandledError;if(e)e(t);else throw t})}function tt(){}function St(t){return it("E",void 0,t)}function Gt(t){return it("N",t,void 0)}function it(t,e,i){return{kind:t,value:e,error:i}}var It=function(){return it("C",void 0,void 0)}();function I(t){if(f.useDeprecatedSynchronousErrorHandling){var e=!P;if(e)P={errorThrown:!1,error:null};if(t(),e){var i=P,n=i.errorThrown,s=i.error;if(P=null,n)throw s}}else t()}function Ut(t){if(f.useDeprecatedSynchronousErrorHandling&&P)P.errorThrown=!0,P.error=t}var P=null;var et=function(t,e){return Qt.call(t,e)},X=function(t){if(f.useDeprecatedSynchronousErrorHandling)Ut(t);else qt(t)},Yt=function(t){throw t},nt=function(t,e){var i=f.onStoppedNotification;i&&q.setTimeout(function(){return i(t,e)})},st=function(t){T(e,t);function e(i){var n=t.call(this)||this;if(n.isStopped=!1,i){if(n.destination=i,J(i))i.add(n)}else n.destination=vt;return n}return e.create=function(i,n,s){return new Q(i,n,s)},e.prototype.next=function(i){if(this.isStopped)nt(Gt(i),this);else this._next(i)},e.prototype.error=function(i){if(this.isStopped)nt(St(i),this);else this.isStopped=!0,this._error(i)},e.prototype.complete=function(){if(this.isStopped)nt(It,this);else this.isStopped=!0,this._complete()},e.prototype.unsubscribe=function(){if(!this.closed)this.isStopped=!0,t.prototype.unsubscribe.call(this),this.destination=null},e.prototype._next=function(i){this.destination.next(i)},e.prototype._error=function(i){try{this.destination.error(i)}finally{this.unsubscribe()}},e.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},e}(O);var Qt=Function.prototype.bind,Zt=function(){function t(e){this.partialObserver=e}return t.prototype.next=function(e){var i=this.partialObserver;if(i.next)try{i.next(e)}catch(n){X(n)}},t.prototype.error=function(e){var i=this.partialObserver;if(i.error)try{i.error(e)}catch(n){X(n)}else X(e)},t.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(i){X(i)}},t}(),Q=function(t){T(e,t);function e(i,n,s){var a=t.call(this)||this,o;if(d(i)||!i)o={next:i!==null&&i!==void 0?i:void 0,error:n!==null&&n!==void 0?n:void 0,complete:s!==null&&s!==void 0?s:void 0};else{var p;if(a&&f.useDeprecatedNextContext)p=Object.create(i),p.unsubscribe=function(){return a.unsubscribe()},o={next:i.next&&et(i.next,p),error:i.error&&et(i.error,p),complete:i.complete&&et(i.complete,p)};else o=i}return a.destination=new Zt(o),a}return e}(st);var vt={closed:!0,next:tt,error:Yt,complete:tt};var Ht=function(){return typeof Symbol==="function"&&Symbol.observable||"@@observable"}();function Mt(t){return t}function xt(t){if(t.length===0)return Mt;if(t.length===1)return t[0];return function e(i){return t.reduce(function(n,s){return s(n)},i)}}var kt=function(t){var e;return(e=t!==null&&t!==void 0?t:f.Promise)!==null&&e!==void 0?e:Promise},jt=function(t){return t&&d(t.next)&&d(t.error)&&d(t.complete)},zt=function(t){return t&&t instanceof st||jt(t)&&J(t)},at=function(){function t(e){if(e)this._subscribe=e}return t.prototype.lift=function(e){var i=new t;return i.source=this,i.operator=e,i},t.prototype.subscribe=function(e,i,n){var s=this,a=zt(e)?e:new Q(e,i,n);return I(function(){var o=s,p=o.operator,u=o.source;a.add(p?p.call(a,u):u?s._subscribe(a):s._trySubscribe(a))}),a},t.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(i){e.error(i)}},t.prototype.forEach=function(e,i){var n=this;return i=kt(i),new i(function(s,a){var o=new Q({next:function(p){try{e(p)}catch(u){a(u),o.unsubscribe()}},error:a,complete:s});n.subscribe(o)})},t.prototype._subscribe=function(e){var i;return(i=this.source)===null||i===void 0?void 0:i.subscribe(e)},t.prototype[Ht]=function(){return this},t.prototype.pipe=function(){var e=[];for(var i=0;i<arguments.length;i++)e[i]=arguments[i];return xt(e)(this)},t.prototype.toPromise=function(e){var i=this;return e=kt(e),new e(function(n,s){var a;i.subscribe(function(o){return a=o},function(o){return s(o)},function(){return n(a)})})},t.create=function(e){return new t(e)},t}();var Wt=C(function(t){return function e(){t(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}});var ot=function(t){T(e,t);function e(){var i=t.call(this)||this;return i.closed=!1,i.currentObservers=null,i.observers=[],i.isStopped=!1,i.hasError=!1,i.thrownError=null,i}return e.prototype.lift=function(i){var n=new Ft(this,this);return n.operator=i,n},e.prototype._throwIfClosed=function(){if(this.closed)throw new Wt},e.prototype.next=function(i){var n=this;I(function(){var s,a;if(n._throwIfClosed(),!n.isStopped){if(!n.currentObservers)n.currentObservers=Array.from(n.observers);try{for(var o=x(n.currentObservers),p=o.next();!p.done;p=o.next()){var u=p.value;u.next(i)}}catch(D){s={error:D}}finally{try{if(p&&!p.done&&(a=o.return))a.call(o)}finally{if(s)throw s.error}}}})},e.prototype.error=function(i){var n=this;I(function(){if(n._throwIfClosed(),!n.isStopped){n.hasError=n.isStopped=!0,n.thrownError=i;var s=n.observers;while(s.length)s.shift().error(i)}})},e.prototype.complete=function(){var i=this;I(function(){if(i._throwIfClosed(),!i.isStopped){i.isStopped=!0;var n=i.observers;while(n.length)n.shift().complete()}})},e.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(e.prototype,"observed",{get:function(){var i;return((i=this.observers)===null||i===void 0?void 0:i.length)>0},enumerable:!1,configurable:!0}),e.prototype._trySubscribe=function(i){return this._throwIfClosed(),t.prototype._trySubscribe.call(this,i)},e.prototype._subscribe=function(i){return this._throwIfClosed(),this._checkFinalizedStatuses(i),this._innerSubscribe(i)},e.prototype._innerSubscribe=function(i){var n=this,s=this,a=s.hasError,o=s.isStopped,p=s.observers;if(a||o)return _;return this.currentObservers=null,p.push(i),new O(function(){n.currentObservers=null,k(p,i)})},e.prototype._checkFinalizedStatuses=function(i){var n=this,s=n.hasError,a=n.thrownError,o=n.isStopped;if(s)i.error(a);else if(o)i.complete()},e.prototype.asObservable=function(){var i=new at;return i.source=this,i},e.create=function(i,n){return new Ft(i,n)},e}(at);var Ft=function(t){T(e,t);function e(i,n){var s=t.call(this)||this;return s.destination=i,s.source=n,s}return e.prototype.next=function(i){var n,s;(s=(n=this.destination)===null||n===void 0?void 0:n.next)===null||s===void 0||s.call(n,i)},e.prototype.error=function(i){var n,s;(s=(n=this.destination)===null||n===void 0?void 0:n.error)===null||s===void 0||s.call(n,i)},e.prototype.complete=function(){var i,n;(n=(i=this.destination)===null||i===void 0?void 0:i.complete)===null||n===void 0||n.call(i)},e.prototype._subscribe=function(i){var n,s;return(s=(n=this.source)===null||n===void 0?void 0:n.subscribe(i))!==null&&s!==void 0?s:_},e}(ot);var m=function(t){T(e,t);function e(i){var n=t.call(this)||this;return n._value=i,n}return Object.defineProperty(e.prototype,"value",{get:function(){return this.getValue()},enumerable:!1,configurable:!0}),e.prototype._subscribe=function(i){var n=t.prototype._subscribe.call(this,i);return!n.closed&&i.next(this._value),n},e.prototype.getValue=function(){var i=this,n=i.hasError,s=i.thrownError,a=i._value;if(n)throw s;return this._throwIfClosed(),a},e.prototype.next=function(i){t.prototype.next.call(this,this._value=i)},e}(ot);var bt;((p)=>{p[p.CRON=0]="CRON";p[p.EVENT=1]="EVENT";p[p.DELETE=2]="DELETE";p[p.GET=3]="GET";p[p.PATCH=4]="PATCH";p[p.POST=5]="POST";p[p.PUT=6]="PUT"})(bt||={});class pt extends h{api;$cache=new m([]);get cache(){return this.$cache.value}set cache(t){this.$cache.next(t)}constructor(t){super();this.api=typeof t=="string"?new r(t):t}delete(t){return this.api.request({url:`/api/actions/${t}`,method:"DELETE"}).then(()=>{this.cache=this.cache.filter((e)=>e._id!=t),this.emit("DELETE",t)})}list(){return this.api.request({url:"/api/actions"}).then((t)=>{if(t.data)this.cache=t.data;return this.emit("LIST",t.data||[]),t.data})}read(t,e=!1){const i=this.cache.find((n)=>n._id==t);if(!e&&i)return Promise.resolve(i);return this.api.request({url:`/api/actions/${t}`}).then((n)=>{if(n.data)this.cache=this.cache.filter((s)=>s._id!=t).concat([n.data]);return this.emit("READ",n.data),n.data})}run(t,e={}){return this.api.request({url:("/api/actions/run/"+t).replaceAll("//","/"),...e}).then((i)=>i.data)}runById(t,e={}){const i=typeof t=="string"?t:t._id;return this.api.request({url:"/api/actions/run-by-id/"+i,method:"POST",...e}).then((n)=>n.data)}update(t){return this.api.request({url:`/api/actions${t._id?`/${t._id}`:""}`,method:"POST",body:t}).then((e)=>{if(e.data)this.cache=this.cache.filter((i)=>i._id!=e.data?._id).concat([e.data]);return this.emit("UPDATE",e.data),e.data})}}class Kt{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,e="app",i){return this.api.request({url:`/api/auth/totp/${t}`,body:v({method:e,totp:i})})}}class ht extends h{e;api;storageKey;totp;$user=new m(void 0);get user(){return this.$user.value}set user(t){if(!j(this.user,t)){const e=t?t:null;this.$user.next(e),this.emit("USER",e)}}constructor(t,e){super();this.opts=e;if(this.api=typeof t=="string"?new r(t):t,this.totp=new Kt(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((i,n)=>{const s=["/api/auth/login","/api/auth/password","/api/auth/totp"];if(i.status==401&&!s.find((a)=>i.url.includes(a)))this.emit("SESSION_EXPIRED");n()}),this.api.on("TOKEN",(i)=>{if(this.opts?.persist)if(i)localStorage.setItem(this.storageKey,i);else localStorage.removeItem(this.storageKey);if(i)this.session(i,!0).catch(()=>{});else this.user=null}),e?.persist){const i=localStorage.getItem(this.storageKey);if(i)this.api.token=i;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)}`}).then(()=>{})}login(t,e,i){return this.api.request({url:"/api/auth/login",headers:{Authorization:void 0},method:"POST",body:{username:t.trim(),password:e.trim(),totp:i}}).then(async(n)=>{return this.api.token=n.data?.token||null,await this.once("USER")})}loginRedirect(t=location.origin){return new Promise((e,i)=>{const n=window.open(encodeURI(`${this.opts?.loginUi}?redirect=postmessage&host=${t}`),"_blank");if(!n)return i("Unable to open login");n.addEventListener("message",(s)=>{if(!s?.data?.token)return i("Unknown response from login");this.api.token=s.data.token,e(s.data.token),n.close()})})}logout(){this.api.token=null,this.user=null,this.emit("LOGOUT")}async register(t){const e=(await this.api.request({url:"/api/auth/register",body:{...t}}))?.data;if(e?.image?.startsWith("/"))e.image=`${this.api.url}${e.image}?token=${this.api.token}`;return this.emit("REGISTER",e),e}reset(t,e){return this.api.request({url:"/api/auth/reset",headers:{Authorization:e?`Bearer ${e}`:void 0},body:{email:e?void 0:t,password:e?t:void 0}}).then(()=>{})}async session(t,e=!1){if(!t)t=this.api.token;const i=(await this.api.request({url:"/api/auth/session",headers:t?{Authorization:`Bearer ${t}`}:void 0}))?.data;if(e){if(this.api.token=t,i?.user)i.user.image=`${this.api.url}${i.user.image}?token=${this.api.token}`;if(this.user=i?.user||null,i)this.emit("LOGIN",i.user)}return i}async updatePassword(t,e,i){return this.api.request({url:"/api/auth/password",body:{username:t,password:e,oldPassword:i}}).then((n)=>{if(n?.data?.token)this.api.token=n.data.token})}}class rt extends h{api;constructor(t){super();this.api=typeof t=="string"?new r(t):t}delete(t,e){return this.api.request({url:`/api/data/${t}/${e}`,method:"DELETE"}).then(()=>this.emit("DELETE",t,e))}get(t,e){return this.api.request({url:`/api/data/${t}${e?`/${e}`:""}`}).then((i)=>{return this.emit("GET",t,i.data),i.data})}raw(t,e,i,n){return this.api.request({url:`/api/data/${t}`,body:{operand:e,query:i,options:n}}).then((s)=>{return this.emit("RAW",t,s.data),s.data})}set(t,e,i=!1){return this.api.request({url:`/api/data/${t}/${e._id||""}`,method:i?"PATCH":"POST",body:e}).then((n)=>{return this.emit("SET",t,n.data),n.data})}}class ut extends h{api;constructor(t){super();this.api=typeof t=="string"?new r(t):t}send(t){let e="/api/email";if(typeof t.body=="object")e+=`/${t.body.template}`;return this.api.request({url:e,body:t}).then((i)=>{return this.emit("SENT",t),i.data})}}class lt extends h{api;constructor(t){super();this.api=typeof t=="string"?new r(t):t}create(t){return this.api.request({url:`/api/groups/${t.name}`,method:"POST",body:t}).then((e)=>{return this.emit("CREATE",e.data),e.data})}list(){return this.api.request({url:"/api/groups"}).then((t)=>{return this.emit("LIST",t.data||[]),t.data})}read(t){return this.api.request({url:`/api/groups/${t}`}).then((e)=>{return this.emit("READ",e.data),e.data})}update(t){return this.api.request({url:`/api/groups/${t.name}`,method:"PATCH",body:t}).then((e)=>{return this.emit("UPDATE",e.data),e.data})}delete(t){return this.api.request({url:`/api/groups/${t}`,method:"DELETE"}).then(()=>this.emit("DELETE",t))}}class yt{api;constructor(t,e){if(this.api=typeof t=="string"?new r(t):t,e!=null&&e!="NONE")window.addEventListener("error",(i)=>this.error(i.error.stack)),window.addEventListener("unhandledrejection",async(i)=>this.error(i.reason.stack))}buildLog(t,e){return{time:(new Date()).getTime(),level:t,log:e,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,e){const i=[t?`length=${t}`:void 0,e?`page=${e}`:void 0].filter((n)=>!!n).join("&");return this.api.request({url:`/api/logs/client${i?`?${i}`:""}`}).then((n)=>n.data)}serverLogs(t,e){const i=[t?`length=${t}`:void 0,e?`page=${e}`:void 0].filter((n)=>!!n).join("&");return this.api.request({url:`/api/logs/server${i?`?${i}`:""}`}).then((n)=>n.data)}debug(...t){return this.api.request({url:"/api/logs/client",body:this.buildLog(w.DEBUG,t)}).then(()=>{}).catch(()=>{})}log(...t){return this.api.request({url:"/api/logs/client",body:this.buildLog(w.LOG,t)}).then(()=>{}).catch(()=>{})}info(...t){return this.api.request({url:"/api/logs/client",body:this.buildLog(w.INFO,t)}).then(()=>{}).catch(()=>{})}warn(...t){return this.api.request({url:"/api/logs/client",body:this.buildLog(w.WARN,t)}).then(()=>{}).catch(()=>{})}error(...t){return this.api.request({url:"/api/logs/client",body:this.buildLog(w.ERROR,t)}).then(()=>{}).catch(()=>{})}}class dt extends h{api;stripe;constructor(t,e){super();this.api=typeof t=="string"?new r(t):t;const i=(n=1)=>{try{if(!Stripe)throw new Error("Stripe not added");this.stripe=Stripe(e)}catch(s){if(n>0)setTimeout(()=>i(n--),250);else console.warn("Stripe failed, did you add the library & setup your API key?",s)}};i()}async charge(t,e={}){return this.emit("CHECKOUT",t,e),(await this.api.request({url:"/api/payments",body:{amount:t,custom:e}})).data.clientSecret}async createForm(t,e,i){const n=await this.charge(e,i),s=this.stripe.elements({clientSecret:n});return s.create("payment").mount(t),()=>this.stripe.confirmPayment({elements:s,redirect:"if_required",confirmParams:{return_url:location.origin}})}async history(t){const e=await this.api.request({url:`/api/payments${t?`/${t}`:""}`});return this.emit("LIST",t||null,e.data),e.data}}class ft extends h{api;constructor(t){super();this.api=typeof t=="string"?new r(t):t}async handleResponse(t,e){const i=await t.blob();if(e){const n=URL.createObjectURL(i);z(n,e.endsWith(".pdf")?e:e+".pdf"),URL.revokeObjectURL(n)}return this.emit("CREATE",i),i}fromHtml(t,e={}){return this.api.request({url:"/api/pdf",body:{html:t}}).then((i)=>this.handleResponse(i,e.download?e.fileName||(new Date()).toISOString():void 0))}fromTemplate(t,e,i={}){return this.api.request({url:`/api/pdf${t}`,body:e}).then((n)=>this.handleResponse(n,i.download?i.fileName||(new Date()).toISOString():void 0))}fromUrl(t,e={}){return this.api.request({url:`/api/pdf?url=${t}`}).then((i)=>this.handleResponse(i,e.download?e.fileName||(new Date()).toISOString():void 0))}}class Z{static timeout=1e4;api;url;connection;open=!1;constructor(t){if(this.api=typeof t=="string"?new r(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 e=setTimeout(()=>{if(this.open)return;if(this.connection.close(),console.error("Momentum connection timeout"),t>0)this.connect(t-1)},Z.timeout);this.connection.onclose=()=>this.open=!1,this.connection.onmessage=this.handle,this.connection.onopen=()=>{this.open=!0,clearTimeout(e),console.debug("Connected to Momentum")}}handle(...t){console.log(t)}send(t,e){this.connection.send(JSON.stringify({token:this.api.token,channel:t,payload:e}))}}class mt extends h{api;constructor(t){super();this.api=typeof t=="string"?new r(t):t}delete(t){const e=(t.startsWith("/api/storage/")?t:"/api/storage/"+t).replaceAll("//","/");return this.api.request({url:e,method:"DELETE"}).then(()=>{this.emit("DELETE",e)})}list(t){const e=(t.startsWith("/api/storage/")?t:"/api/storage/"+t).replaceAll("//","/");return this.api.request({url:e+"?list"}).then((i)=>{return this.emit("LIST",t,i.data),i.data})}open(t,e="_blank"){const i=(t.startsWith("/api/storage/")?t:"/api/storage/"+t).replaceAll(/\/{2,}/g,"/"),n=`${this.api.url}${i}${this.api.token?`?token=${this.api.token}`:""}`;if(!e)return n;return this.emit("OPEN",t),window.open(n,e)}mkdir(t){const e=(t.startsWith("/api/storage/")?t:"/api/storage/"+t).replaceAll(/\/{2,}/g,"/");return this.api.request({url:e+"?directory",method:"POST"}).then((i)=>i.data)}download(t,e={}){const i=("/api/storage/"+t).replaceAll("//","/");return this.api.request({...e,url:i,skipConverting:!0}).then((n)=>{const s=e.downloadAs||new URL(n.url).pathname.split("/").pop();return this.emit("DOWNLOAD",t,n.data),Tt(n.data,s),n.data})}upload(t,e=""){return new E(async(i,n,s)=>{if(!t)t=await At();if(!t||Array.isArray(t)&&!t.length)return[];const a=this.api.url+("/api/storage/"+(typeof e=="string"?e:e?.path)).replaceAll("//","/");return V({url:a,files:Array.isArray(t)?t:[t],headers:this.api.headers}).onProgress((o)=>{s(o)}).then((o)=>{this.emit("UPLOAD",o),i(o)}).catch((o)=>n(o))})}}class gt extends h{api;listed=!1;$cache=new m([]);get cache(){return this.$cache.value}set cache(t){this.$cache.next(t)}constructor(t){super();this.api=typeof t=="string"?new r(t):t}delete(t){return this.api.request({url:`/api/users/${t}`,method:"DELETE"}).then(()=>{this.cache=this.cache.filter((e)=>e.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((e)=>{return e.data?.map((i)=>{return i.image=this.api.url+i.image+`?token=${this.api.token}`,i}),this.cache=e.data||[],this.listed=!0,this.emit("LIST",e.data||[]),e.data})}read(t,e=!1){if(!e){const i=this.cache.find((n)=>n.username==t);if(i)return Promise.resolve(i)}return this.api.request({url:`/api/users/${t}`}).then((i)=>{if(i.data)i.data.image=this.api.url+i.data.image+`?token=${this.api.token}`,this.cache=[...this.cache.filter((n)=>n.username!=t),i.data];return this.emit("READ",i.data),i.data})}update(t){return this.api.request({url:`/api/users/${t.username}`,method:"PATCH",body:t}).then((e)=>{if(e.data)e.data.image=this.api.url+e.data.image+`?token=${this.api.token}`,this.cache=this.cache.filter((i)=>i.username!=t.username).concat([e.data]);return this.emit(t._id?"UPDATE":"CREATE",e.data),e.data})}uploadImage(t,e){return V({url:this.api.url+`/api/users/${t}/image`,files:[e],headers:this.api.headers}).then((i)=>{return this.emit("UPLOAD_IMAGE",t,e),i})}}class ct extends h{api;$cache=new m({});get cache(){return this.$cache.value}set cache(t){this.$cache.next(t)}constructor(t){super();this.api=typeof t=="string"?new r(t):t}list(t=!1){return this.api.request({url:"/api/settings"+(t?"?detailed":"")}).then((e)=>{return this.cache=!t?e.data:Object.values(e.data||{}).reduce((i,n)=>({...i,[n.key]:n.value}),{}),this.emit("LIST",e.data||[]),e.data})}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,e=!1){if(!e&&this.cache[t])return Promise.resolve(this.cache[t]);return this.api.request({url:`/api/settings/${t}`}).then((i)=>{if(i.data)this.cache={...this.cache,[i.data.key]:i};return this.emit("READ",i.data),i.data})}update(t){return this.api.request({url:`/api/settings/${t.key}`,body:t}).then((e)=>{if(e.data)this.cache={...this.cache,[e.data.key]:e.data.value};return this.emit("UPDATE",e.data),e.data})}}class Et extends h{api;constructor(t){super();this.api=typeof t=="string"?new r(t):t}delete(t){return this.api.request({url:`/api/static/${t}`,method:"DELETE"}).then(()=>{this.emit("DELETE",t)})}list(t){const e=("/api/static/"+t).replaceAll("//","/");return this.api.request({url:e}).then((i)=>{return this.emit("LIST",t,i.data||[]),i.data})}upload(t,e="/"){const i=new FormData;return(Array.isArray(t)?t:[t]).forEach((n)=>i.append("file",n)),this.api.request({url:"/api/static"+e,body:i}).then((n)=>{return this.emit("UPLOAD",n.data||[]),n.data})}}class _t extends h{api;actions;auth;data;email;groups;logger;payments;pdf;settings;socket;static;storage;users;constructor(t,e){super();if(this.api=new r(t,e?.api),this.actions=new pt(this.api),this.auth=new ht(this.api,{persist:e?.persist??!0,loginUi:e?.loginUi}),this.data=new rt(this.api),this.email=new ut(this.api),this.groups=new lt(this.api),this.logger=new yt(this.api,e?.logLevel),e?.stripeSecret)this.payments=new dt(this.api,e.stripeSecret);if(this.pdf=new ft(this.api),this.settings=new ct(this.api),this.static=new Et(this.api),this.storage=new mt(this.api),this.users=new gt(this.api),e?.socket)this.socket=new Z(this.api);if(this.api.on("*",(i,...n)=>this.emit(`API::${i}`,...n)),this.actions.on("*",(i,...n)=>this.emit(`ACTIONS::${i}`,...n)),this.auth.on("*",(i,...n)=>this.emit(`AUTH::${i}`,...n)),this.data.on("*",(i,...n)=>this.emit(`DATA::${i}`,...n)),this.email.on("*",(i,...n)=>this.emit(`EMAIL::${i}`,...n)),this.groups.on("*",(i,...n)=>this.emit(`GROUPS::${i}`,...n)),this.payments)this.payments.on("*",(i,...n)=>this.emit(`PAYMENT::${i}`,...n));this.pdf.on("*",(i,...n)=>this.emit(`PDF::${i}`,...n)),this.settings.on("*",(i,...n)=>this.emit(`SETTINGS::${i}`,...n)),this.static.on("*",(i,...n)=>this.emit(`STATIC::${i}`,...n)),this.storage.on("*",(i,...n)=>this.emit(`STORAGE::${i}`,...n)),this.users.on("*",(i,...n)=>this.emit(`USERS::${i}`,...n)),this.users.on("*",(i,...n)=>{if(Array.isArray(n[0])){const s=n[0].find((a)=>a._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{gt as Users,Kt as Totp,mt as Storage,Et as Static,Z as Socket,ct as Settings,ft as Pdf,dt as Payments,_t as Momentum,yt as Logger,lt as Groups,ut as Email,rt as Data,ht as Auth,r as Api,pt as Actions,bt as ActionType};
1
+ var __defProp = Object.defineProperty;
2
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
4
+ var Y = Object.defineProperty;
5
+ var v = (n, e, t) => e in n ? Y(n, e, { enumerable: true, configurable: true, writable: true, value: t }) : n[e] = t;
6
+ var a = (n, e, t) => (v(n, typeof e != "symbol" ? e + "" : e, t), t);
7
+ function F(n, e = false) {
8
+ if (n == null)
9
+ throw new Error("Cannot clean a NULL value");
10
+ return Array.isArray(n) ? n = n.filter((t) => t != null) : Object.entries(n).forEach(([t, r]) => {
11
+ (e && r === void 0 || !e && r == null) && delete n[t];
12
+ }), n;
13
+ }
14
+ function b(n, e) {
15
+ const t = typeof n, r = typeof e;
16
+ return t != "object" || n == null || r != "object" || e == null ? t == "function" && r == "function" ? n.toString() == e.toString() : n === e : Object.keys(n).length != Object.keys(e).length ? false : Object.keys(n).every((s) => b(n[s], e[s]));
17
+ }
18
+ class E extends Promise {
19
+ constructor(t) {
20
+ super((r, o) => t(
21
+ (s) => r(s),
22
+ (s) => o(s),
23
+ (s) => this.progress = s
24
+ ));
25
+ a(this, "listeners", []);
26
+ a(this, "_progress", 0);
27
+ }
28
+ get progress() {
29
+ return this._progress;
30
+ }
31
+ set progress(t) {
32
+ t != this._progress && (this._progress = t, this.listeners.forEach((r) => r(t)));
33
+ }
34
+ static from(t) {
35
+ return t instanceof E ? t : new E((r, o) => t.then((...s) => r(...s)).catch((...s) => o(...s)));
36
+ }
37
+ from(t) {
38
+ const r = E.from(t);
39
+ return this.onProgress((o) => r.progress = o), r;
40
+ }
41
+ onProgress(t) {
42
+ return this.listeners.push(t), this;
43
+ }
44
+ then(t, r) {
45
+ const o = super.then(t, r);
46
+ return this.from(o);
47
+ }
48
+ catch(t) {
49
+ return this.from(super.catch(t));
50
+ }
51
+ finally(t) {
52
+ return this.from(super.finally(t));
53
+ }
54
+ }
55
+ function V(n, e) {
56
+ const t = document.createElement("a");
57
+ t.href = n, t.download = e, document.body.appendChild(t), t.click(), document.body.removeChild(t);
58
+ }
59
+ function wt(n, e) {
60
+ const t = URL.createObjectURL(n);
61
+ V(t, e), URL.revokeObjectURL(t);
62
+ }
63
+ function xt(n = {}) {
64
+ return new Promise((e) => {
65
+ const t = document.createElement("input");
66
+ t.type = "file", t.accept = n.accept || "*", t.style.display = "none", t.multiple = !!n.multiple, t.onblur = t.onchange = async () => {
67
+ e(Array.from(t.files)), t.remove();
68
+ }, document.body.appendChild(t), t.click();
69
+ });
70
+ }
71
+ function At(n) {
72
+ return new E((e, t, r) => {
73
+ const o = new XMLHttpRequest(), s = new FormData();
74
+ n.files.forEach((i) => s.append("file", i)), o.withCredentials = !!n.withCredentials, o.upload.addEventListener("progress", (i) => i.lengthComputable ? r(i.loaded / i.total) : null), o.upload.addEventListener("load", (i) => e(i)), o.upload.addEventListener("error", (i) => t(i)), o.open("POST", n.url), Object.entries(n.headers || {}).forEach(([i, y]) => o.setRequestHeader(i, y)), o.send(s);
75
+ });
76
+ }
77
+ class P {
78
+ constructor() {
79
+ a(this, "listeners", {});
80
+ }
81
+ static emit(e, ...t) {
82
+ (this.listeners["*"] || []).forEach((r) => r(e, ...t)), (this.listeners[e.toString()] || []).forEach((r) => r(...t));
83
+ }
84
+ static off(e, t) {
85
+ const r = e.toString();
86
+ this.listeners[r] = (this.listeners[r] || []).filter((o) => o === t);
87
+ }
88
+ static on(e, t) {
89
+ var o;
90
+ const r = e.toString();
91
+ return this.listeners[r] || (this.listeners[r] = []), (o = this.listeners[r]) == null || o.push(t), () => this.off(e, t);
92
+ }
93
+ static once(e, t) {
94
+ return new Promise((r) => {
95
+ const o = this.on(e, (...s) => {
96
+ r(s.length == 1 ? s[0] : s), t && t(...s), o();
97
+ });
98
+ });
99
+ }
100
+ emit(e, ...t) {
101
+ (this.listeners["*"] || []).forEach((r) => r(e, ...t)), (this.listeners[e] || []).forEach((r) => r(...t));
102
+ }
103
+ off(e, t) {
104
+ this.listeners[e] = (this.listeners[e] || []).filter((r) => r === t);
105
+ }
106
+ on(e, t) {
107
+ var r;
108
+ return this.listeners[e] || (this.listeners[e] = []), (r = this.listeners[e]) == null || r.push(t), () => this.off(e, t);
109
+ }
110
+ once(e, t) {
111
+ return new Promise((r) => {
112
+ const o = this.on(e, (...s) => {
113
+ r(s.length == 1 ? s[0] : s), t && t(...s), o();
114
+ });
115
+ });
116
+ }
117
+ }
118
+ a(P, "listeners", {});
119
+ class w extends Error {
120
+ constructor(t, r) {
121
+ super(t);
122
+ a(this, "_code");
123
+ r != null && (this._code = r);
124
+ }
125
+ get code() {
126
+ return this._code || this.constructor.code;
127
+ }
128
+ set code(t) {
129
+ this._code = t;
130
+ }
131
+ static from(t) {
132
+ const r = Number(t.statusCode) ?? Number(t.code), o = new this(t.message || t.toString());
133
+ return Object.assign(o, {
134
+ stack: t.stack,
135
+ ...t,
136
+ code: r ?? void 0
137
+ });
138
+ }
139
+ static instanceof(t) {
140
+ return t.constructor.code != null;
141
+ }
142
+ toString() {
143
+ return this.message || super.toString();
144
+ }
145
+ }
146
+ a(w, "code", 500);
147
+ class Z extends w {
148
+ constructor(e = "Bad Request") {
149
+ super(e);
150
+ }
151
+ static instanceof(e) {
152
+ return e.constructor.code == this.code;
153
+ }
154
+ }
155
+ a(Z, "code", 400);
156
+ class X extends w {
157
+ constructor(e = "Unauthorized") {
158
+ super(e);
159
+ }
160
+ static instanceof(e) {
161
+ return e.constructor.code == this.code;
162
+ }
163
+ }
164
+ a(X, "code", 401);
165
+ class Q extends w {
166
+ constructor(e = "Forbidden") {
167
+ super(e);
168
+ }
169
+ static instanceof(e) {
170
+ return e.constructor.code == this.code;
171
+ }
172
+ }
173
+ a(Q, "code", 403);
174
+ class _ extends w {
175
+ constructor(e = "Not Found") {
176
+ super(e);
177
+ }
178
+ static instanceof(e) {
179
+ return e.constructor.code == this.code;
180
+ }
181
+ }
182
+ a(_, "code", 404);
183
+ class tt extends w {
184
+ constructor(e = "Internal Server Error") {
185
+ super(e);
186
+ }
187
+ static instanceof(e) {
188
+ return e.constructor.code == this.code;
189
+ }
190
+ }
191
+ a(tt, "code", 500);
192
+ const g = class g2 {
193
+ constructor(e = {}) {
194
+ a(this, "interceptors", {});
195
+ a(this, "headers", {});
196
+ a(this, "url");
197
+ this.url = e.url ?? null, this.headers = e.headers || {}, e.interceptors && e.interceptors.forEach((t) => g2.addInterceptor(t));
198
+ }
199
+ static addInterceptor(e) {
200
+ const t = Object.keys(g2.interceptors).length.toString();
201
+ return g2.interceptors[t] = e, () => {
202
+ g2.interceptors[t] = null;
203
+ };
204
+ }
205
+ addInterceptor(e) {
206
+ const t = Object.keys(this.interceptors).length.toString();
207
+ return this.interceptors[t] = e, () => {
208
+ this.interceptors[t] = null;
209
+ };
210
+ }
211
+ request(e = {}) {
212
+ var o;
213
+ if (!this.url && !e.url)
214
+ throw new Error("URL needs to be set");
215
+ let t = ((o = e.url) != null && o.startsWith("http") ? e.url : (this.url || "") + (e.url || "")).replace(/([^:]\/)\/+/g, "$1");
216
+ if (e.fragment && (t.includes("#") ? t.replace(/#.*(\?|\n)/g, (s, i) => `#${e.fragment}${i}`) : t += "#" + e.fragment), e.query) {
217
+ const s = Array.isArray(e.query) ? e.query : Object.keys(e.query).map((i) => ({ key: i, value: e.query[i] }));
218
+ t += (t.includes("?") ? "&" : "?") + s.map((i) => `${i.key}=${i.value}`).join("&");
219
+ }
220
+ const r = F({
221
+ "Content-Type": e.body ? e.body instanceof FormData ? "multipart/form-data" : "application/json" : void 0,
222
+ ...g2.headers,
223
+ ...this.headers,
224
+ ...e.headers
225
+ });
226
+ return typeof e.body == "object" && e.body != null && r["Content-Type"] == "application/json" && (e.body = JSON.stringify(e.body)), new E((s, i, y) => {
227
+ fetch(t, {
228
+ headers: r,
229
+ method: e.method || (e.body ? "POST" : "GET"),
230
+ body: e.body
231
+ }).then(async (c) => {
232
+ var k, G;
233
+ for (let u of [...Object.values(g2.interceptors), ...Object.values(this.interceptors)])
234
+ await new Promise((L) => u(c, () => L()));
235
+ const R = c.headers.get("Content-Length"), N = R ? parseInt(R, 10) : 0;
236
+ let j = 0;
237
+ const I = (k = c.body) == null ? void 0 : k.getReader(), H = new ReadableStream({
238
+ start(u) {
239
+ function L() {
240
+ I == null || I.read().then((x) => {
241
+ if (x.done)
242
+ return u.close();
243
+ j += x.value.byteLength, y(j / N), u.enqueue(x.value), L();
244
+ }).catch((x) => u.error(x));
245
+ }
246
+ L();
247
+ }
248
+ });
249
+ if (c.data = new Response(H), e.decode == null || e.decode) {
250
+ const u = (G = c.headers.get("Content-Type")) == null ? void 0 : G.toLowerCase();
251
+ u != null && u.includes("form") ? c.data = await c.data.formData() : u != null && u.includes("json") ? c.data = await c.data.json() : u != null && u.includes("text") ? c.data = await c.data.text() : u != null && u.includes("application") && (c.data = await c.data.blob());
252
+ }
253
+ c.ok ? s(c) : i(c);
254
+ });
255
+ });
256
+ }
257
+ };
258
+ a(g, "interceptors", {}), a(g, "headers", {});
259
+ let M = g;
260
+ const A = {
261
+ CLEAR: "\x1B[0m",
262
+ BRIGHT: "\x1B[1m",
263
+ DIM: "\x1B[2m",
264
+ UNDERSCORE: "\x1B[4m",
265
+ BLINK: "\x1B[5m",
266
+ REVERSE: "\x1B[7m",
267
+ HIDDEN: "\x1B[8m"
268
+ }, O = {
269
+ BLACK: "\x1B[30m",
270
+ RED: "\x1B[31m",
271
+ GREEN: "\x1B[32m",
272
+ YELLOW: "\x1B[33m",
273
+ BLUE: "\x1B[34m",
274
+ MAGENTA: "\x1B[35m",
275
+ CYAN: "\x1B[36m",
276
+ LIGHT_GREY: "\x1B[37m",
277
+ GREY: "\x1B[90m",
278
+ LIGHT_RED: "\x1B[91m",
279
+ LIGHT_GREEN: "\x1B[92m",
280
+ LIGHT_YELLOW: "\x1B[93m",
281
+ LIGHT_BLUE: "\x1B[94m",
282
+ LIGHT_MAGENTA: "\x1B[95m",
283
+ LIGHT_CYAN: "\x1B[96m",
284
+ WHITE: "\x1B[97m"
285
+ };
286
+ var et = /* @__PURE__ */ ((n) => (n[n.ERROR = 0] = "ERROR", n[n.WARN = 1] = "WARN", n[n.INFO = 2] = "INFO", n[n.LOG = 3] = "LOG", n[n.DEBUG = 4] = "DEBUG", n))(et || {});
287
+ const p = class p2 extends P {
288
+ constructor(e) {
289
+ super(), this.namespace = e;
290
+ }
291
+ pad(e, t, r, o = false) {
292
+ const s = e.toString(), i = t - s.length;
293
+ if (i <= 0)
294
+ return s;
295
+ const y = Array(~~(i / r.length)).fill(r).join("");
296
+ return o ? s + y : y + s;
297
+ }
298
+ format(...e) {
299
+ const t = /* @__PURE__ */ new Date();
300
+ 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", true)}`}${this.namespace ? ` [${this.namespace}]` : ""} ${e.join(" ")}`;
301
+ }
302
+ debug(...e) {
303
+ if (p2.LOG_LEVEL < 4)
304
+ return;
305
+ const t = this.format(...e);
306
+ p2.emit(4, t), console.debug(O.LIGHT_GREY + t + A.CLEAR);
307
+ }
308
+ log(...e) {
309
+ if (p2.LOG_LEVEL < 3)
310
+ return;
311
+ const t = this.format(...e);
312
+ p2.emit(3, t), console.log(A.CLEAR + t);
313
+ }
314
+ info(...e) {
315
+ if (p2.LOG_LEVEL < 2)
316
+ return;
317
+ const t = this.format(...e);
318
+ p2.emit(2, t), console.info(O.BLUE + t + A.CLEAR);
319
+ }
320
+ warn(...e) {
321
+ if (p2.LOG_LEVEL < 1)
322
+ return;
323
+ const t = this.format(...e);
324
+ p2.emit(1, t), console.warn(O.YELLOW + t + A.CLEAR);
325
+ }
326
+ error(...e) {
327
+ if (p2.LOG_LEVEL < 0)
328
+ return;
329
+ const t = this.format(...e);
330
+ p2.emit(0, t), console.error(O.RED + t + A.CLEAR);
331
+ }
332
+ };
333
+ a(p, "LOG_LEVEL", 4);
334
+ class Api extends M {
335
+ constructor(url = location.origin, opts = {}) {
336
+ opts.url = url;
337
+ super(opts);
338
+ __publicField(this, "emitter", new P());
339
+ __publicField(this, "_token", null);
340
+ __publicField(this, "emit", this.emitter.emit.bind(this.emitter));
341
+ __publicField(this, "off", this.emitter.off.bind(this.emitter));
342
+ __publicField(this, "on", this.emitter.on.bind(this.emitter));
343
+ __publicField(this, "once", this.emitter.once.bind(this.emitter));
344
+ this.url = url;
345
+ this.opts = opts;
346
+ }
347
+ get token() {
348
+ return this._token;
349
+ }
350
+ set token(token) {
351
+ if (token == this._token) return;
352
+ this._token = token;
353
+ this.headers["Authorization"] = token ? `Bearer ${token}` : void 0;
354
+ this.emit("TOKEN", token);
355
+ }
356
+ request(options) {
357
+ const req = super.request(options).then((resp) => {
358
+ this.emit("RESPONSE", resp, options);
359
+ return resp.data;
360
+ }).catch((err) => {
361
+ const e = (err == null ? void 0 : err.data) || err;
362
+ this.emit("REJECTED", e, options);
363
+ throw e;
364
+ });
365
+ this.emit("REQUEST", req, options);
366
+ return req;
367
+ }
368
+ }
369
+ var extendStatics = function(d, b2) {
370
+ extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b3) {
371
+ d2.__proto__ = b3;
372
+ } || function(d2, b3) {
373
+ for (var p3 in b3) if (Object.prototype.hasOwnProperty.call(b3, p3)) d2[p3] = b3[p3];
374
+ };
375
+ return extendStatics(d, b2);
376
+ };
377
+ function __extends(d, b2) {
378
+ if (typeof b2 !== "function" && b2 !== null)
379
+ throw new TypeError("Class extends value " + String(b2) + " is not a constructor or null");
380
+ extendStatics(d, b2);
381
+ function __() {
382
+ this.constructor = d;
383
+ }
384
+ d.prototype = b2 === null ? Object.create(b2) : (__.prototype = b2.prototype, new __());
385
+ }
386
+ function __values(o) {
387
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
388
+ if (m) return m.call(o);
389
+ if (o && typeof o.length === "number") return {
390
+ next: function() {
391
+ if (o && i >= o.length) o = void 0;
392
+ return { value: o && o[i++], done: !o };
393
+ }
394
+ };
395
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
396
+ }
397
+ function __read(o, n) {
398
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
399
+ if (!m) return o;
400
+ var i = m.call(o), r, ar = [], e;
401
+ try {
402
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
403
+ } catch (error) {
404
+ e = { error };
405
+ } finally {
406
+ try {
407
+ if (r && !r.done && (m = i["return"])) m.call(i);
408
+ } finally {
409
+ if (e) throw e.error;
410
+ }
411
+ }
412
+ return ar;
413
+ }
414
+ function __spreadArray(to, from, pack) {
415
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
416
+ if (ar || !(i in from)) {
417
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
418
+ ar[i] = from[i];
419
+ }
420
+ }
421
+ return to.concat(ar || Array.prototype.slice.call(from));
422
+ }
423
+ typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
424
+ var e = new Error(message);
425
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
426
+ };
427
+ function isFunction(value) {
428
+ return typeof value === "function";
429
+ }
430
+ function createErrorClass(createImpl) {
431
+ var _super = function(instance) {
432
+ Error.call(instance);
433
+ instance.stack = new Error().stack;
434
+ };
435
+ var ctorFunc = createImpl(_super);
436
+ ctorFunc.prototype = Object.create(Error.prototype);
437
+ ctorFunc.prototype.constructor = ctorFunc;
438
+ return ctorFunc;
439
+ }
440
+ var UnsubscriptionError = createErrorClass(function(_super) {
441
+ return function UnsubscriptionErrorImpl(errors) {
442
+ _super(this);
443
+ this.message = errors ? errors.length + " errors occurred during unsubscription:\n" + errors.map(function(err, i) {
444
+ return i + 1 + ") " + err.toString();
445
+ }).join("\n ") : "";
446
+ this.name = "UnsubscriptionError";
447
+ this.errors = errors;
448
+ };
449
+ });
450
+ function arrRemove(arr, item) {
451
+ if (arr) {
452
+ var index = arr.indexOf(item);
453
+ 0 <= index && arr.splice(index, 1);
454
+ }
455
+ }
456
+ var Subscription = function() {
457
+ function Subscription2(initialTeardown) {
458
+ this.initialTeardown = initialTeardown;
459
+ this.closed = false;
460
+ this._parentage = null;
461
+ this._finalizers = null;
462
+ }
463
+ Subscription2.prototype.unsubscribe = function() {
464
+ var e_1, _a, e_2, _b;
465
+ var errors;
466
+ if (!this.closed) {
467
+ this.closed = true;
468
+ var _parentage = this._parentage;
469
+ if (_parentage) {
470
+ this._parentage = null;
471
+ if (Array.isArray(_parentage)) {
472
+ try {
473
+ for (var _parentage_1 = __values(_parentage), _parentage_1_1 = _parentage_1.next(); !_parentage_1_1.done; _parentage_1_1 = _parentage_1.next()) {
474
+ var parent_1 = _parentage_1_1.value;
475
+ parent_1.remove(this);
476
+ }
477
+ } catch (e_1_1) {
478
+ e_1 = { error: e_1_1 };
479
+ } finally {
480
+ try {
481
+ if (_parentage_1_1 && !_parentage_1_1.done && (_a = _parentage_1.return)) _a.call(_parentage_1);
482
+ } finally {
483
+ if (e_1) throw e_1.error;
484
+ }
485
+ }
486
+ } else {
487
+ _parentage.remove(this);
488
+ }
489
+ }
490
+ var initialFinalizer = this.initialTeardown;
491
+ if (isFunction(initialFinalizer)) {
492
+ try {
493
+ initialFinalizer();
494
+ } catch (e) {
495
+ errors = e instanceof UnsubscriptionError ? e.errors : [e];
496
+ }
497
+ }
498
+ var _finalizers = this._finalizers;
499
+ if (_finalizers) {
500
+ this._finalizers = null;
501
+ try {
502
+ for (var _finalizers_1 = __values(_finalizers), _finalizers_1_1 = _finalizers_1.next(); !_finalizers_1_1.done; _finalizers_1_1 = _finalizers_1.next()) {
503
+ var finalizer = _finalizers_1_1.value;
504
+ try {
505
+ execFinalizer(finalizer);
506
+ } catch (err) {
507
+ errors = errors !== null && errors !== void 0 ? errors : [];
508
+ if (err instanceof UnsubscriptionError) {
509
+ errors = __spreadArray(__spreadArray([], __read(errors)), __read(err.errors));
510
+ } else {
511
+ errors.push(err);
512
+ }
513
+ }
514
+ }
515
+ } catch (e_2_1) {
516
+ e_2 = { error: e_2_1 };
517
+ } finally {
518
+ try {
519
+ if (_finalizers_1_1 && !_finalizers_1_1.done && (_b = _finalizers_1.return)) _b.call(_finalizers_1);
520
+ } finally {
521
+ if (e_2) throw e_2.error;
522
+ }
523
+ }
524
+ }
525
+ if (errors) {
526
+ throw new UnsubscriptionError(errors);
527
+ }
528
+ }
529
+ };
530
+ Subscription2.prototype.add = function(teardown) {
531
+ var _a;
532
+ if (teardown && teardown !== this) {
533
+ if (this.closed) {
534
+ execFinalizer(teardown);
535
+ } else {
536
+ if (teardown instanceof Subscription2) {
537
+ if (teardown.closed || teardown._hasParent(this)) {
538
+ return;
539
+ }
540
+ teardown._addParent(this);
541
+ }
542
+ (this._finalizers = (_a = this._finalizers) !== null && _a !== void 0 ? _a : []).push(teardown);
543
+ }
544
+ }
545
+ };
546
+ Subscription2.prototype._hasParent = function(parent) {
547
+ var _parentage = this._parentage;
548
+ return _parentage === parent || Array.isArray(_parentage) && _parentage.includes(parent);
549
+ };
550
+ Subscription2.prototype._addParent = function(parent) {
551
+ var _parentage = this._parentage;
552
+ this._parentage = Array.isArray(_parentage) ? (_parentage.push(parent), _parentage) : _parentage ? [_parentage, parent] : parent;
553
+ };
554
+ Subscription2.prototype._removeParent = function(parent) {
555
+ var _parentage = this._parentage;
556
+ if (_parentage === parent) {
557
+ this._parentage = null;
558
+ } else if (Array.isArray(_parentage)) {
559
+ arrRemove(_parentage, parent);
560
+ }
561
+ };
562
+ Subscription2.prototype.remove = function(teardown) {
563
+ var _finalizers = this._finalizers;
564
+ _finalizers && arrRemove(_finalizers, teardown);
565
+ if (teardown instanceof Subscription2) {
566
+ teardown._removeParent(this);
567
+ }
568
+ };
569
+ Subscription2.EMPTY = function() {
570
+ var empty = new Subscription2();
571
+ empty.closed = true;
572
+ return empty;
573
+ }();
574
+ return Subscription2;
575
+ }();
576
+ var EMPTY_SUBSCRIPTION = Subscription.EMPTY;
577
+ function isSubscription(value) {
578
+ return value instanceof Subscription || value && "closed" in value && isFunction(value.remove) && isFunction(value.add) && isFunction(value.unsubscribe);
579
+ }
580
+ function execFinalizer(finalizer) {
581
+ if (isFunction(finalizer)) {
582
+ finalizer();
583
+ } else {
584
+ finalizer.unsubscribe();
585
+ }
586
+ }
587
+ var config = {
588
+ onUnhandledError: null,
589
+ onStoppedNotification: null,
590
+ Promise: void 0,
591
+ useDeprecatedSynchronousErrorHandling: false,
592
+ useDeprecatedNextContext: false
593
+ };
594
+ var timeoutProvider = {
595
+ setTimeout: function(handler, timeout) {
596
+ var args = [];
597
+ for (var _i = 2; _i < arguments.length; _i++) {
598
+ args[_i - 2] = arguments[_i];
599
+ }
600
+ return setTimeout.apply(void 0, __spreadArray([handler, timeout], __read(args)));
601
+ },
602
+ clearTimeout: function(handle) {
603
+ var delegate = timeoutProvider.delegate;
604
+ return ((delegate === null || delegate === void 0 ? void 0 : delegate.clearTimeout) || clearTimeout)(handle);
605
+ },
606
+ delegate: void 0
607
+ };
608
+ function reportUnhandledError(err) {
609
+ timeoutProvider.setTimeout(function() {
610
+ {
611
+ throw err;
612
+ }
613
+ });
614
+ }
615
+ function noop() {
616
+ }
617
+ function errorContext(cb) {
618
+ {
619
+ cb();
620
+ }
621
+ }
622
+ var Subscriber = function(_super) {
623
+ __extends(Subscriber2, _super);
624
+ function Subscriber2(destination) {
625
+ var _this = _super.call(this) || this;
626
+ _this.isStopped = false;
627
+ if (destination) {
628
+ _this.destination = destination;
629
+ if (isSubscription(destination)) {
630
+ destination.add(_this);
631
+ }
632
+ } else {
633
+ _this.destination = EMPTY_OBSERVER;
634
+ }
635
+ return _this;
636
+ }
637
+ Subscriber2.create = function(next, error, complete) {
638
+ return new SafeSubscriber(next, error, complete);
639
+ };
640
+ Subscriber2.prototype.next = function(value) {
641
+ if (this.isStopped) ;
642
+ else {
643
+ this._next(value);
644
+ }
645
+ };
646
+ Subscriber2.prototype.error = function(err) {
647
+ if (this.isStopped) ;
648
+ else {
649
+ this.isStopped = true;
650
+ this._error(err);
651
+ }
652
+ };
653
+ Subscriber2.prototype.complete = function() {
654
+ if (this.isStopped) ;
655
+ else {
656
+ this.isStopped = true;
657
+ this._complete();
658
+ }
659
+ };
660
+ Subscriber2.prototype.unsubscribe = function() {
661
+ if (!this.closed) {
662
+ this.isStopped = true;
663
+ _super.prototype.unsubscribe.call(this);
664
+ this.destination = null;
665
+ }
666
+ };
667
+ Subscriber2.prototype._next = function(value) {
668
+ this.destination.next(value);
669
+ };
670
+ Subscriber2.prototype._error = function(err) {
671
+ try {
672
+ this.destination.error(err);
673
+ } finally {
674
+ this.unsubscribe();
675
+ }
676
+ };
677
+ Subscriber2.prototype._complete = function() {
678
+ try {
679
+ this.destination.complete();
680
+ } finally {
681
+ this.unsubscribe();
682
+ }
683
+ };
684
+ return Subscriber2;
685
+ }(Subscription);
686
+ var _bind = Function.prototype.bind;
687
+ function bind(fn, thisArg) {
688
+ return _bind.call(fn, thisArg);
689
+ }
690
+ var ConsumerObserver = function() {
691
+ function ConsumerObserver2(partialObserver) {
692
+ this.partialObserver = partialObserver;
693
+ }
694
+ ConsumerObserver2.prototype.next = function(value) {
695
+ var partialObserver = this.partialObserver;
696
+ if (partialObserver.next) {
697
+ try {
698
+ partialObserver.next(value);
699
+ } catch (error) {
700
+ handleUnhandledError(error);
701
+ }
702
+ }
703
+ };
704
+ ConsumerObserver2.prototype.error = function(err) {
705
+ var partialObserver = this.partialObserver;
706
+ if (partialObserver.error) {
707
+ try {
708
+ partialObserver.error(err);
709
+ } catch (error) {
710
+ handleUnhandledError(error);
711
+ }
712
+ } else {
713
+ handleUnhandledError(err);
714
+ }
715
+ };
716
+ ConsumerObserver2.prototype.complete = function() {
717
+ var partialObserver = this.partialObserver;
718
+ if (partialObserver.complete) {
719
+ try {
720
+ partialObserver.complete();
721
+ } catch (error) {
722
+ handleUnhandledError(error);
723
+ }
724
+ }
725
+ };
726
+ return ConsumerObserver2;
727
+ }();
728
+ var SafeSubscriber = function(_super) {
729
+ __extends(SafeSubscriber2, _super);
730
+ function SafeSubscriber2(observerOrNext, error, complete) {
731
+ var _this = _super.call(this) || this;
732
+ var partialObserver;
733
+ if (isFunction(observerOrNext) || !observerOrNext) {
734
+ partialObserver = {
735
+ next: observerOrNext !== null && observerOrNext !== void 0 ? observerOrNext : void 0,
736
+ error: error !== null && error !== void 0 ? error : void 0,
737
+ complete: complete !== null && complete !== void 0 ? complete : void 0
738
+ };
739
+ } else {
740
+ var context_1;
741
+ if (_this && config.useDeprecatedNextContext) {
742
+ context_1 = Object.create(observerOrNext);
743
+ context_1.unsubscribe = function() {
744
+ return _this.unsubscribe();
745
+ };
746
+ partialObserver = {
747
+ next: observerOrNext.next && bind(observerOrNext.next, context_1),
748
+ error: observerOrNext.error && bind(observerOrNext.error, context_1),
749
+ complete: observerOrNext.complete && bind(observerOrNext.complete, context_1)
750
+ };
751
+ } else {
752
+ partialObserver = observerOrNext;
753
+ }
754
+ }
755
+ _this.destination = new ConsumerObserver(partialObserver);
756
+ return _this;
757
+ }
758
+ return SafeSubscriber2;
759
+ }(Subscriber);
760
+ function handleUnhandledError(error) {
761
+ {
762
+ reportUnhandledError(error);
763
+ }
764
+ }
765
+ function defaultErrorHandler(err) {
766
+ throw err;
767
+ }
768
+ var EMPTY_OBSERVER = {
769
+ closed: true,
770
+ next: noop,
771
+ error: defaultErrorHandler,
772
+ complete: noop
773
+ };
774
+ var observable = function() {
775
+ return typeof Symbol === "function" && Symbol.observable || "@@observable";
776
+ }();
777
+ function identity(x) {
778
+ return x;
779
+ }
780
+ function pipeFromArray(fns) {
781
+ if (fns.length === 0) {
782
+ return identity;
783
+ }
784
+ if (fns.length === 1) {
785
+ return fns[0];
786
+ }
787
+ return function piped(input) {
788
+ return fns.reduce(function(prev, fn) {
789
+ return fn(prev);
790
+ }, input);
791
+ };
792
+ }
793
+ var Observable = function() {
794
+ function Observable2(subscribe) {
795
+ if (subscribe) {
796
+ this._subscribe = subscribe;
797
+ }
798
+ }
799
+ Observable2.prototype.lift = function(operator) {
800
+ var observable2 = new Observable2();
801
+ observable2.source = this;
802
+ observable2.operator = operator;
803
+ return observable2;
804
+ };
805
+ Observable2.prototype.subscribe = function(observerOrNext, error, complete) {
806
+ var _this = this;
807
+ var subscriber = isSubscriber(observerOrNext) ? observerOrNext : new SafeSubscriber(observerOrNext, error, complete);
808
+ errorContext(function() {
809
+ var _a = _this, operator = _a.operator, source = _a.source;
810
+ subscriber.add(operator ? operator.call(subscriber, source) : source ? _this._subscribe(subscriber) : _this._trySubscribe(subscriber));
811
+ });
812
+ return subscriber;
813
+ };
814
+ Observable2.prototype._trySubscribe = function(sink) {
815
+ try {
816
+ return this._subscribe(sink);
817
+ } catch (err) {
818
+ sink.error(err);
819
+ }
820
+ };
821
+ Observable2.prototype.forEach = function(next, promiseCtor) {
822
+ var _this = this;
823
+ promiseCtor = getPromiseCtor(promiseCtor);
824
+ return new promiseCtor(function(resolve, reject) {
825
+ var subscriber = new SafeSubscriber({
826
+ next: function(value) {
827
+ try {
828
+ next(value);
829
+ } catch (err) {
830
+ reject(err);
831
+ subscriber.unsubscribe();
832
+ }
833
+ },
834
+ error: reject,
835
+ complete: resolve
836
+ });
837
+ _this.subscribe(subscriber);
838
+ });
839
+ };
840
+ Observable2.prototype._subscribe = function(subscriber) {
841
+ var _a;
842
+ return (_a = this.source) === null || _a === void 0 ? void 0 : _a.subscribe(subscriber);
843
+ };
844
+ Observable2.prototype[observable] = function() {
845
+ return this;
846
+ };
847
+ Observable2.prototype.pipe = function() {
848
+ var operations = [];
849
+ for (var _i = 0; _i < arguments.length; _i++) {
850
+ operations[_i] = arguments[_i];
851
+ }
852
+ return pipeFromArray(operations)(this);
853
+ };
854
+ Observable2.prototype.toPromise = function(promiseCtor) {
855
+ var _this = this;
856
+ promiseCtor = getPromiseCtor(promiseCtor);
857
+ return new promiseCtor(function(resolve, reject) {
858
+ var value;
859
+ _this.subscribe(function(x) {
860
+ return value = x;
861
+ }, function(err) {
862
+ return reject(err);
863
+ }, function() {
864
+ return resolve(value);
865
+ });
866
+ });
867
+ };
868
+ Observable2.create = function(subscribe) {
869
+ return new Observable2(subscribe);
870
+ };
871
+ return Observable2;
872
+ }();
873
+ function getPromiseCtor(promiseCtor) {
874
+ var _a;
875
+ return (_a = promiseCtor !== null && promiseCtor !== void 0 ? promiseCtor : config.Promise) !== null && _a !== void 0 ? _a : Promise;
876
+ }
877
+ function isObserver(value) {
878
+ return value && isFunction(value.next) && isFunction(value.error) && isFunction(value.complete);
879
+ }
880
+ function isSubscriber(value) {
881
+ return value && value instanceof Subscriber || isObserver(value) && isSubscription(value);
882
+ }
883
+ var ObjectUnsubscribedError = createErrorClass(function(_super) {
884
+ return function ObjectUnsubscribedErrorImpl() {
885
+ _super(this);
886
+ this.name = "ObjectUnsubscribedError";
887
+ this.message = "object unsubscribed";
888
+ };
889
+ });
890
+ var Subject = function(_super) {
891
+ __extends(Subject2, _super);
892
+ function Subject2() {
893
+ var _this = _super.call(this) || this;
894
+ _this.closed = false;
895
+ _this.currentObservers = null;
896
+ _this.observers = [];
897
+ _this.isStopped = false;
898
+ _this.hasError = false;
899
+ _this.thrownError = null;
900
+ return _this;
901
+ }
902
+ Subject2.prototype.lift = function(operator) {
903
+ var subject = new AnonymousSubject(this, this);
904
+ subject.operator = operator;
905
+ return subject;
906
+ };
907
+ Subject2.prototype._throwIfClosed = function() {
908
+ if (this.closed) {
909
+ throw new ObjectUnsubscribedError();
910
+ }
911
+ };
912
+ Subject2.prototype.next = function(value) {
913
+ var _this = this;
914
+ errorContext(function() {
915
+ var e_1, _a;
916
+ _this._throwIfClosed();
917
+ if (!_this.isStopped) {
918
+ if (!_this.currentObservers) {
919
+ _this.currentObservers = Array.from(_this.observers);
920
+ }
921
+ try {
922
+ for (var _b = __values(_this.currentObservers), _c = _b.next(); !_c.done; _c = _b.next()) {
923
+ var observer = _c.value;
924
+ observer.next(value);
925
+ }
926
+ } catch (e_1_1) {
927
+ e_1 = { error: e_1_1 };
928
+ } finally {
929
+ try {
930
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
931
+ } finally {
932
+ if (e_1) throw e_1.error;
933
+ }
934
+ }
935
+ }
936
+ });
937
+ };
938
+ Subject2.prototype.error = function(err) {
939
+ var _this = this;
940
+ errorContext(function() {
941
+ _this._throwIfClosed();
942
+ if (!_this.isStopped) {
943
+ _this.hasError = _this.isStopped = true;
944
+ _this.thrownError = err;
945
+ var observers = _this.observers;
946
+ while (observers.length) {
947
+ observers.shift().error(err);
948
+ }
949
+ }
950
+ });
951
+ };
952
+ Subject2.prototype.complete = function() {
953
+ var _this = this;
954
+ errorContext(function() {
955
+ _this._throwIfClosed();
956
+ if (!_this.isStopped) {
957
+ _this.isStopped = true;
958
+ var observers = _this.observers;
959
+ while (observers.length) {
960
+ observers.shift().complete();
961
+ }
962
+ }
963
+ });
964
+ };
965
+ Subject2.prototype.unsubscribe = function() {
966
+ this.isStopped = this.closed = true;
967
+ this.observers = this.currentObservers = null;
968
+ };
969
+ Object.defineProperty(Subject2.prototype, "observed", {
970
+ get: function() {
971
+ var _a;
972
+ return ((_a = this.observers) === null || _a === void 0 ? void 0 : _a.length) > 0;
973
+ },
974
+ enumerable: false,
975
+ configurable: true
976
+ });
977
+ Subject2.prototype._trySubscribe = function(subscriber) {
978
+ this._throwIfClosed();
979
+ return _super.prototype._trySubscribe.call(this, subscriber);
980
+ };
981
+ Subject2.prototype._subscribe = function(subscriber) {
982
+ this._throwIfClosed();
983
+ this._checkFinalizedStatuses(subscriber);
984
+ return this._innerSubscribe(subscriber);
985
+ };
986
+ Subject2.prototype._innerSubscribe = function(subscriber) {
987
+ var _this = this;
988
+ var _a = this, hasError = _a.hasError, isStopped = _a.isStopped, observers = _a.observers;
989
+ if (hasError || isStopped) {
990
+ return EMPTY_SUBSCRIPTION;
991
+ }
992
+ this.currentObservers = null;
993
+ observers.push(subscriber);
994
+ return new Subscription(function() {
995
+ _this.currentObservers = null;
996
+ arrRemove(observers, subscriber);
997
+ });
998
+ };
999
+ Subject2.prototype._checkFinalizedStatuses = function(subscriber) {
1000
+ var _a = this, hasError = _a.hasError, thrownError = _a.thrownError, isStopped = _a.isStopped;
1001
+ if (hasError) {
1002
+ subscriber.error(thrownError);
1003
+ } else if (isStopped) {
1004
+ subscriber.complete();
1005
+ }
1006
+ };
1007
+ Subject2.prototype.asObservable = function() {
1008
+ var observable2 = new Observable();
1009
+ observable2.source = this;
1010
+ return observable2;
1011
+ };
1012
+ Subject2.create = function(destination, source) {
1013
+ return new AnonymousSubject(destination, source);
1014
+ };
1015
+ return Subject2;
1016
+ }(Observable);
1017
+ var AnonymousSubject = function(_super) {
1018
+ __extends(AnonymousSubject2, _super);
1019
+ function AnonymousSubject2(destination, source) {
1020
+ var _this = _super.call(this) || this;
1021
+ _this.destination = destination;
1022
+ _this.source = source;
1023
+ return _this;
1024
+ }
1025
+ AnonymousSubject2.prototype.next = function(value) {
1026
+ var _a, _b;
1027
+ (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.next) === null || _b === void 0 ? void 0 : _b.call(_a, value);
1028
+ };
1029
+ AnonymousSubject2.prototype.error = function(err) {
1030
+ var _a, _b;
1031
+ (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.error) === null || _b === void 0 ? void 0 : _b.call(_a, err);
1032
+ };
1033
+ AnonymousSubject2.prototype.complete = function() {
1034
+ var _a, _b;
1035
+ (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.complete) === null || _b === void 0 ? void 0 : _b.call(_a);
1036
+ };
1037
+ AnonymousSubject2.prototype._subscribe = function(subscriber) {
1038
+ var _a, _b;
1039
+ return (_b = (_a = this.source) === null || _a === void 0 ? void 0 : _a.subscribe(subscriber)) !== null && _b !== void 0 ? _b : EMPTY_SUBSCRIPTION;
1040
+ };
1041
+ return AnonymousSubject2;
1042
+ }(Subject);
1043
+ var BehaviorSubject = function(_super) {
1044
+ __extends(BehaviorSubject2, _super);
1045
+ function BehaviorSubject2(_value) {
1046
+ var _this = _super.call(this) || this;
1047
+ _this._value = _value;
1048
+ return _this;
1049
+ }
1050
+ Object.defineProperty(BehaviorSubject2.prototype, "value", {
1051
+ get: function() {
1052
+ return this.getValue();
1053
+ },
1054
+ enumerable: false,
1055
+ configurable: true
1056
+ });
1057
+ BehaviorSubject2.prototype._subscribe = function(subscriber) {
1058
+ var subscription = _super.prototype._subscribe.call(this, subscriber);
1059
+ !subscription.closed && subscriber.next(this._value);
1060
+ return subscription;
1061
+ };
1062
+ BehaviorSubject2.prototype.getValue = function() {
1063
+ var _a = this, hasError = _a.hasError, thrownError = _a.thrownError, _value = _a._value;
1064
+ if (hasError) {
1065
+ throw thrownError;
1066
+ }
1067
+ this._throwIfClosed();
1068
+ return _value;
1069
+ };
1070
+ BehaviorSubject2.prototype.next = function(value) {
1071
+ _super.prototype.next.call(this, this._value = value);
1072
+ };
1073
+ return BehaviorSubject2;
1074
+ }(Subject);
1075
+ var ActionType = /* @__PURE__ */ ((ActionType2) => {
1076
+ ActionType2[ActionType2["CRON"] = 0] = "CRON";
1077
+ ActionType2[ActionType2["EVENT"] = 1] = "EVENT";
1078
+ ActionType2[ActionType2["DELETE"] = 2] = "DELETE";
1079
+ ActionType2[ActionType2["GET"] = 3] = "GET";
1080
+ ActionType2[ActionType2["PATCH"] = 4] = "PATCH";
1081
+ ActionType2[ActionType2["POST"] = 5] = "POST";
1082
+ ActionType2[ActionType2["PUT"] = 6] = "PUT";
1083
+ return ActionType2;
1084
+ })(ActionType || {});
1085
+ class Actions extends P {
1086
+ constructor(api) {
1087
+ super();
1088
+ __publicField(this, "api");
1089
+ __publicField(this, "$cache", new BehaviorSubject([]));
1090
+ this.api = typeof api == "string" ? new Api(api) : api;
1091
+ }
1092
+ get cache() {
1093
+ return this.$cache.value;
1094
+ }
1095
+ set cache(val) {
1096
+ this.$cache.next(val);
1097
+ }
1098
+ delete(id) {
1099
+ return this.api.request({ url: `/api/actions/${id}`, method: "DELETE" }).then(() => {
1100
+ this.cache = this.cache.filter((a2) => a2._id != id);
1101
+ this.emit("DELETE", id);
1102
+ });
1103
+ }
1104
+ list() {
1105
+ return this.api.request({ url: `/api/actions` }).then((resp) => {
1106
+ if (resp) this.cache = resp;
1107
+ this.emit("LIST", resp || []);
1108
+ return resp;
1109
+ });
1110
+ }
1111
+ read(id, reload = false) {
1112
+ const cached = this.cache.find((a2) => a2._id == id);
1113
+ if (!reload && cached) return Promise.resolve(cached);
1114
+ return this.api.request({ url: `/api/actions/${id}` }).then((action) => {
1115
+ if (action) this.cache = this.cache.filter((a2) => a2._id != id).concat([action]);
1116
+ this.emit("READ", action);
1117
+ return action;
1118
+ });
1119
+ }
1120
+ run(path, opts = {}) {
1121
+ return this.api.request({ url: (`/api/actions/run/` + path).replaceAll("//", "/"), ...opts });
1122
+ }
1123
+ runById(action, opts = {}) {
1124
+ const id = typeof action == "string" ? action : action._id;
1125
+ return this.api.request({ url: "/api/actions/run-by-id/" + id, method: "POST", ...opts });
1126
+ }
1127
+ update(action) {
1128
+ return this.api.request({
1129
+ url: `/api/actions${action._id ? `/${action._id}` : ""}`,
1130
+ method: "POST",
1131
+ body: action
1132
+ }).then((action2) => {
1133
+ if (action2) this.cache = this.cache.filter((a2) => a2._id != (action2 == null ? void 0 : action2._id)).concat([action2]);
1134
+ this.emit("UPDATE", action2);
1135
+ return action2;
1136
+ });
1137
+ }
1138
+ }
1139
+ class Totp {
1140
+ constructor(api) {
1141
+ __publicField(this, "enable", this.reset);
1142
+ this.api = api;
1143
+ }
1144
+ disable(username) {
1145
+ return this.api.request({ url: `/api/auth/totp/${username}`, method: "DELETE" });
1146
+ }
1147
+ reset(username) {
1148
+ return this.api.request({ url: `/api/auth/totp/${username}`, method: "POST" });
1149
+ }
1150
+ setup(username, method = "app", totp) {
1151
+ return this.api.request({ url: `/api/auth/totp/${username}`, body: F({
1152
+ method,
1153
+ totp
1154
+ }) });
1155
+ }
1156
+ }
1157
+ class Auth extends P {
1158
+ constructor(api, opts) {
1159
+ var _a;
1160
+ super();
1161
+ __publicField(this, "api");
1162
+ __publicField(this, "storageKey");
1163
+ __publicField(this, "totp");
1164
+ __publicField(this, "$user", new BehaviorSubject(void 0));
1165
+ this.opts = opts;
1166
+ this.api = typeof api == "string" ? new Api(api) : api;
1167
+ this.totp = new Totp(this.api);
1168
+ if (!((_a = this.opts) == null ? void 0 : _a.loginUi)) this.opts = { ...this.opts, loginUi: this.api.url + "/ui/login" };
1169
+ this.storageKey = `momentum:${new URL(this.api.url).host}`;
1170
+ this.api.addInterceptor((resp, next) => {
1171
+ const blacklist = [
1172
+ "/api/auth/login",
1173
+ "/api/auth/password",
1174
+ "/api/auth/totp"
1175
+ ];
1176
+ if (resp.status == 401 && !blacklist.find((url) => resp.url.includes(url)))
1177
+ this.emit("SESSION_EXPIRED");
1178
+ next();
1179
+ });
1180
+ this.api.on("TOKEN", (token) => {
1181
+ var _a2;
1182
+ if ((_a2 = this.opts) == null ? void 0 : _a2.persist) {
1183
+ if (token) localStorage.setItem(this.storageKey, token);
1184
+ else localStorage.removeItem(this.storageKey);
1185
+ }
1186
+ if (token) this.session(token, true).catch(() => {
1187
+ });
1188
+ else this.user = null;
1189
+ });
1190
+ if (opts == null ? void 0 : opts.persist) {
1191
+ const token = localStorage.getItem(this.storageKey);
1192
+ if (token) this.api.token = token;
1193
+ else this.user = null;
1194
+ } else {
1195
+ this.user = null;
1196
+ }
1197
+ }
1198
+ get user() {
1199
+ return this.$user.value;
1200
+ }
1201
+ set user(user) {
1202
+ if (!b(this.user, user)) {
1203
+ const u = user ? user : null;
1204
+ this.$user.next(u);
1205
+ this.emit("USER", u);
1206
+ }
1207
+ }
1208
+ knownHost(host = location.origin) {
1209
+ if (host.startsWith("/")) return Promise.resolve();
1210
+ return this.api.request({ url: `/api/auth/known-host?host=${encodeURI(new URL(host).origin)}` }).then(() => {
1211
+ });
1212
+ }
1213
+ login(username, password, totp) {
1214
+ return this.api.request({
1215
+ url: "/api/auth/login",
1216
+ headers: { Authorization: void 0 },
1217
+ method: "POST",
1218
+ body: {
1219
+ username: username.trim(),
1220
+ password: password.trim(),
1221
+ totp
1222
+ }
1223
+ }).then(async (resp) => {
1224
+ this.api.token = (resp == null ? void 0 : resp.token) || null;
1225
+ return await this.once("USER");
1226
+ });
1227
+ }
1228
+ loginRedirect(host = location.origin) {
1229
+ return new Promise((res, rej) => {
1230
+ var _a;
1231
+ const win = window.open(encodeURI(`${(_a = this.opts) == null ? void 0 : _a.loginUi}?redirect=postmessage&host=${host}`), "_blank");
1232
+ if (!win) return rej("Unable to open login");
1233
+ win.addEventListener("message", (event) => {
1234
+ var _a2;
1235
+ if (!((_a2 = event == null ? void 0 : event.data) == null ? void 0 : _a2.token)) return rej("Unknown response from login");
1236
+ this.api.token = event.data.token;
1237
+ res(event.data.token);
1238
+ win.close();
1239
+ });
1240
+ });
1241
+ }
1242
+ logout() {
1243
+ this.api.token = null;
1244
+ this.user = null;
1245
+ this.emit("LOGOUT");
1246
+ }
1247
+ async register(u) {
1248
+ var _a;
1249
+ const user = await this.api.request({ url: "/api/auth/register", body: { ...u } });
1250
+ if ((_a = user == null ? void 0 : user.image) == null ? void 0 : _a.startsWith("/")) user.image = `${this.api.url}${user.image}?token=${this.api.token}`;
1251
+ this.emit("REGISTER", user);
1252
+ return user;
1253
+ }
1254
+ reset(emailOrPass, token) {
1255
+ return this.api.request({
1256
+ url: "/api/auth/reset",
1257
+ headers: { "Authorization": token ? `Bearer ${token}` : void 0 },
1258
+ body: {
1259
+ email: token ? void 0 : emailOrPass,
1260
+ password: token ? emailOrPass : void 0
1261
+ }
1262
+ }).then(() => {
1263
+ });
1264
+ }
1265
+ async session(token, set = false) {
1266
+ if (!token) token = this.api.token;
1267
+ const session = await this.api.request({
1268
+ url: "/api/auth/session",
1269
+ headers: token ? { "Authorization": `Bearer ${token}` } : void 0
1270
+ });
1271
+ if (set) {
1272
+ this.api.token = token;
1273
+ if (session == null ? void 0 : session.user) session.user.image = `${this.api.url}${session.user.image}?token=${this.api.token}`;
1274
+ this.user = (session == null ? void 0 : session.user) || null;
1275
+ if (session) this.emit("LOGIN", session.user);
1276
+ }
1277
+ return session;
1278
+ }
1279
+ async updatePassword(username, password, oldPassword) {
1280
+ return this.api.request({
1281
+ url: "/api/auth/password",
1282
+ body: { username, password, oldPassword }
1283
+ }).then((resp) => {
1284
+ if (resp == null ? void 0 : resp.token) this.api.token = resp.token;
1285
+ });
1286
+ }
1287
+ }
1288
+ class Data extends P {
1289
+ constructor(api) {
1290
+ super();
1291
+ __publicField(this, "api");
1292
+ this.api = typeof api == "string" ? new Api(api) : api;
1293
+ }
1294
+ delete(collection, document2) {
1295
+ return this.api.request({
1296
+ url: `/api/data/${collection}/${document2}`,
1297
+ method: "DELETE"
1298
+ }).then(() => this.emit("DELETE", collection, document2));
1299
+ }
1300
+ get(collection, document2) {
1301
+ return this.api.request({ url: `/api/data/${collection}${document2 ? `/${document2}` : ""}` }).then((resp) => {
1302
+ this.emit("GET", collection, resp);
1303
+ return resp;
1304
+ });
1305
+ }
1306
+ raw(collection, operand, query, options) {
1307
+ return this.api.request({
1308
+ url: `/api/data/${collection}`,
1309
+ body: {
1310
+ operand,
1311
+ query,
1312
+ options
1313
+ }
1314
+ }).then((resp) => {
1315
+ this.emit("RAW", collection, resp);
1316
+ return resp;
1317
+ });
1318
+ }
1319
+ set(collection, document2, append = false) {
1320
+ return this.api.request({
1321
+ url: `/api/data/${collection}/${document2._id || ""}`,
1322
+ method: append ? "PATCH" : "POST",
1323
+ body: document2
1324
+ }).then((resp) => {
1325
+ this.emit("SET", collection, resp);
1326
+ return resp;
1327
+ });
1328
+ }
1329
+ }
1330
+ class Email extends P {
1331
+ constructor(api) {
1332
+ super();
1333
+ __publicField(this, "api");
1334
+ this.api = typeof api == "string" ? new Api(api) : api;
1335
+ }
1336
+ send(email) {
1337
+ let url = "/api/email";
1338
+ if (typeof email.body == "object") url += `/${email.body.template}`;
1339
+ return this.api.request({ url, body: email }).then((resp) => {
1340
+ this.emit("SENT", email);
1341
+ return resp;
1342
+ });
1343
+ }
1344
+ }
1345
+ class Groups extends P {
1346
+ constructor(api) {
1347
+ super();
1348
+ __publicField(this, "api");
1349
+ this.api = typeof api == "string" ? new Api(api) : api;
1350
+ }
1351
+ create(group) {
1352
+ return this.api.request({
1353
+ url: `/api/groups/${group.name}`,
1354
+ method: "POST",
1355
+ body: group
1356
+ }).then((resp) => {
1357
+ this.emit("CREATE", resp);
1358
+ return resp;
1359
+ });
1360
+ }
1361
+ list() {
1362
+ return this.api.request({ url: `/api/groups` }).then((resp) => {
1363
+ this.emit("LIST", resp || []);
1364
+ return resp;
1365
+ });
1366
+ }
1367
+ read(name) {
1368
+ return this.api.request({ url: `/api/groups/${name}` }).then((resp) => {
1369
+ this.emit("READ", resp);
1370
+ return resp;
1371
+ });
1372
+ }
1373
+ update(group) {
1374
+ return this.api.request({
1375
+ url: `/api/groups/${group.name}`,
1376
+ method: "PATCH",
1377
+ body: group
1378
+ }).then((resp) => {
1379
+ this.emit("UPDATE", resp);
1380
+ return resp;
1381
+ });
1382
+ }
1383
+ delete(name) {
1384
+ return this.api.request({
1385
+ url: `/api/groups/${name}`,
1386
+ method: "DELETE"
1387
+ }).then(() => this.emit("DELETE", name));
1388
+ }
1389
+ }
1390
+ class Logger {
1391
+ constructor(api, logLevel) {
1392
+ __publicField(this, "api");
1393
+ this.api = typeof api == "string" ? new Api(api) : api;
1394
+ if (logLevel != null && logLevel != "NONE") {
1395
+ window.addEventListener("error", (event) => this.error(event.error.stack));
1396
+ window.addEventListener("unhandledrejection", async (event) => this.error(event.reason.stack));
1397
+ }
1398
+ }
1399
+ buildLog(level, log) {
1400
+ return {
1401
+ time: (/* @__PURE__ */ new Date()).getTime(),
1402
+ level,
1403
+ log,
1404
+ ctx: {
1405
+ cores: navigator.hardwareConcurrency,
1406
+ mem: navigator == null ? void 0 : navigator.deviceMemory,
1407
+ res: [window.innerWidth, window.innerHeight],
1408
+ url: location.href
1409
+ }
1410
+ };
1411
+ }
1412
+ clearClientLogs() {
1413
+ return this.api.request({ url: `/api/logs/client`, method: "DELETE" });
1414
+ }
1415
+ clearServerLogs() {
1416
+ return this.api.request({ url: `/api/logs/server`, method: "DELETE" });
1417
+ }
1418
+ clientLogs(length, page) {
1419
+ const query = [length ? `length=${length}` : void 0, page ? `page=${page}` : void 0].filter((v2) => !!v2).join("&");
1420
+ return this.api.request({ url: `/api/logs/client${query ? `?${query}` : ""}` }).then((resp) => resp);
1421
+ }
1422
+ serverLogs(length, page) {
1423
+ const query = [length ? `length=${length}` : void 0, page ? `page=${page}` : void 0].filter((v2) => !!v2).join("&");
1424
+ return this.api.request({ url: `/api/logs/server${query ? `?${query}` : ""}` }).then((resp) => resp);
1425
+ }
1426
+ debug(...logs) {
1427
+ return this.api.request({ url: `/api/logs/client`, body: this.buildLog(et.DEBUG, logs) }).then(() => {
1428
+ }).catch(() => {
1429
+ });
1430
+ }
1431
+ log(...logs) {
1432
+ return this.api.request({ url: `/api/logs/client`, body: this.buildLog(et.LOG, logs) }).then(() => {
1433
+ }).catch(() => {
1434
+ });
1435
+ }
1436
+ info(...logs) {
1437
+ return this.api.request({ url: `/api/logs/client`, body: this.buildLog(et.INFO, logs) }).then(() => {
1438
+ }).catch(() => {
1439
+ });
1440
+ }
1441
+ warn(...logs) {
1442
+ return this.api.request({ url: `/api/logs/client`, body: this.buildLog(et.WARN, logs) }).then(() => {
1443
+ }).catch(() => {
1444
+ });
1445
+ }
1446
+ error(...logs) {
1447
+ return this.api.request({ url: `/api/logs/client`, body: this.buildLog(et.ERROR, logs) }).then(() => {
1448
+ }).catch(() => {
1449
+ });
1450
+ }
1451
+ }
1452
+ class Payments extends P {
1453
+ constructor(api, secret) {
1454
+ super();
1455
+ __publicField(this, "api");
1456
+ __publicField(this, "stripe");
1457
+ this.api = typeof api == "string" ? new Api(api) : api;
1458
+ const setup = (retry = 1) => {
1459
+ try {
1460
+ if (!Stripe) throw new Error("Stripe not added");
1461
+ this.stripe = Stripe(secret);
1462
+ } catch (err) {
1463
+ if (retry > 0) setTimeout(() => setup(retry--), 250);
1464
+ else console.warn("Stripe failed, did you add the library & setup your API key?", err);
1465
+ }
1466
+ };
1467
+ setup();
1468
+ }
1469
+ async charge(amount, custom = {}) {
1470
+ this.emit("CHECKOUT", amount, custom);
1471
+ const request = await this.api.request({ url: "/api/payments", body: {
1472
+ amount,
1473
+ custom
1474
+ } });
1475
+ return request.data.clientSecret;
1476
+ }
1477
+ async createForm(element, amount, custom) {
1478
+ const token = await this.charge(amount, custom);
1479
+ const form = this.stripe.elements({ clientSecret: token });
1480
+ form.create("payment").mount(element);
1481
+ return () => this.stripe.confirmPayment({
1482
+ elements: form,
1483
+ redirect: "if_required",
1484
+ confirmParams: { return_url: location.origin }
1485
+ });
1486
+ }
1487
+ async history(username) {
1488
+ const history = await this.api.request({ url: `/api/payments${username ? `/${username}` : ""}` });
1489
+ this.emit("LIST", username || null, history);
1490
+ return history;
1491
+ }
1492
+ }
1493
+ class Pdf extends P {
1494
+ constructor(api) {
1495
+ super();
1496
+ __publicField(this, "api");
1497
+ this.api = typeof api == "string" ? new Api(api) : api;
1498
+ }
1499
+ async handleResponse(resp, fileName) {
1500
+ const blob = await resp.blob();
1501
+ if (fileName) {
1502
+ const url = URL.createObjectURL(blob);
1503
+ V(url, fileName.endsWith(".pdf") ? fileName : fileName + ".pdf");
1504
+ URL.revokeObjectURL(url);
1505
+ }
1506
+ this.emit("CREATE", blob);
1507
+ return blob;
1508
+ }
1509
+ fromHtml(content, opts = {}) {
1510
+ return this.api.request({ url: `/api/pdf`, body: { html: content } }).then((resp) => this.handleResponse(resp, opts.download ? opts.fileName || (/* @__PURE__ */ new Date()).toISOString() : void 0));
1511
+ }
1512
+ fromTemplate(template, data, opts = {}) {
1513
+ return this.api.request({ url: `/api/pdf${template}`, body: data }).then((resp) => this.handleResponse(resp, opts.download ? opts.fileName || (/* @__PURE__ */ new Date()).toISOString() : void 0));
1514
+ }
1515
+ fromUrl(url, opts = {}) {
1516
+ return this.api.request({ url: `/api/pdf?url=${url}` }).then((resp) => this.handleResponse(resp, opts.download ? opts.fileName || (/* @__PURE__ */ new Date()).toISOString() : void 0));
1517
+ }
1518
+ }
1519
+ const _Socket = class _Socket {
1520
+ constructor(api) {
1521
+ __publicField(this, "api");
1522
+ __publicField(this, "url");
1523
+ __publicField(this, "connection");
1524
+ __publicField(this, "open", false);
1525
+ this.api = typeof api == "string" ? new Api(api) : api;
1526
+ this.url = this.api.url.replace("http", "ws");
1527
+ this.api.on("TOKEN", () => this.connect());
1528
+ this.connect();
1529
+ }
1530
+ close() {
1531
+ console.debug("Disconnected from Momentum");
1532
+ this.open = false;
1533
+ this.connection.close();
1534
+ }
1535
+ connect(retry = 3) {
1536
+ var _a;
1537
+ if (((_a = this.connection) == null ? void 0 : _a.readyState) < 2) this.connection.close();
1538
+ this.connection = new WebSocket(this.url + (this.api.token ? `?token=${this.api.token}` : ""));
1539
+ const timeout = setTimeout(() => {
1540
+ if (this.open) return;
1541
+ this.connection.close();
1542
+ console.error(`Momentum connection timeout`);
1543
+ if (retry > 0) this.connect(retry - 1);
1544
+ }, _Socket.timeout);
1545
+ this.connection.onclose = () => this.open = false;
1546
+ this.connection.onmessage = this.handle;
1547
+ this.connection.onopen = () => {
1548
+ this.open = true;
1549
+ clearTimeout(timeout);
1550
+ console.debug("Connected to Momentum");
1551
+ };
1552
+ }
1553
+ handle(...args) {
1554
+ console.log(args);
1555
+ }
1556
+ send(channel, payload) {
1557
+ this.connection.send(JSON.stringify({
1558
+ token: this.api.token,
1559
+ channel,
1560
+ payload
1561
+ }));
1562
+ }
1563
+ };
1564
+ __publicField(_Socket, "timeout", 1e4);
1565
+ let Socket = _Socket;
1566
+ class Storage extends P {
1567
+ constructor(api) {
1568
+ super();
1569
+ __publicField(this, "api");
1570
+ this.api = typeof api == "string" ? new Api(api) : api;
1571
+ }
1572
+ delete(path) {
1573
+ const url = (path.startsWith("/api/storage/") ? path : "/api/storage/" + path).replaceAll("//", "/");
1574
+ return this.api.request({ url, method: "DELETE" }).then(() => {
1575
+ this.emit("DELETE", url);
1576
+ });
1577
+ }
1578
+ list(path) {
1579
+ const url = (path.startsWith("/api/storage/") ? path : "/api/storage/" + path).replaceAll("//", "/");
1580
+ return this.api.request({ url: url + "?list" }).then((resp) => {
1581
+ this.emit("LIST", path, resp);
1582
+ return resp;
1583
+ });
1584
+ }
1585
+ open(path, target = "_blank") {
1586
+ const p3 = (path.startsWith("/api/storage/") ? path : "/api/storage/" + path).replaceAll(/\/{2,}/g, "/");
1587
+ const link = `${this.api.url}${p3}${this.api.token ? `?token=${this.api.token}` : ""}`;
1588
+ if (!target) return link;
1589
+ this.emit("OPEN", path);
1590
+ return window.open(link, target);
1591
+ }
1592
+ mkdir(path) {
1593
+ const p3 = (path.startsWith("/api/storage/") ? path : "/api/storage/" + path).replaceAll(/\/{2,}/g, "/");
1594
+ return this.api.request({ url: p3 + "?directory", method: "POST" });
1595
+ }
1596
+ download(path, opts = {}) {
1597
+ const p3 = ("/api/storage/" + path).replaceAll("//", "/");
1598
+ return this.api.request({ ...opts, url: p3, decode: false }).then(async (response) => {
1599
+ const blob = await response.blob();
1600
+ const name = opts.downloadAs || new URL(path).pathname.split("/").pop();
1601
+ this.emit("DOWNLOAD", path, blob);
1602
+ wt(blob, name);
1603
+ return response;
1604
+ });
1605
+ }
1606
+ upload(files, opts = "") {
1607
+ return new E(async (res, rej, prog) => {
1608
+ if (!files) files = await xt();
1609
+ if (!files || Array.isArray(files) && !files.length) return [];
1610
+ const url = this.api.url + ("/api/storage/" + (typeof opts == "string" ? opts : opts == null ? void 0 : opts.path)).replaceAll("//", "/");
1611
+ return At({
1612
+ url,
1613
+ files: Array.isArray(files) ? files : [files],
1614
+ headers: this.api.headers
1615
+ }).onProgress((p3) => {
1616
+ prog(p3);
1617
+ }).then((resp) => {
1618
+ this.emit("UPLOAD", resp);
1619
+ res(resp);
1620
+ }).catch((err) => rej(err));
1621
+ });
1622
+ }
1623
+ }
1624
+ class Users extends P {
1625
+ constructor(api) {
1626
+ super();
1627
+ __publicField(this, "api");
1628
+ __publicField(this, "listed", false);
1629
+ __publicField(this, "$cache", new BehaviorSubject([]));
1630
+ this.api = typeof api == "string" ? new Api(api) : api;
1631
+ }
1632
+ get cache() {
1633
+ return this.$cache.value;
1634
+ }
1635
+ set cache(val) {
1636
+ this.$cache.next(val);
1637
+ }
1638
+ delete(username) {
1639
+ return this.api.request({
1640
+ url: `/api/users/${username}`,
1641
+ method: "DELETE"
1642
+ }).then(() => {
1643
+ this.cache = this.cache.filter((u) => u.username != username);
1644
+ this.emit("DELETE", username);
1645
+ });
1646
+ }
1647
+ list(reload = false) {
1648
+ if (!reload && this.listed) return Promise.resolve(this.cache);
1649
+ return this.api.request({ url: `/api/users` }).then((resp) => {
1650
+ resp == null ? void 0 : resp.map((r) => {
1651
+ r.image = this.api.url + r.image + `?token=${this.api.token}`;
1652
+ return r;
1653
+ });
1654
+ this.cache = resp || [];
1655
+ this.listed = true;
1656
+ this.emit("LIST", resp || []);
1657
+ return resp;
1658
+ });
1659
+ }
1660
+ read(username, reload = false) {
1661
+ if (!reload) {
1662
+ const cached = this.cache.find((u) => u.username == username);
1663
+ if (cached) return Promise.resolve(cached);
1664
+ }
1665
+ return this.api.request({ url: `/api/users/${username}` }).then((resp) => {
1666
+ if (resp) {
1667
+ resp.image = this.api.url + resp.image + `?token=${this.api.token}`;
1668
+ this.cache = [...this.cache.filter((u) => u.username != username), resp];
1669
+ }
1670
+ this.emit("READ", resp);
1671
+ return resp;
1672
+ });
1673
+ }
1674
+ update(user) {
1675
+ return this.api.request({
1676
+ url: `/api/users/${user.username}`,
1677
+ method: "PATCH",
1678
+ body: user
1679
+ }).then((resp) => {
1680
+ if (resp) {
1681
+ resp.image = this.api.url + resp.image + `?token=${this.api.token}`;
1682
+ this.cache = this.cache.filter((u) => u.username != user.username).concat([resp]);
1683
+ }
1684
+ this.emit(user._id ? "UPDATE" : "CREATE", resp);
1685
+ return resp;
1686
+ });
1687
+ }
1688
+ uploadImage(username, file) {
1689
+ return At({
1690
+ url: this.api.url + `/api/users/${username}/image`,
1691
+ files: [file],
1692
+ headers: this.api.headers
1693
+ }).then((resp) => {
1694
+ this.emit("UPLOAD_IMAGE", username, file);
1695
+ return resp;
1696
+ });
1697
+ }
1698
+ }
1699
+ class Settings extends P {
1700
+ constructor(api) {
1701
+ super();
1702
+ __publicField(this, "api");
1703
+ __publicField(this, "$cache", new BehaviorSubject({}));
1704
+ this.api = typeof api == "string" ? new Api(api) : api;
1705
+ }
1706
+ get cache() {
1707
+ return this.$cache.value;
1708
+ }
1709
+ set cache(val) {
1710
+ this.$cache.next(val);
1711
+ }
1712
+ list(detailed = false) {
1713
+ return this.api.request({ url: `/api/settings` + (detailed ? "?detailed" : "") }).then((resp) => {
1714
+ this.cache = !detailed ? resp : Object.values(resp).reduce((acc, v2) => ({ ...acc, [v2.key]: v2.value }), {});
1715
+ this.emit("LIST", resp || []);
1716
+ return resp;
1717
+ });
1718
+ }
1719
+ delete(key) {
1720
+ return this.api.request({ url: `/api/settings/${key}`, method: "DELETE" }).then(() => {
1721
+ this.cache = { ...this.cache, [key]: void 0 };
1722
+ this.emit("DELETE", key);
1723
+ });
1724
+ }
1725
+ read(key, reload = false) {
1726
+ if (!reload && this.cache[key]) return Promise.resolve(this.cache[key]);
1727
+ return this.api.request({ url: `/api/settings/${key}` }).then((variable) => {
1728
+ if (variable) this.cache = { ...this.cache, [variable.key]: variable };
1729
+ this.emit("READ", variable);
1730
+ return variable;
1731
+ });
1732
+ }
1733
+ update(variable) {
1734
+ return this.api.request({ url: `/api/settings/${variable.key}`, body: variable }).then((variable2) => {
1735
+ if (variable2) this.cache = { ...this.cache, [variable2.key]: variable2.value };
1736
+ this.emit("UPDATE", variable2);
1737
+ return variable2;
1738
+ });
1739
+ }
1740
+ }
1741
+ class Static extends P {
1742
+ constructor(api) {
1743
+ super();
1744
+ __publicField(this, "api");
1745
+ this.api = typeof api == "string" ? new Api(api) : api;
1746
+ }
1747
+ delete(path) {
1748
+ return this.api.request({ url: `/api/static/${path}`, method: "DELETE" }).then(() => {
1749
+ this.emit("DELETE", path);
1750
+ });
1751
+ }
1752
+ list(path) {
1753
+ const url = ("/api/static/" + path).replaceAll("//", "/");
1754
+ return this.api.request({ url }).then((resp) => {
1755
+ this.emit("LIST", path, resp || []);
1756
+ return resp;
1757
+ });
1758
+ }
1759
+ upload(files, path = "/") {
1760
+ const data = new FormData();
1761
+ (Array.isArray(files) ? files : [files]).forEach((f) => data.append("file", f));
1762
+ return this.api.request({ url: "/api/static" + path, body: data }).then((resp) => {
1763
+ this.emit("UPLOAD", resp || []);
1764
+ return resp;
1765
+ });
1766
+ }
1767
+ }
1768
+ class Momentum extends P {
1769
+ constructor(url, opts) {
1770
+ super();
1771
+ __publicField(this, "api");
1772
+ __publicField(this, "actions");
1773
+ __publicField(this, "auth");
1774
+ __publicField(this, "data");
1775
+ __publicField(this, "email");
1776
+ __publicField(this, "groups");
1777
+ __publicField(this, "logger");
1778
+ __publicField(this, "payments");
1779
+ __publicField(this, "pdf");
1780
+ __publicField(this, "settings");
1781
+ __publicField(this, "socket");
1782
+ __publicField(this, "static");
1783
+ __publicField(this, "storage");
1784
+ __publicField(this, "users");
1785
+ this.api = new Api(url, opts == null ? void 0 : opts.api);
1786
+ this.actions = new Actions(this.api);
1787
+ this.auth = new Auth(this.api, {
1788
+ persist: (opts == null ? void 0 : opts.persist) ?? true,
1789
+ loginUi: opts == null ? void 0 : opts.loginUi
1790
+ });
1791
+ this.data = new Data(this.api);
1792
+ this.email = new Email(this.api);
1793
+ this.groups = new Groups(this.api);
1794
+ this.logger = new Logger(this.api, opts == null ? void 0 : opts.logLevel);
1795
+ if (opts == null ? void 0 : opts.stripeSecret) this.payments = new Payments(this.api, opts.stripeSecret);
1796
+ this.pdf = new Pdf(this.api);
1797
+ this.settings = new Settings(this.api);
1798
+ this.static = new Static(this.api);
1799
+ this.storage = new Storage(this.api);
1800
+ this.users = new Users(this.api);
1801
+ if (opts == null ? void 0 : opts.socket) this.socket = new Socket(this.api);
1802
+ this.api.on("*", (event, ...args) => this.emit(`API::${event}`, ...args));
1803
+ this.actions.on("*", (event, ...args) => this.emit(`ACTIONS::${event}`, ...args));
1804
+ this.auth.on("*", (event, ...args) => this.emit(`AUTH::${event}`, ...args));
1805
+ this.data.on("*", (event, ...args) => this.emit(`DATA::${event}`, ...args));
1806
+ this.email.on("*", (event, ...args) => this.emit(`EMAIL::${event}`, ...args));
1807
+ this.groups.on("*", (event, ...args) => this.emit(`GROUPS::${event}`, ...args));
1808
+ if (this.payments) this.payments.on("*", (event, ...args) => this.emit(`PAYMENT::${event}`, ...args));
1809
+ this.pdf.on("*", (event, ...args) => this.emit(`PDF::${event}`, ...args));
1810
+ this.settings.on("*", (event, ...args) => this.emit(`SETTINGS::${event}`, ...args));
1811
+ this.static.on("*", (event, ...args) => this.emit(`STATIC::${event}`, ...args));
1812
+ this.storage.on("*", (event, ...args) => this.emit(`STORAGE::${event}`, ...args));
1813
+ this.users.on("*", (event, ...args) => this.emit(`USERS::${event}`, ...args));
1814
+ this.users.on("*", (event, ...args) => {
1815
+ var _a;
1816
+ if (Array.isArray(args[0])) {
1817
+ const u = args[0].find((u2) => {
1818
+ var _a2;
1819
+ return u2._id == ((_a2 = this.auth.user) == null ? void 0 : _a2._id);
1820
+ });
1821
+ if (u) this.auth.user = u;
1822
+ } else if (args[0]._id == ((_a = this.auth.user) == null ? void 0 : _a._id)) {
1823
+ this.auth.user = args[0];
1824
+ }
1825
+ });
1826
+ }
1827
+ }
1828
+ export {
1829
+ ActionType,
1830
+ Actions,
1831
+ Api,
1832
+ Auth,
1833
+ Data,
1834
+ Email,
1835
+ Groups,
1836
+ Logger,
1837
+ Momentum,
1838
+ Payments,
1839
+ Pdf,
1840
+ Settings,
1841
+ Socket,
1842
+ Static,
1843
+ Storage,
1844
+ Totp,
1845
+ Users
1846
+ };