@ztimson/momentum 0.20.0 → 0.27.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.
@@ -0,0 +1,99 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Storage = void 0;
4
+ const api_1 = require("./api");
5
+ const utils_1 = require("@ztimson/utils");
6
+ class Storage extends utils_1.TypedEmitter {
7
+ api;
8
+ constructor(api) {
9
+ super();
10
+ this.api = typeof api == 'string' ? new api_1.Api(api) : api;
11
+ }
12
+ delete(path) {
13
+ const url = (path.startsWith('/api/storage/') ? path : '/api/storage/' + path).replaceAll('//', '/');
14
+ return this.api.request({ url, method: 'DELETE' }).then(() => {
15
+ this.emit('DELETE', url);
16
+ });
17
+ }
18
+ list(path) {
19
+ const url = (path.startsWith('/api/storage/') ? path : '/api/storage/' + path).replaceAll('//', '/');
20
+ return this.api.request({ url: url + '?list' }).then(resp => {
21
+ this.emit('LIST', path, resp);
22
+ return resp;
23
+ });
24
+ }
25
+ open(path, target = '_blank') {
26
+ const p = (path.startsWith('/api/storage/') ? path : '/api/storage/' + path).replaceAll(/\/{2,}/g, '/');
27
+ const link = `${this.api.url}${p}${this.api.token ? `?token=${this.api.token}` : ''}`;
28
+ if (!target)
29
+ return link;
30
+ this.emit('OPEN', path);
31
+ return window.open(link, target);
32
+ }
33
+ mkdir(path) {
34
+ const p = (path.startsWith('/api/storage/') ? path : '/api/storage/' + path).replaceAll(/\/{2,}/g, '/');
35
+ return this.api.request({ url: p + '?directory', method: 'POST' });
36
+ }
37
+ download(path, opts = {}) {
38
+ return new utils_1.PromiseProgress((res, rej, progress) => {
39
+ const p = ('/api/storage/' + path).replaceAll('//', '/');
40
+ this.api.request({ ...opts, url: p, skipConverting: true }).then((response) => {
41
+ if (!response.ok)
42
+ return rej(response.statusText);
43
+ const contentLength = response.headers.get('Content-Length');
44
+ const total = contentLength ? parseInt(contentLength, 10) : 0;
45
+ let chunks = [], loaded = 0;
46
+ const reader = response.body?.getReader();
47
+ const process = (result) => {
48
+ if (result.done) {
49
+ progress(1);
50
+ const blob = new Blob(chunks);
51
+ const name = opts.downloadAs || new URL(response.url).pathname.split('/').pop();
52
+ const url = URL.createObjectURL(blob);
53
+ (0, utils_1.download)(url, name.includes('.') ? name : name + '.zip');
54
+ URL.revokeObjectURL(url);
55
+ this.emit('DOWNLOAD', path, blob);
56
+ res(blob);
57
+ }
58
+ else {
59
+ const chunk = result.value;
60
+ chunks.push(chunk);
61
+ loaded += chunk.length;
62
+ progress(loaded / total);
63
+ reader.read().then(process);
64
+ }
65
+ };
66
+ reader?.read().then(process);
67
+ });
68
+ });
69
+ }
70
+ async upload(files, opts = '') {
71
+ const fileBrowser = () => {
72
+ return new Promise(res => {
73
+ const input = document.createElement('input');
74
+ input.type = 'file';
75
+ input.accept = opts?.accept || '*';
76
+ input.style.display = 'none';
77
+ input.multiple = !!opts?.multiple;
78
+ input.onblur = input.onchange = async () => {
79
+ res(Array.from(input.files));
80
+ input.remove();
81
+ };
82
+ document.body.appendChild(input);
83
+ input.click();
84
+ });
85
+ };
86
+ if (!files)
87
+ files = await fileBrowser();
88
+ if (!files || Array.isArray(files) && !files.length)
89
+ return [];
90
+ const data = new FormData();
91
+ const p = ('/api/storage/' + (typeof opts == 'string' ? opts : opts?.path)).replaceAll('//', '/');
92
+ (Array.isArray(files) ? files : [files]).forEach(f => data.append('file', f));
93
+ return this.api.request({ url: p, body: data }).then(resp => {
94
+ this.emit('UPLOAD', resp);
95
+ return resp;
96
+ });
97
+ }
98
+ }
99
+ exports.Storage = Storage;
package/dist/users.d.ts CHANGED
@@ -1,13 +1,26 @@
1
1
  import { Api } from './api';
2
- import { User } from './auth';
3
- import { TypedEmitter, TypedEvents } from '@ztimson/utils';
2
+ import { TypedEmitter, type TypedEvents } from '@ztimson/utils';
4
3
  import { BehaviorSubject } from 'rxjs';
5
-
4
+ import type { Meta } from './core';
5
+ export type User = Meta & {
6
+ username: string;
7
+ name: string;
8
+ email: string;
9
+ image: string;
10
+ disabled?: boolean;
11
+ groups: string[];
12
+ permissions: string[];
13
+ notes: string;
14
+ custom?: any;
15
+ lastLogin?: number | null;
16
+ totp?: false | 'app' | 'email' | 'phone';
17
+ };
6
18
  export type UserEvents = TypedEvents & {
7
19
  LIST: (users: User[]) => any;
8
20
  READ: (user: User) => any;
9
21
  UPDATE: (user: User) => any;
10
22
  DELETE: (username: string) => any;
23
+ UPLOAD_IMAGE: (file: File) => any;
11
24
  };
12
25
  export declare class Users extends TypedEmitter<UserEvents> {
13
26
  private readonly api;
@@ -20,5 +33,6 @@ export declare class Users extends TypedEmitter<UserEvents> {
20
33
  list(reload?: boolean): Promise<User[]>;
21
34
  read(username: string, reload?: boolean): Promise<User>;
22
35
  update(user: User): Promise<User>;
36
+ uploadImage(username: string, file: File): Promise<unknown>;
23
37
  }
24
38
  //# sourceMappingURL=users.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"users.d.ts","sourceRoot":"","sources":["../src/users.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,GAAG,EAAC,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAC,KAAK,IAAI,EAAC,MAAM,QAAQ,CAAC;AACjC,OAAO,EAAC,YAAY,EAAE,KAAK,WAAW,EAAC,MAAM,gBAAgB,CAAC;AAC9D,OAAO,EAAC,eAAe,EAAC,MAAM,MAAM,CAAC;AAErC,MAAM,MAAM,UAAU,GAAG,WAAW,GAAG;IACtC,IAAI,EAAE,CAAC,KAAK,EAAE,IAAI,EAAE,KAAK,GAAG,CAAC;IAC7B,IAAI,EAAE,CAAC,IAAI,EAAE,IAAI,KAAK,GAAG,CAAC;IAC1B,MAAM,EAAE,CAAC,IAAI,EAAE,IAAI,KAAK,GAAG,CAAC;IAC5B,MAAM,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,GAAG,CAAC;CAClC,CAAC;AAEF,qBAAa,KAAM,SAAQ,YAAY,CAAC,UAAU,CAAC;IAClD,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAO;IAC3B,OAAO,CAAC,MAAM,CAAS;IAEvB,MAAM,0BAAkC;IACxC,IAAI,KAAK,WAAgC;IACzC,IAAI,KAAK,CAAC,GAAG,QAAA,EAA4B;gBAE7B,GAAG,EAAE,GAAG,GAAG,MAAM;IAK7B,MAAM,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAUvC,IAAI,CAAC,MAAM,UAAM,GAAG,OAAO,CAAC,IAAI,EAAE,CAAC;IAUnC,IAAI,CAAC,QAAQ,EAAE,MAAM,EAAE,MAAM,UAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAYnD,MAAM,CAAC,IAAI,EAAE,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;CAWjC"}
1
+ {"version":3,"file":"users.d.ts","sourceRoot":"","sources":["../src/users.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,GAAG,EAAC,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAC,YAAY,EAAE,KAAK,WAAW,EAAC,MAAM,gBAAgB,CAAC;AAC9D,OAAO,EAAC,eAAe,EAAC,MAAM,MAAM,CAAC;AACrC,OAAO,KAAK,EAAC,IAAI,EAAC,MAAM,QAAQ,CAAC;AAEjC,MAAM,MAAM,IAAI,GAAG,IAAI,GAAG;IACzB,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,MAAM,EAAE,MAAM,EAAE,CAAC;IACjB,WAAW,EAAE,MAAM,EAAE,CAAC;IACtB,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,CAAC,EAAE,GAAG,CAAC;IACb,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B,IAAI,CAAC,EAAE,KAAK,GAAG,KAAK,GAAG,OAAO,GAAG,OAAO,CAAC;CACzC,CAAA;AAED,MAAM,MAAM,UAAU,GAAG,WAAW,GAAG;IACtC,IAAI,EAAE,CAAC,KAAK,EAAE,IAAI,EAAE,KAAK,GAAG,CAAC;IAC7B,IAAI,EAAE,CAAC,IAAI,EAAE,IAAI,KAAK,GAAG,CAAC;IAC1B,MAAM,EAAE,CAAC,IAAI,EAAE,IAAI,KAAK,GAAG,CAAC;IAC5B,MAAM,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,GAAG,CAAC;IAClC,YAAY,EAAE,CAAC,IAAI,EAAE,IAAI,KAAK,GAAG,CAAC;CAClC,CAAC;AAEF,qBAAa,KAAM,SAAQ,YAAY,CAAC,UAAU,CAAC;IAClD,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAO;IAC3B,OAAO,CAAC,MAAM,CAAS;IAEvB,MAAM,0BAAkC;IACxC,IAAI,KAAK,WAAgC;IACzC,IAAI,KAAK,CAAC,GAAG,QAAA,EAA4B;gBAE7B,GAAG,EAAE,GAAG,GAAG,MAAM;IAK7B,MAAM,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAUvC,IAAI,CAAC,MAAM,UAAM,GAAG,OAAO,CAAC,IAAI,EAAE,CAAC;IAcnC,IAAI,CAAC,QAAQ,EAAE,MAAM,EAAE,MAAM,UAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAanD,MAAM,CAAC,IAAI,EAAE,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;IAajC,WAAW,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI;CAQxC"}
package/dist/users.js ADDED
@@ -0,0 +1,76 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Users = void 0;
4
+ const api_1 = require("./api");
5
+ const utils_1 = require("@ztimson/utils");
6
+ const rxjs_1 = require("rxjs");
7
+ class Users extends utils_1.TypedEmitter {
8
+ api;
9
+ listed = false;
10
+ $cache = new rxjs_1.BehaviorSubject([]);
11
+ get cache() { return this.$cache.value; }
12
+ set cache(val) { this.$cache.next(val); }
13
+ constructor(api) {
14
+ super();
15
+ this.api = typeof api == 'string' ? new api_1.Api(api) : api;
16
+ }
17
+ delete(username) {
18
+ return this.api.request({
19
+ url: `/api/users/${username}`,
20
+ method: 'DELETE'
21
+ }).then(() => {
22
+ this.cache = this.cache.filter(u => u.username != username);
23
+ this.emit('DELETE', username);
24
+ });
25
+ }
26
+ list(reload = false) {
27
+ if (!reload && this.listed)
28
+ return Promise.resolve(this.cache);
29
+ return this.api.request({ url: `/api/users` }).then(resp => {
30
+ resp.map(r => {
31
+ r.image = this.api.url + r.image + `?token=${this.api.token}`;
32
+ return r;
33
+ });
34
+ this.cache = resp;
35
+ this.listed = true;
36
+ this.emit('LIST', resp);
37
+ return resp;
38
+ });
39
+ }
40
+ read(username, reload = false) {
41
+ if (!reload) {
42
+ const cached = this.cache.find(u => u.username == username);
43
+ if (cached)
44
+ return Promise.resolve(cached);
45
+ }
46
+ return this.api.request({ url: `/api/users/${username}` }).then(resp => {
47
+ resp.image = this.api.url + resp.image + `?token=${this.api.token}`;
48
+ if (resp)
49
+ this.cache = [...this.cache.filter(u => u.username != username), resp];
50
+ this.emit('READ', resp);
51
+ return resp;
52
+ });
53
+ }
54
+ update(user) {
55
+ return this.api.request({
56
+ url: `/api/users/${user.username}`,
57
+ method: 'PATCH',
58
+ body: user
59
+ }).then(resp => {
60
+ resp.image = this.api.url + resp.image + `?token=${this.api.token}`;
61
+ if (resp)
62
+ this.cache = this.cache.filter(u => u.username != user.username).concat([resp]);
63
+ this.emit('UPDATE', resp);
64
+ return resp;
65
+ });
66
+ }
67
+ uploadImage(username, file) {
68
+ const data = new FormData();
69
+ data.append('file', file);
70
+ return this.api.request({ url: `/api/users/${username}/image`, body: data }).then(resp => {
71
+ this.emit('UPLOAD_IMAGE', file);
72
+ return resp;
73
+ });
74
+ }
75
+ }
76
+ exports.Users = Users;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ztimson/momentum",
3
- "version": "0.20.0",
3
+ "version": "0.27.1",
4
4
  "description": "Client library for momentum",
5
5
  "keywords": [
6
6
  "Momentum"
@@ -10,30 +10,27 @@
10
10
  "type": "git",
11
11
  "url": "https://git.zakscode.com/ztimson/momentum"
12
12
  },
13
- "main": "dist/momentum.cjs",
14
- "module": "dist/momentum.mjs",
13
+ "main": "dist/index.js",
14
+ "module": "dist/index.mjs",
15
15
  "types": "dist/index.d.ts",
16
+ "typings": "dist/index.d.ts",
16
17
  "exports": {
17
- "types": "./dist/index.d.ts",
18
- "import": "./dist/momentum.mjs",
19
- "require": "./dist/momentum.cjs"
18
+ "import": "./dist/index.mjs",
19
+ "require": "./dist/index.js",
20
+ "types": "./dist/index.d.ts"
20
21
  },
21
22
  "scripts": {
22
- "prebuild": "node -e \"const fs=require('fs');fs.cpSync('../README.md','./README.md')\"",
23
- "build": "npx tsc && npx vite build",
24
- "postbuild": "node -e \"const fs=require('fs');fs.cpSync('dist/momentum.cjs','../server/public/momentum.cjs');fs.cpSync('dist/momentum.mjs','../server/public/momentum.mjs')\"",
25
- "watch": "npx vite build --watch"
23
+ "prebuild": "bun -e \"const fs=require('fs');fs.cpSync('../README.md','./README.md')\"",
24
+ "build": "tsc && bun build --target browser --outfile dist/index.mjs --minify src/index.ts",
25
+ "postbuild": "bun -e \"const fs=require('fs');fs.cpSync('dist/index.mjs','../server/public/momentum.mjs')\"",
26
+ "watch": "tsc -w & bun build --watch --target browser --outfile dist/index.mjs --minify src/index.ts"
26
27
  },
27
28
  "dependencies": {
28
- "@ztimson/utils": "^0.11.3",
29
+ "@ztimson/utils": "^0.12.3",
29
30
  "rxjs": "^7.8.1"
30
31
  },
31
32
  "devDependencies": {
32
- "@types/node": "^18.14.0",
33
- "rxjs": "^7.8.1",
34
- "typescript": "^5.3.3",
35
- "vite": "^5.0.12",
36
- "vite-plugin-dts": "^3.7.2"
33
+ "typescript": "^5.3.3"
37
34
  },
38
35
  "files": [
39
36
  "dist"
package/dist/momentum.cjs DELETED
@@ -1,4 +0,0 @@
1
- (function(h,y){typeof exports=="object"&&typeof module<"u"?y(exports):typeof define=="function"&&define.amd?define(["exports"],y):(h=typeof globalThis<"u"?globalThis:h||self,y(h.utils={}))})(this,function(h){"use strict";var Ht=Object.defineProperty;var Wt=(h,y,L)=>y in h?Ht(h,y,{enumerable:!0,configurable:!0,writable:!0,value:L}):h[y]=L;var a=(h,y,L)=>Wt(h,typeof y!="symbol"?y+"":y,L);var y=Object.defineProperty,L=(i,e,t)=>e in i?y(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,l=(i,e,t)=>(L(i,typeof e!="symbol"?e+"":e,t),t);function St(i,e=!1){if(i==null)throw new Error("Cannot clean a NULL value");return Array.isArray(i)?i=i.filter(t=>t!=null):Object.entries(i).forEach(([t,r])=>{(e&&r===void 0||!e&&r==null)&&delete i[t]}),i}function K(i,e){const t=typeof i,r=typeof e;return t!="object"||i==null||r!="object"||e==null?t=="function"&&r=="function"?i.toString()==e.toString():i===e:Object.keys(i).length!=Object.keys(e).length?!1:Object.keys(i).every(n=>K(i[n],e[n]))}function z(i,e){const t=document.createElement("a");t.href=i,t.download=e,document.body.appendChild(t),t.click(),document.body.removeChild(t)}class d{constructor(){l(this,"listeners",{})}static emit(e,...t){(this.listeners["*"]||[]).forEach(r=>r(e,...t)),(this.listeners[e.toString()]||[]).forEach(r=>r(...t))}static off(e,t){const r=e.toString();this.listeners[r]=(this.listeners[r]||[]).filter(n=>n===t)}static on(e,t){var r;const n=e.toString();return this.listeners[n]||(this.listeners[n]=[]),(r=this.listeners[n])==null||r.push(t),()=>this.off(e,t)}static once(e,t){return new Promise(r=>{const n=this.on(e,(...s)=>{r(s.length==1?s[0]:s),t&&t(...s),n()})})}emit(e,...t){(this.listeners["*"]||[]).forEach(r=>r(e,...t)),(this.listeners[e]||[]).forEach(r=>r(...t))}off(e,t){this.listeners[e]=(this.listeners[e]||[]).filter(r=>r===t)}on(e,t){var r;return this.listeners[e]||(this.listeners[e]=[]),(r=this.listeners[e])==null||r.push(t),()=>this.off(e,t)}once(e,t){return new Promise(r=>{const n=this.on(e,(...s)=>{r(s.length==1?s[0]:s),t&&t(...s),n()})})}}l(d,"listeners",{});class T extends Error{constructor(e,t){super(e),l(this,"_code"),t!=null&&(this._code=t)}get code(){return this._code||this.constructor.code}set code(e){this._code=e}static from(e){const t=Number(e.statusCode)??Number(e.code),r=new this(e.message||e.toString());return Object.assign(r,{stack:e.stack,...e,code:t??void 0})}static instanceof(e){return e.constructor.code!=null}toString(){return this.message||super.toString()}}l(T,"code",500);class Lt extends T{constructor(e="Bad Request"){super(e)}static instanceof(e){return e.constructor.code==this.code}}l(Lt,"code",400);class Tt extends T{constructor(e="Unauthorized"){super(e)}static instanceof(e){return e.constructor.code==this.code}}l(Tt,"code",401);class Ot extends T{constructor(e="Forbidden"){super(e)}static instanceof(e){return e.constructor.code==this.code}}l(Ot,"code",403);class $t extends T{constructor(e="Not Found"){super(e)}static instanceof(e){return e.constructor.code==this.code}}l($t,"code",404);class At extends T{constructor(e="Internal Server Error"){super(e)}static instanceof(e){return e.constructor.code==this.code}}l(At,"code",500);const A={CLEAR:"\x1B[0m",BRIGHT:"\x1B[1m",DIM:"\x1B[2m",UNDERSCORE:"\x1B[4m",BLINK:"\x1B[5m",REVERSE:"\x1B[7m",HIDDEN:"\x1B[8m"},q={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 O=(i=>(i[i.ERROR=0]="ERROR",i[i.WARN=1]="WARN",i[i.INFO=2]="INFO",i[i.LOG=3]="LOG",i[i.DEBUG=4]="DEBUG",i))(O||{});l(class g extends d{constructor(e){super(),this.namespace=e}pad(e,t,r,n=!1){const s=e.toString(),o=t-s.length;if(o<=0)return s;const u=Array(~~(o/r.length)).fill(r).join("");return n?s+u:u+s}format(...e){const t=new Date;return`${`${t.getFullYear()}-${t.getMonth()+1}-${t.getDate()} ${this.pad(t.getHours().toString(),2,"0")}:${this.pad(t.getMinutes().toString(),2,"0")}:${this.pad(t.getSeconds().toString(),2,"0")}.${this.pad(t.getMilliseconds().toString(),3,"0",!0)}`}${this.namespace?` [${this.namespace}]`:""} ${e.join(" ")}`}debug(...e){if(g.LOG_LEVEL<4)return;const t=this.format(...e);g.emit(4,t),console.debug(q.LIGHT_GREY+t+A.CLEAR)}log(...e){if(g.LOG_LEVEL<3)return;const t=this.format(...e);g.emit(3,t),console.log(A.CLEAR+t)}info(...e){if(g.LOG_LEVEL<2)return;const t=this.format(...e);g.emit(2,t),console.info(q.BLUE+t+A.CLEAR)}warn(...e){if(g.LOG_LEVEL<1)return;const t=this.format(...e);g.emit(1,t),console.warn(q.YELLOW+t+A.CLEAR)}error(...e){if(g.LOG_LEVEL<0)return;const t=this.format(...e);g.emit(0,t),console.error(q.RED+t+A.CLEAR)}},"LOG_LEVEL",4);class _t extends Promise{constructor(e){super((t,r)=>e(n=>t(n),n=>r(n),n=>this.progress=n)),l(this,"listeners",[]),l(this,"_progress",0)}get progress(){return this._progress}set progress(e){e!=this._progress&&(this._progress=e,this.listeners.forEach(t=>t(e)))}onProgress(e){return this.listeners.push(e),this}}const k=class S{constructor(e={}){l(this,"interceptors",{}),l(this,"headers",{}),this.opts=e,this.headers=e.headers||{},e.interceptors&&e.interceptors.forEach(t=>S.addInterceptor(t))}static addInterceptor(e){const t=Object.keys(S.interceptors).length.toString();return S.interceptors[t]=e,()=>{S.interceptors[t]=null}}addInterceptor(e){const t=Object.keys(this.interceptors).length.toString();return this.interceptors[t]=e,()=>{this.interceptors[t]=null}}async request(e={}){var t,r;if(!this.opts.url&&!e.url)throw new Error("URL needs to be set");let n=((t=e.url)!=null&&t.startsWith("http")?e.url:(this.opts.url||"")+(e.url||"")).replace(/([^:]\/)\/+/g,"$1");if(e.fragment&&(n.includes("#")?n.replace(/#.*(\?|\n)/g,(o,u)=>`#${e.fragment}${u}`):n+="#"+e.fragment),e.query){const o=Array.isArray(e.query)?e.query:Object.keys(e.query).map(u=>({key:u,value:e.query[u]}));n+=(n.includes("?")?"&":"?")+o.map(u=>`${u.key}=${u.value}`).join("&")}const s=St({"Content-Type":e.body&&!(e.body instanceof FormData)?"application/json":void 0,...S.headers,...this.headers,...e.headers});return fetch(n,{headers:s,method:e.method||(e.body?"POST":"GET"),body:(r=s["Content-Type"])!=null&&r.startsWith("application/json")&&e.body?JSON.stringify(e.body):e.body}).then(async o=>{for(let f of[...Object.values(S.interceptors),...Object.values(this.interceptors)])await new Promise(v=>f(o,()=>v()));const u=await(async()=>{var f,v;return!e.skipConverting&&(f=o.headers.get("Content-Type"))!=null&&f.startsWith("application/json")?await o.json():!e.skipConverting&&(v=o.headers.get("Content-Type"))!=null&&v.startsWith("text/plain")?await o.text():o})();if(o.ok)return u;const c=o.statusText||(typeof u=="string"?u:null);throw c?new Error(c):u})}};l(k,"interceptors",{}),l(k,"headers",{});let Rt=k;class p extends Rt{constructor(t=location.origin,r={}){r.url=t;super(r);a(this,"emitter",new d);a(this,"_token",null);a(this,"emit",this.emitter.emit.bind(this.emitter));a(this,"off",this.emitter.off.bind(this.emitter));a(this,"on",this.emitter.on.bind(this.emitter));a(this,"once",this.emitter.once.bind(this.emitter));this.url=t,this.opts=r}get token(){return this._token}set token(t){t!=this._token&&(this._token=t,this.headers.Authorization=`Bearer ${t}`,this.emit("TOKEN",t))}request(t){const r=super.request(t).then(n=>(this.emit("RESPONSE",n,t),n)).catch(n=>{throw this.emit("REJECTED",n,t),n});return this.emit("REQUEST",r,t),r}}var B=function(i,e){return B=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,r){t.__proto__=r}||function(t,r){for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])},B(i,e)};function _(i,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");B(i,e);function t(){this.constructor=i}i.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}function G(i){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&i[e],r=0;if(t)return t.call(i);if(i&&typeof i.length=="number")return{next:function(){return i&&r>=i.length&&(i=void 0),{value:i&&i[r++],done:!i}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function N(i,e){var t=typeof Symbol=="function"&&i[Symbol.iterator];if(!t)return i;var r=t.call(i),n,s=[],o;try{for(;(e===void 0||e-- >0)&&!(n=r.next()).done;)s.push(n.value)}catch(u){o={error:u}}finally{try{n&&!n.done&&(t=r.return)&&t.call(r)}finally{if(o)throw o.error}}return s}function H(i,e,t){if(t||arguments.length===2)for(var r=0,n=e.length,s;r<n;r++)(s||!(r in e))&&(s||(s=Array.prototype.slice.call(e,0,r)),s[r]=e[r]);return i.concat(s||Array.prototype.slice.call(e))}typeof SuppressedError=="function"&&SuppressedError;function b(i){return typeof i=="function"}function J(i){var e=function(r){Error.call(r),r.stack=new Error().stack},t=i(e);return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}var W=J(function(i){return function(t){i(this),this.message=t?t.length+` errors occurred during unsubscription:
2
- `+t.map(function(r,n){return n+1+") "+r.toString()}).join(`
3
- `):"",this.name="UnsubscriptionError",this.errors=t}});function M(i,e){if(i){var t=i.indexOf(e);0<=t&&i.splice(t,1)}}var P=function(){function i(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return i.prototype.unsubscribe=function(){var e,t,r,n,s;if(!this.closed){this.closed=!0;var o=this._parentage;if(o)if(this._parentage=null,Array.isArray(o))try{for(var u=G(o),c=u.next();!c.done;c=u.next()){var f=c.value;f.remove(this)}}catch(m){e={error:m}}finally{try{c&&!c.done&&(t=u.return)&&t.call(u)}finally{if(e)throw e.error}}else o.remove(this);var v=this.initialTeardown;if(b(v))try{v()}catch(m){s=m instanceof W?m.errors:[m]}var R=this._finalizers;if(R){this._finalizers=null;try{for(var w=G(R),E=w.next();!E.done;E=w.next()){var C=E.value;try{Z(C)}catch(m){s=s??[],m instanceof W?s=H(H([],N(s)),N(m.errors)):s.push(m)}}}catch(m){r={error:m}}finally{try{E&&!E.done&&(n=w.return)&&n.call(w)}finally{if(r)throw r.error}}}if(s)throw new W(s)}},i.prototype.add=function(e){var t;if(e&&e!==this)if(this.closed)Z(e);else{if(e instanceof i){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=(t=this._finalizers)!==null&&t!==void 0?t:[]).push(e)}},i.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},i.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},i.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&M(t,e)},i.prototype.remove=function(e){var t=this._finalizers;t&&M(t,e),e instanceof i&&e._removeParent(this)},i.EMPTY=function(){var e=new i;return e.closed=!0,e}(),i}(),Q=P.EMPTY;function X(i){return i instanceof P||i&&"closed"in i&&b(i.remove)&&b(i.add)&&b(i.unsubscribe)}function Z(i){b(i)?i():i.unsubscribe()}var tt={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1},et={setTimeout:function(i,e){for(var t=[],r=2;r<arguments.length;r++)t[r-2]=arguments[r];return setTimeout.apply(void 0,H([i,e],N(t)))},clearTimeout:function(i){var e=et.delegate;return((e==null?void 0:e.clearTimeout)||clearTimeout)(i)},delegate:void 0};function qt(i){et.setTimeout(function(){throw i})}function rt(){}function x(i){i()}var it=function(i){_(e,i);function e(t){var r=i.call(this)||this;return r.isStopped=!1,t?(r.destination=t,X(t)&&t.add(r)):r.destination=Dt,r}return e.create=function(t,r,n){return new Y(t,r,n)},e.prototype.next=function(t){this.isStopped||this._next(t)},e.prototype.error=function(t){this.isStopped||(this.isStopped=!0,this._error(t))},e.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},e.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,i.prototype.unsubscribe.call(this),this.destination=null)},e.prototype._next=function(t){this.destination.next(t)},e.prototype._error=function(t){try{this.destination.error(t)}finally{this.unsubscribe()}},e.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},e}(P),Pt=Function.prototype.bind;function F(i,e){return Pt.call(i,e)}var xt=function(){function i(e){this.partialObserver=e}return i.prototype.next=function(e){var t=this.partialObserver;if(t.next)try{t.next(e)}catch(r){U(r)}},i.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(r){U(r)}else U(e)},i.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(t){U(t)}},i}(),Y=function(i){_(e,i);function e(t,r,n){var s=i.call(this)||this,o;if(b(t)||!t)o={next:t??void 0,error:r??void 0,complete:n??void 0};else{var u;s&&tt.useDeprecatedNextContext?(u=Object.create(t),u.unsubscribe=function(){return s.unsubscribe()},o={next:t.next&&F(t.next,u),error:t.error&&F(t.error,u),complete:t.complete&&F(t.complete,u)}):o=t}return s.destination=new xt(o),s}return e}(it);function U(i){qt(i)}function Ut(i){throw i}var Dt={closed:!0,next:rt,error:Ut,complete:rt},It=function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"}();function jt(i){return i}function Ct(i){return i.length===0?jt:i.length===1?i[0]:function(t){return i.reduce(function(r,n){return n(r)},t)}}var nt=function(){function i(e){e&&(this._subscribe=e)}return i.prototype.lift=function(e){var t=new i;return t.source=this,t.operator=e,t},i.prototype.subscribe=function(e,t,r){var n=this,s=Bt(e)?e:new Y(e,t,r);return x(function(){var o=n,u=o.operator,c=o.source;s.add(u?u.call(s,c):c?n._subscribe(s):n._trySubscribe(s))}),s},i.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){e.error(t)}},i.prototype.forEach=function(e,t){var r=this;return t=st(t),new t(function(n,s){var o=new Y({next:function(u){try{e(u)}catch(c){s(c),o.unsubscribe()}},error:s,complete:n});r.subscribe(o)})},i.prototype._subscribe=function(e){var t;return(t=this.source)===null||t===void 0?void 0:t.subscribe(e)},i.prototype[It]=function(){return this},i.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Ct(e)(this)},i.prototype.toPromise=function(e){var t=this;return e=st(e),new e(function(r,n){var s;t.subscribe(function(o){return s=o},function(o){return n(o)},function(){return r(s)})})},i.create=function(e){return new i(e)},i}();function st(i){var e;return(e=i??tt.Promise)!==null&&e!==void 0?e:Promise}function kt(i){return i&&b(i.next)&&b(i.error)&&b(i.complete)}function Bt(i){return i&&i instanceof it||kt(i)&&X(i)}var Gt=J(function(i){return function(){i(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),ot=function(i){_(e,i);function e(){var t=i.call(this)||this;return t.closed=!1,t.currentObservers=null,t.observers=[],t.isStopped=!1,t.hasError=!1,t.thrownError=null,t}return e.prototype.lift=function(t){var r=new ut(this,this);return r.operator=t,r},e.prototype._throwIfClosed=function(){if(this.closed)throw new Gt},e.prototype.next=function(t){var r=this;x(function(){var n,s;if(r._throwIfClosed(),!r.isStopped){r.currentObservers||(r.currentObservers=Array.from(r.observers));try{for(var o=G(r.currentObservers),u=o.next();!u.done;u=o.next()){var c=u.value;c.next(t)}}catch(f){n={error:f}}finally{try{u&&!u.done&&(s=o.return)&&s.call(o)}finally{if(n)throw n.error}}}})},e.prototype.error=function(t){var r=this;x(function(){if(r._throwIfClosed(),!r.isStopped){r.hasError=r.isStopped=!0,r.thrownError=t;for(var n=r.observers;n.length;)n.shift().error(t)}})},e.prototype.complete=function(){var t=this;x(function(){if(t._throwIfClosed(),!t.isStopped){t.isStopped=!0;for(var r=t.observers;r.length;)r.shift().complete()}})},e.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(e.prototype,"observed",{get:function(){var t;return((t=this.observers)===null||t===void 0?void 0:t.length)>0},enumerable:!1,configurable:!0}),e.prototype._trySubscribe=function(t){return this._throwIfClosed(),i.prototype._trySubscribe.call(this,t)},e.prototype._subscribe=function(t){return this._throwIfClosed(),this._checkFinalizedStatuses(t),this._innerSubscribe(t)},e.prototype._innerSubscribe=function(t){var r=this,n=this,s=n.hasError,o=n.isStopped,u=n.observers;return s||o?Q:(this.currentObservers=null,u.push(t),new P(function(){r.currentObservers=null,M(u,t)}))},e.prototype._checkFinalizedStatuses=function(t){var r=this,n=r.hasError,s=r.thrownError,o=r.isStopped;n?t.error(s):o&&t.complete()},e.prototype.asObservable=function(){var t=new nt;return t.source=this,t},e.create=function(t,r){return new ut(t,r)},e}(nt),ut=function(i){_(e,i);function e(t,r){var n=i.call(this)||this;return n.destination=t,n.source=r,n}return e.prototype.next=function(t){var r,n;(n=(r=this.destination)===null||r===void 0?void 0:r.next)===null||n===void 0||n.call(r,t)},e.prototype.error=function(t){var r,n;(n=(r=this.destination)===null||r===void 0?void 0:r.error)===null||n===void 0||n.call(r,t)},e.prototype.complete=function(){var t,r;(r=(t=this.destination)===null||t===void 0?void 0:t.complete)===null||r===void 0||r.call(t)},e.prototype._subscribe=function(t){var r,n;return(n=(r=this.source)===null||r===void 0?void 0:r.subscribe(t))!==null&&n!==void 0?n:Q},e}(ot),D=function(i){_(e,i);function e(t){var r=i.call(this)||this;return r._value=t,r}return Object.defineProperty(e.prototype,"value",{get:function(){return this.getValue()},enumerable:!1,configurable:!0}),e.prototype._subscribe=function(t){var r=i.prototype._subscribe.call(this,t);return!r.closed&&t.next(this._value),r},e.prototype.getValue=function(){var t=this,r=t.hasError,n=t.thrownError,s=t._value;if(r)throw n;return this._throwIfClosed(),s},e.prototype.next=function(t){i.prototype.next.call(this,this._value=t)},e}(ot),at=(i=>(i[i.CRON=0]="CRON",i[i.EVENT=1]="EVENT",i[i.DELETE=2]="DELETE",i[i.GET=3]="GET",i[i.PATCH=4]="PATCH",i[i.POST=5]="POST",i[i.PUT=6]="PUT",i))(at||{});class ct extends d{constructor(t){super();a(this,"api");a(this,"$cache",new D([]));this.api=typeof t=="string"?new p(t):t}get cache(){return this.$cache.value}set cache(t){this.$cache.next(t)}delete(t){return this.api.request({url:`/api/actions/${t}`,method:"DELETE"}).then(()=>{this.cache=this.cache.filter(r=>r._id!=t),this.emit("DELETE",t)})}list(){return this.api.request({url:"/api/actions"}).then(t=>(this.cache=t,this.emit("LIST",t),t))}read(t,r=!1){const n=this.cache.find(s=>s._id==t);return!r&&n?Promise.resolve(n):this.api.request({url:`/api/actions/${t}`}).then(s=>(s&&(this.cache=this.cache.filter(o=>o._id!=t).concat([s])),this.emit("READ",s),s))}run(t,r={}){return this.api.request({url:("/api/actions/run/"+t).replaceAll("//","/"),...r})}runById(t,r={}){const n=typeof t=="string"?t:t._id;return this.api.request({url:"/api/actions/run-by-id/"+n,method:"POST",...r})}update(t){return this.api.request({url:`/api/actions${t._id?`/${t._id}`:""}`,method:"POST",body:t}).then(r=>(r&&(this.cache=this.cache.filter(n=>n._id!=r._id).concat([r])),this.emit("UPDATE",r),r))}}class ht extends d{constructor(t,r){var n;super();a(this,"api");a(this,"storageKey");a(this,"$user",new D(void 0));if(this.opts=r,this.api=typeof t=="string"?new p(t):t,(n=this.opts)!=null&&n.loginUi||(this.opts={...this.opts,loginUi:this.api.url+"/ui/login"}),this.storageKey=`momentum:${new URL(this.api.url).host}`,this.api.on("TOKEN",s=>{var o;(o=this.opts)!=null&&o.persist&&(s?localStorage.setItem(this.storageKey,s):localStorage.removeItem(this.storageKey)),s?this.whoAmI(s,!0):this.user=null}),r!=null&&r.persist){const s=localStorage.getItem(this.storageKey);s?this.api.token=s:this.user=null}else this.user=null}get user(){return this.$user.value}set user(t){if(!K(this.user,t)){const r=t||null;this.$user.next(r),this.emit("USER",r)}}knownHost(t=location.origin){return t.startsWith("/")?Promise.resolve():this.api.request({url:`/api/auth/known-host?host=${encodeURI(new URL(t).origin)}`})}login(t,r){return this.api.request({url:"/api/auth/login",headers:{Authorization:void 0},body:{username:t,password:r}}).then(async n=>(this.api.token=n.token,await this.once("USER")))}loginRedirect(t=location.origin){return new Promise((r,n)=>{var o;const s=window.open(encodeURI(`${(o=this.opts)==null?void 0:o.loginUi}?redirect=postmessage&host=${t}`),"_blank");if(!s)return n("Unable to open login");s.addEventListener("message",u=>{var c;if(!((c=u==null?void 0:u.data)!=null&&c.token))return n("Unknown response from login");this.api.token=u.data.token,r(u.data.token),s.close()})})}logout(){this.api.token=null,this.user=null,this.emit("LOGOUT")}async register(t){const r=await this.api.request({url:"/api/auth/register",body:{...t}});return this.emit("REGISTER",t),r}async reset(t,r){await this.api.request({url:"/api/auth/reset",headers:{Authorization:r?`Bearer ${r}`:void 0},body:{email:r?void 0:t,password:r?t:void 0}}),this.emit(r?"RESET_COMPLETE":"RESET_REQUEST",r||t)}async whoAmI(t,r=!1){t||(t=this.api.token);const n=await this.api.request({url:"/api/auth/whoami",headers:t?{Authorization:`Bearer ${t}`}:void 0});return r&&(this.api.token=t,this.user=(n==null?void 0:n.user)||null,n&&this.emit("LOGIN",n.user)),n}}class lt extends d{constructor(t){super();a(this,"api");this.api=typeof t=="string"?new p(t):t}delete(t,r){return this.api.request({url:`/api/data/${t}/${r}`,method:"DELETE"}).then(()=>this.emit("DELETE",t,r))}get(t,r){return this.api.request({url:`/api/data/${t}${r?`/${r}`:""}`}).then(n=>(this.emit("GET",t,n),n))}raw(t,r,n,s){return this.api.request({url:`/api/data/${t}`,body:{operand:r,query:n,options:s}}).then(o=>(this.emit("RAW",t,o),o))}set(t,r,n=!1){return this.api.request({url:`/api/data/${t}/${r._id||""}`,method:n?"PATCH":"POST",body:r}).then(s=>(this.emit("SET",t,r),s))}}class dt extends d{constructor(t){super();a(this,"api");this.api=typeof t=="string"?new p(t):t}send(t){let r="/api/email";return typeof t.body=="object"&&(r+=`/${t.body.template}`),this.api.request({url:r,body:t}).then(n=>(this.emit("SENT",t),n))}}class pt extends d{constructor(t){super();a(this,"api");this.api=typeof t=="string"?new p(t):t}create(t){return this.api.request({url:`/api/groups/${t.name}`,method:"POST",body:t}).then(r=>(this.emit("CREATE",r),r))}list(){return this.api.request({url:"/api/groups"}).then(t=>(this.emit("LIST",t),t))}read(t){return this.api.request({url:`/api/groups/${t}`}).then(r=>(this.emit("READ",r),r))}update(t){return this.api.request({url:`/api/groups/${t.name}`,method:"PATCH",body:t}).then(r=>(this.emit("UPDATE",r),r))}delete(t){return this.api.request({url:`/api/groups/${t}`,method:"DELETE"}).then(()=>this.emit("DELETE",t))}}class ft{constructor(e,t){a(this,"api");this.api=typeof e=="string"?new p(e):e,t!=null&&t!="NONE"&&(window.addEventListener("error",r=>this.error(r.error.stack)),window.addEventListener("unhandledrejection",async r=>this.error(r.reason.stack)))}buildLog(e,t){return{time:new Date().getTime(),level:e,log:t,ctx:{cores:navigator.hardwareConcurrency,mem:navigator==null?void 0:navigator.deviceMemory,res:[window.innerWidth,window.innerHeight],url:location.href}}}clearClientLogs(){return this.api.request({url:"/api/logs/client",method:"DELETE"})}clearServerLogs(){return this.api.request({url:"/api/logs/server",method:"DELETE"})}clientLogs(e,t){const r=[e?`length=${e}`:void 0,t?`page=${t}`:void 0].filter(n=>!!n).join("&");return this.api.request({url:`/api/logs/client${r?`?${r}`:""}`})}serverLogs(e,t){const r=[e?`length=${e}`:void 0,t?`page=${t}`:void 0].filter(n=>!!n).join("&");return this.api.request({url:`/api/logs/server${r?`?${r}`:""}`})}debug(...e){return this.api.request({url:"/api/logs/client",body:this.buildLog(O.DEBUG,e)}).catch(()=>{})}log(...e){return this.api.request({url:"/api/logs/client",body:this.buildLog(O.LOG,e)}).catch(()=>{})}info(...e){return this.api.request({url:"/api/logs/client",body:this.buildLog(O.INFO,e)}).catch(()=>{})}warn(...e){return this.api.request({url:"/api/logs/client",body:this.buildLog(O.WARN,e)}).catch(()=>{})}error(...e){return this.api.request({url:"/api/logs/client",body:this.buildLog(O.ERROR,e)}).catch(()=>{})}}class mt extends d{constructor(t){super();a(this,"api");this.api=typeof t=="string"?new p(t):t}async handleResponse(t,r){const n=await t.blob();if(r){const s=URL.createObjectURL(n);z(s,r.endsWith(".pdf")?r:r+".pdf"),URL.revokeObjectURL(s)}return this.emit("CREATE",n),n}generate(t,r={}){const n=t==null?void 0:t.template;return this.api.request({url:`/api/pdf${n?`/${n}`:""}`,body:n?t==null?void 0:t.data:{html:t}}).then(s=>this.handleResponse(s,r.download?r.fileName||new Date().toISOString():void 0))}fromUrl(t,r={}){return this.api.request({url:`/api/pdf?url=${t}`}).then(n=>this.handleResponse(n,r.download?r.fileName||new Date().toISOString():void 0))}}const j=class j{constructor(e){a(this,"api");a(this,"url");a(this,"connection");a(this,"open",!1);this.api=typeof e=="string"?new p(e):e,this.url=this.api.url.replace("http","ws"),this.api.on("TOKEN",()=>this.connect()),this.api.token||this.connect()}close(){console.debug("Disconnected from Momentum"),this.open=!1,this.connection.close()}connect(e=3){var r;((r=this.connection)==null?void 0:r.readyState)<2&&this.connection.close(),this.connection=new WebSocket(this.url+(this.api.token?`?token=${this.api.token}`:""));const t=setTimeout(()=>{this.open||(this.connection.close(),console.error("Momentum connection timeout"),e>0&&this.connect(e-1))},j.timeout);this.connection.onclose=()=>this.open=!1,this.connection.onmessage=this.handle,this.connection.onopen=()=>{this.open=!0,clearTimeout(t),console.debug("Connected to Momentum")}}handle(...e){console.log(e)}send(e,t){this.connection.send(JSON.stringify({token:this.api.token,channel:e,payload:t}))}};a(j,"timeout",1e4);let I=j;class yt extends d{constructor(t){super();a(this,"api");this.api=typeof t=="string"?new p(t):t}delete(t){const r=(t.startsWith("/api/storage/")?t:"/api/storage/"+t).replaceAll("//","/");return this.api.request({url:r,method:"DELETE"}).then(()=>{this.emit("DELETE",r)})}list(t){const r=(t.startsWith("/api/storage/")?t:"/api/storage/"+t).replaceAll("//","/");return this.api.request({url:r+"?list"}).then(n=>(this.emit("LIST",t,n),n))}open(t,r="_blank"){const n=(t.startsWith("/api/storage/")?t:"/api/storage/"+t).replaceAll(/\/{2,}/g,"/"),s=`${this.api.url}${n}${this.api.token?`?token=${this.api.token}`:""}`;return r?(this.emit("OPEN",t),window.open(s,r)):s}mkdir(t){const r=(t.startsWith("/api/storage/")?t:"/api/storage/"+t).replaceAll(/\/{2,}/g,"/");return this.api.request({url:r+"?directory",method:"POST"})}download(t,r={}){return new _t((n,s,o)=>{const u=("/api/storage/"+t).replaceAll("//","/");this.api.request({...r,url:u,skipConverting:!0}).then(c=>{var m;if(!c.ok)return s(c.statusText);const f=c.headers.get("Content-Length"),v=f?parseInt(f,10):0;let R=[],w=0;const E=(m=c.body)==null?void 0:m.getReader(),C=vt=>{if(vt.done){o(1);const $=new Blob(R),V=r.downloadAs||new URL(c.url).pathname.split("/").pop(),wt=URL.createObjectURL($);z(wt,V.includes(".")?V:V+".zip"),URL.revokeObjectURL(wt),this.emit("DOWNLOAD",t,$),n($)}else{const $=vt.value;R.push($),w+=$.length,o(w/v),E.read().then(C)}};E==null||E.read().then(C)})})}async upload(t,r=""){if(t||(t=await new Promise(u=>{const c=document.createElement("input");c.type="file",c.accept=(r==null?void 0:r.accept)||"*",c.style.display="none",c.multiple=!!(r!=null&&r.multiple),c.onblur=c.onchange=async()=>{u(Array.from(c.files)),c.remove()},document.body.appendChild(c),c.click()})),!t||Array.isArray(t)&&!t.length)return[];const s=new FormData,o=("/api/storage/"+(typeof r=="string"?r:r==null?void 0:r.path)).replaceAll("//","/");return(Array.isArray(t)?t:[t]).forEach(u=>s.append("file",u)),this.api.request({url:o,body:s}).then(u=>(this.emit("UPLOAD",u),u))}}class gt extends d{constructor(t){super();a(this,"api");a(this,"listed",!1);a(this,"$cache",new D([]));this.api=typeof t=="string"?new p(t):t}get cache(){return this.$cache.value}set cache(t){this.$cache.next(t)}delete(t){return this.api.request({url:`/api/users/${t}`,method:"DELETE"}).then(()=>{this.cache=this.cache.filter(r=>r.username!=t),this.emit("DELETE",t)})}list(t=!1){return!t&&this.listed?Promise.resolve(this.cache):this.api.request({url:"/api/users"}).then(r=>(this.cache=r,this.listed=!0,this.emit("LIST",r),r))}read(t,r=!1){if(!r){const n=this.cache.find(s=>s.username==t);if(n)return Promise.resolve(n)}return this.api.request({url:`/api/users/${t}`}).then(n=>(n&&(this.cache={...this.cache,[n.username]:n}),this.emit("READ",n),n))}update(t){return this.api.request({url:`/api/users/${t.username}`,method:"PATCH",body:t}).then(r=>(r&&(this.cache=this.cache.filter(n=>n.username!=t.username).concat([r])),this.emit("UPDATE",r),r))}}class Et extends d{constructor(t){super();a(this,"api");a(this,"$cache",new D({}));this.api=typeof t=="string"?new p(t):t}get cache(){return this.$cache.value}set cache(t){this.$cache.next(t)}list(t=!1){return this.api.request({url:"/api/settings"+(t?"?detailed":"")}).then(r=>(this.cache=t?Object.values(r).reduce((n,s)=>({...n,[s.key]:s.value}),{}):r,this.emit("LIST",r),r))}delete(t){return this.api.request({url:`/api/settings/${t}`,method:"DELETE"}).then(()=>{this.cache={...this.cache,[t]:void 0},this.emit("DELETE",t)})}read(t,r=!1){return!r&&this.cache[t]?Promise.resolve(this.cache[t]):this.api.request({url:`/api/settings/${t}`}).then(n=>(n&&(this.cache={...this.cache,[n.key]:n}),this.emit("READ",n),n))}update(t){return this.api.request({url:`/api/settings/${t.key}`,body:t}).then(r=>(r&&(this.cache={...this.cache,[r.key]:r.value}),this.emit("UPDATE",r),r))}}class bt extends d{constructor(t){super();a(this,"api");this.api=typeof t=="string"?new p(t):t}delete(t){return this.api.request({url:`/api/static/${t}`,method:"DELETE"}).then(()=>{this.emit("DELETE",t)})}list(t){const r=("/api/static/"+t).replaceAll("//","/");return this.api.request({url:r}).then(n=>(this.emit("LIST",t,n),n))}upload(t,r="/"){const n=new FormData;return(Array.isArray(t)?t:[t]).forEach(s=>n.append("file",s)),this.api.request({url:"/api/static"+r,body:n}).then(s=>(this.emit("UPLOAD",s),s))}}class Nt extends d{constructor(t,r){super();a(this,"api");a(this,"actions");a(this,"auth");a(this,"data");a(this,"email");a(this,"groups");a(this,"logger");a(this,"pdf");a(this,"settings");a(this,"socket");a(this,"static");a(this,"storage");a(this,"users");this.api=new p(t,r==null?void 0:r.api),this.actions=new ct(this.api),this.auth=new ht(this.api,{persist:(r==null?void 0:r.persist)??!0,loginUi:r==null?void 0:r.loginUi}),this.data=new lt(this.api),this.email=new dt(this.api),this.groups=new pt(this.api),this.logger=new ft(this.api,r==null?void 0:r.logLevel),this.pdf=new mt(this.api),this.settings=new Et(this.api),this.static=new bt(this.api),this.storage=new yt(this.api),this.users=new gt(this.api),r!=null&&r.socket&&(this.socket=new I(this.api)),this.api.on("*",(n,...s)=>this.emit(`API::${n}`,...s)),this.actions.on("*",(n,...s)=>this.emit(`ACTIONS::${n}`,...s)),this.auth.on("*",(n,...s)=>this.emit(`AUTH::${n}`,...s)),this.data.on("*",(n,...s)=>this.emit(`DATA::${n}`,...s)),this.email.on("*",(n,...s)=>this.emit(`EMAIL::${n}`,...s)),this.groups.on("*",(n,...s)=>this.emit(`GROUPS::${n}`,...s)),this.pdf.on("*",(n,...s)=>this.emit(`PDF::${n}`,...s)),this.settings.on("*",(n,...s)=>this.emit(`SETTINGS::${n}`,...s)),this.static.on("*",(n,...s)=>this.emit(`STATIC::${n}`,...s)),this.storage.on("*",(n,...s)=>this.emit(`STORAGE::${n}`,...s)),this.users.on("*",(n,...s)=>this.emit(`USERS::${n}`,...s)),this.users.on("*",(n,...s)=>{var o;if(Array.isArray(s[0])){const u=s[0].find(c=>{var f;return c._id==((f=this.auth.user)==null?void 0:f._id)});u&&(this.auth.user=u)}else s[0]._id==((o=this.auth.user)==null?void 0:o._id)&&(this.auth.user=s[0])})}}h.ActionType=at,h.Actions=ct,h.Api=p,h.Auth=ht,h.Data=lt,h.Email=dt,h.Groups=pt,h.Logger=ft,h.Momentum=Nt,h.Pdf=mt,h.Settings=Et,h.Socket=I,h.Static=bt,h.Storage=yt,h.Users=gt,Object.defineProperty(h,Symbol.toStringTag,{value:"Module"})});
4
- //# sourceMappingURL=momentum.cjs.map