@clairejs/server 3.3.5 → 3.3.8
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/README.md +5 -0
- package/dist/http/auth/AbstractRbacAuthProvider.d.ts +1 -1
- package/dist/http/repository/DtoRepository.d.ts +15 -12
- package/dist/http/repository/ICrudRepository.d.ts +10 -7
- package/dist/http/repository/ModelRepository.d.ts +10 -7
- package/dist/index.js +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -12,7 +12,7 @@ export declare abstract class AbstractRbacAuthProvider<T extends IPrincipal> ext
|
|
|
12
12
|
constructor(authDataResolver: (req: HttpRequest) => string, principalResolver: AbstractPrincipalResolver<T>, logger: AbstractLogger);
|
|
13
13
|
getPrincipalResolver(): AbstractPrincipalResolver<T>;
|
|
14
14
|
abstract getRbacCache(): Promise<RbacCache | undefined>;
|
|
15
|
-
abstract getRolesOfPrincipal(principal: T
|
|
15
|
+
abstract getRolesOfPrincipal(principal: T): Promise<number[]>;
|
|
16
16
|
resolvePrincipal(req: HttpRequest): Promise<T | undefined>;
|
|
17
17
|
authorize(principal: T | undefined, request: HttpRequest, endpoint: MountedEndpointInfo): Promise<void>;
|
|
18
18
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { AbstractModel, Constructor, CreateManyRequestBody, CreateManyResponseBody, DeepPartial, GetManyQueries, GetManyResponseBody, Identifiable, UpdateManyBody, UpdateManyQueries, UpdateManyResponse } from "@clairejs/core";
|
|
1
|
+
import { AbstractModel, Constructor, CreateManyRequestBody, CreateManyResponseBody, DeepPartial, GetManyQueries, GetManyResponseBody, Identifiable, QueryCondition, UpdateManyBody, UpdateManyQueries, UpdateManyResponse } from "@clairejs/core";
|
|
2
2
|
import { IQueryProvider } from "../../database/adapter/IQueryProvider";
|
|
3
3
|
import { ITransaction } from "../../database/transaction/ITransaction";
|
|
4
4
|
import { IPrincipal } from "../../common/auth/IPrincipal";
|
|
@@ -8,23 +8,23 @@ export declare type DtoDissolver<R extends Identifiable, K extends Identifiable>
|
|
|
8
8
|
export interface MappingMetadata<R extends Identifiable, K extends AbstractModel> {
|
|
9
9
|
multiple: boolean;
|
|
10
10
|
modelClass: Constructor<K>;
|
|
11
|
-
|
|
11
|
+
forwardOps: (ops?: QueryCondition<R>[]) => QueryCondition<K>[] | undefined;
|
|
12
12
|
forwardMapping: (t: DeepPartial<K>[]) => DeepPartial<K>[] | undefined;
|
|
13
13
|
rootMapping: (ks?: DeepPartial<K>[]) => DeepPartial<R>;
|
|
14
14
|
nestedMapping?: DtoDissolver<R, K>;
|
|
15
15
|
}
|
|
16
|
-
export declare const SingleMap: <R extends Identifiable, K extends AbstractModel>(modelClass: Constructor<K>,
|
|
16
|
+
export declare const SingleMap: <R extends Identifiable, K extends AbstractModel>(modelClass: Constructor<K>, forwardOps: (ops?: QueryCondition<R>[] | undefined) => QueryCondition<K>[] | undefined, forwardMapping: (t: DeepPartial<K>) => DeepPartial<K> | undefined, rootMapping: (k?: DeepPartial<K> | undefined) => DeepPartial<R>, nestedMapping?: DtoDissolver<R, K> | undefined) => {
|
|
17
17
|
multiple: boolean;
|
|
18
18
|
modelClass: Constructor<K>;
|
|
19
|
-
|
|
19
|
+
forwardOps: (ops?: QueryCondition<R>[] | undefined) => QueryCondition<K>[] | undefined;
|
|
20
20
|
forwardMapping: (t: DeepPartial<K>[]) => DeepPartial<K>[] | undefined;
|
|
21
21
|
rootMapping: (ks?: DeepPartial<K>[] | undefined) => DeepPartial<R>;
|
|
22
22
|
nestedMapping: DtoDissolver<R, K> | undefined;
|
|
23
23
|
};
|
|
24
|
-
export declare const MultipleMap: <R extends Identifiable, K extends AbstractModel>(modelClass: Constructor<K>,
|
|
24
|
+
export declare const MultipleMap: <R extends Identifiable, K extends AbstractModel>(modelClass: Constructor<K>, forwardOps: (ops?: QueryCondition<R>[] | undefined) => QueryCondition<K>[] | undefined, forwardMapping: (t: DeepPartial<K>[]) => DeepPartial<K>[] | undefined, rootMapping: (ks?: DeepPartial<K>[] | undefined) => DeepPartial<R>, nestedMapping?: DtoDissolver<R, K> | undefined) => {
|
|
25
25
|
multiple: boolean;
|
|
26
26
|
modelClass: Constructor<K>;
|
|
27
|
-
|
|
27
|
+
forwardOps: (ops?: QueryCondition<R>[] | undefined) => QueryCondition<K>[] | undefined;
|
|
28
28
|
forwardMapping: (t: DeepPartial<K>[]) => DeepPartial<K>[] | undefined;
|
|
29
29
|
rootMapping: (ks?: DeepPartial<K>[] | undefined) => DeepPartial<R>;
|
|
30
30
|
nestedMapping: DtoDissolver<R, K> | undefined;
|
|
@@ -39,18 +39,21 @@ export declare class DtoRepository<T extends Identifiable> extends AbstractRepos
|
|
|
39
39
|
body: CreateManyRequestBody<T>;
|
|
40
40
|
tx: ITransaction & IQueryProvider;
|
|
41
41
|
}): Promise<CreateManyResponseBody<T>>;
|
|
42
|
-
updateMany({ principal, queries, body, tx, }: {
|
|
42
|
+
updateMany({ principal, queries, ops, body, tx, }: {
|
|
43
43
|
principal?: IPrincipal | undefined;
|
|
44
|
-
queries
|
|
44
|
+
queries?: UpdateManyQueries<T>;
|
|
45
|
+
ops?: QueryCondition<T>[];
|
|
45
46
|
body: UpdateManyBody<T>;
|
|
46
47
|
tx: ITransaction & IQueryProvider;
|
|
47
48
|
}): Promise<UpdateManyResponse<T>>;
|
|
48
|
-
getMany({ queries, queryProvider, }: {
|
|
49
|
-
queries
|
|
49
|
+
getMany({ queries, ops, queryProvider, }: {
|
|
50
|
+
queries?: GetManyQueries<T>;
|
|
51
|
+
ops?: QueryCondition<T>[];
|
|
50
52
|
queryProvider: IQueryProvider;
|
|
51
53
|
}): Promise<GetManyResponseBody<T>>;
|
|
52
|
-
deleteMany({ queries, tx, }: {
|
|
53
|
-
queries
|
|
54
|
+
deleteMany({ queries, ops, tx, }: {
|
|
55
|
+
queries?: UpdateManyQueries<T>;
|
|
56
|
+
ops?: QueryCondition<T>[];
|
|
54
57
|
tx: ITransaction;
|
|
55
58
|
}): Promise<UpdateManyResponse<T>>;
|
|
56
59
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { CreateManyRequestBody, CreateManyResponseBody, GetManyQueries, GetManyResponseBody, UpdateManyBody, UpdateManyQueries, UpdateManyResponse } from "@clairejs/core";
|
|
1
|
+
import { CreateManyRequestBody, CreateManyResponseBody, GetManyQueries, GetManyResponseBody, QueryCondition, UpdateManyBody, UpdateManyQueries, UpdateManyResponse } from "@clairejs/core";
|
|
2
2
|
import { IQueryProvider } from "../../database/adapter/IQueryProvider";
|
|
3
3
|
import { ITransaction } from "../../database/transaction/ITransaction";
|
|
4
4
|
import { IPrincipal } from "../../common/auth/IPrincipal";
|
|
@@ -8,18 +8,21 @@ export interface ICrudRepository<T> {
|
|
|
8
8
|
body: CreateManyRequestBody<T>;
|
|
9
9
|
tx: ITransaction;
|
|
10
10
|
}): Promise<CreateManyResponseBody<T>>;
|
|
11
|
-
getMany({ queries, queryProvider, }: {
|
|
12
|
-
queries
|
|
11
|
+
getMany({ queries, ops, queryProvider, }: {
|
|
12
|
+
queries?: GetManyQueries<T>;
|
|
13
|
+
ops?: QueryCondition<T>[];
|
|
13
14
|
queryProvider: IQueryProvider;
|
|
14
15
|
}): Promise<GetManyResponseBody<T>>;
|
|
15
|
-
updateMany({ principal, queries, body, tx, }: {
|
|
16
|
+
updateMany({ principal, queries, ops, body, tx, }: {
|
|
16
17
|
principal?: IPrincipal;
|
|
17
|
-
queries
|
|
18
|
+
queries?: UpdateManyQueries<T>;
|
|
19
|
+
ops?: QueryCondition<T>[];
|
|
18
20
|
body: UpdateManyBody<T>;
|
|
19
21
|
tx: ITransaction;
|
|
20
22
|
}): Promise<UpdateManyResponse<T>>;
|
|
21
|
-
deleteMany({ queries, tx }: {
|
|
22
|
-
queries
|
|
23
|
+
deleteMany({ queries, ops, tx, }: {
|
|
24
|
+
queries?: UpdateManyQueries<T>;
|
|
25
|
+
ops?: QueryCondition<T>[];
|
|
23
26
|
tx: ITransaction;
|
|
24
27
|
}): Promise<UpdateManyResponse<T>>;
|
|
25
28
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { AbstractModel, Constructor, CreateManyRequestBody, CreateManyResponseBody, GetManyQueries, GetManyResponseBody, UpdateManyBody, UpdateManyQueries, UpdateManyResponse } from "@clairejs/core";
|
|
1
|
+
import { AbstractModel, Constructor, CreateManyRequestBody, CreateManyResponseBody, GetManyQueries, GetManyResponseBody, UpdateManyBody, UpdateManyQueries, UpdateManyResponse, QueryCondition } from "@clairejs/core";
|
|
2
2
|
import { IQueryProvider } from "../../database/adapter/IQueryProvider";
|
|
3
3
|
import { ITransaction } from "../../database/transaction/ITransaction";
|
|
4
4
|
import { IPrincipal } from "../../common/auth/IPrincipal";
|
|
@@ -18,18 +18,21 @@ export declare class ModelRepository<T extends AbstractModel> extends AbstractRe
|
|
|
18
18
|
body: CreateManyRequestBody<T>;
|
|
19
19
|
tx: ITransaction;
|
|
20
20
|
}): Promise<CreateManyResponseBody<T>>;
|
|
21
|
-
updateMany({ principal, queries, body, tx, }: {
|
|
21
|
+
updateMany({ principal, ops, queries, body, tx, }: {
|
|
22
22
|
principal?: IPrincipal;
|
|
23
|
-
queries
|
|
23
|
+
queries?: UpdateManyQueries<T>;
|
|
24
|
+
ops?: QueryCondition<T>[];
|
|
24
25
|
body: UpdateManyBody<T>;
|
|
25
26
|
tx: ITransaction;
|
|
26
27
|
}): Promise<UpdateManyResponse<T>>;
|
|
27
|
-
getMany({ queries, queryProvider, }: {
|
|
28
|
-
queries
|
|
28
|
+
getMany({ queries, ops, queryProvider, }: {
|
|
29
|
+
queries?: GetManyQueries<T>;
|
|
30
|
+
ops?: QueryCondition<T>[];
|
|
29
31
|
queryProvider: IQueryProvider;
|
|
30
32
|
}): Promise<GetManyResponseBody<T>>;
|
|
31
|
-
deleteMany({ queries, tx, }: {
|
|
32
|
-
queries
|
|
33
|
+
deleteMany({ queries, ops, tx, }: {
|
|
34
|
+
queries?: UpdateManyQueries<T>;
|
|
35
|
+
ops?: QueryCondition<T>[];
|
|
33
36
|
tx: ITransaction;
|
|
34
37
|
}): Promise<UpdateManyResponse<T>>;
|
|
35
38
|
}
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
!function webpackUniversalModuleDefinition(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var n=t();for(var i in n)("object"==typeof exports?exports:e)[i]=n[i]}}(global,(function(){return function(e){var t={};function __webpack_require__(n){if(t[n])return t[n].exports;var i=t[n]={i:n,l:!1,exports:{}};return e[n].call(i.exports,i,i.exports,__webpack_require__),i.l=!0,i.exports}return __webpack_require__.m=e,__webpack_require__.c=t,__webpack_require__.d=function(e,t,n){__webpack_require__.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},__webpack_require__.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},__webpack_require__.t=function(e,t){if(1&t&&(e=__webpack_require__(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(__webpack_require__.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var i in e)__webpack_require__.d(n,i,function(t){return e[t]}.bind(null,i));return n},__webpack_require__.n=function(e){var t=e&&e.__esModule?function getDefault(){return e.default}:function getModuleExports(){return e};return __webpack_require__.d(t,"a",t),t},__webpack_require__.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},__webpack_require__.p="",__webpack_require__(__webpack_require__.s=37)}([function(e,t){e.exports=require("@clairejs/core")},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractHttpAuthorizationProvider=void 0;t.AbstractHttpAuthorizationProvider=class AbstractHttpAuthorizationProvider{}},function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractHttpRequestHandler=void 0;const o=n(0),r=n(6),s=n(9);t.AbstractHttpRequestHandler=class AbstractHttpRequestHandler{constructor(e,t){this.mountPoint=e,this.logger=t}resolverMountPoint(e,t){if(!e)return"";const n=[];return n.push(...t),n.reduce(((e,t)=>`${e}/${t}`),"").replace(/(\/)\/+/g,"$1")}getMountedEndpointInfo(){var e,t,n;return i(this,void 0,void 0,(function*(){if(!this.mountedEndpointInfo){const i=[],a=(0,o.getServiceProvider)().getInjector(),d=a.resolveMultiple(s.AbstractHttpController);yield a.initInstances();for(const e of d){const t=(0,o.getObjectMetadata)(e.constructor),n=e.getEndpointMetadata();for(const r of n){const n={mount:r.httpMethod===o.SocketMethod.MESSAGE?r.url:this.resolverMountPoint(t,[this.mountPoint||"/",r.url]),httpMethod:r.httpMethod,controller:e,handlerFunctionName:r.name};i.push({endpointMetadata:r,endpoint:n})}}const c=[];for(const o of i){const i=c.find((e=>e.endpoint.mount===o.endpoint.mount&&e.endpoint.httpMethod===o.endpoint.httpMethod));i?null===(e=this.logger)||void 0===e||e.warn(`Implicit overriding endpoint: ${(0,r.getEndpointId)(i.endpoint)} of ${null===(t=i.endpoint.controller)||void 0===t?void 0:t.constructor.name}:${i.endpoint.handlerFunctionName}`,`Ignore ${(0,r.getEndpointId)(o.endpoint)} of ${null===(n=o.endpoint.controller)||void 0===n?void 0:n.constructor.name}:${o.endpoint.handlerFunctionName}`):c.push(o)}this.mountedEndpointInfo=c}return this.mountedEndpointInfo}))}}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getDirectFields=t.getFieldByName=t.getTransactionFromContext=void 0;const i=n(0),o=n(10);t.getTransactionFromContext=e=>{const t=e[o.INJECTED_TRANSACTION];if(!t)throw i.ErrorBuilder.systemError("Cannot get transaction from current context");return t};t.getFieldByName=(e,t)=>e.fields.find((e=>e.name===t));t.getDirectFields=e=>e.fields.filter((e=>!e.hasMany))},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractAccessCondition=void 0;t.AbstractAccessCondition=class AbstractAccessCondition{}},function(e,t,n){"use strict";var i=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},o=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractServerSocketManager=void 0;const r=n(0),s=n(29),a=n(4),d=n(7),c="x-socket-action",l="read",u="write";let h=class SocketReadCondition extends a.AbstractAccessCondition{resolveConditionValue(e){return o(this,void 0,void 0,(function*(){return e.getHeaders()["x-socket-action"]===l}))}validate(e){return o(this,void 0,void 0,(function*(){return!!e}))}getConditionMetadata(){return{name:"socket_read",description:"Can receive message from channel",valueType:r.AccessConditionValueType.BOOLEAN}}};h=i([(0,r.Register)()],h);let p=class SocketWriteCondition extends a.AbstractAccessCondition{resolveConditionValue(e){return o(this,void 0,void 0,(function*(){return e.getHeaders()["x-socket-action"]===u}))}validate(e){return o(this,void 0,void 0,(function*(){return!!e}))}getConditionMetadata(){return{name:"socket_write",description:"Can send message to channel",valueType:r.AccessConditionValueType.BOOLEAN}}};p=i([(0,r.Register)()],p);t.AbstractServerSocketManager=class AbstractServerSocketManager{constructor(e,t,n,i,o){this.requireAuthentication=e,this.logger=t,this.redisClient=n,this.connectionHandler=i,this.authProvider=o}getUniqueChannelPrefix(){return"CHANNEL:"}formatBroadcastData(e,t){return{type:r.MessageType.PLAIN,data:{channel:e,message:t}}}getUniqueChannelName(e){return`${this.getUniqueChannelPrefix()}${e}`}getSocketIdsOfChannel(e){return o(this,void 0,void 0,(function*(){return yield new Promise(((t,n)=>this.redisClient.smembers(this.getUniqueChannelName(e),((e,i)=>{e?n(e):t(i)}))))}))}addSocketToChannel(e,t){return o(this,void 0,void 0,(function*(){const n=yield this.getById(e);n&&(n.addChannels(t),yield Promise.all(t.map((t=>new Promise(((n,i)=>this.redisClient.sadd(this.getUniqueChannelName(t.name),e,(e=>{e?i(e):n()}))))))),yield n.saveSocketInfo())}))}removeSocketFromChannel(e,t){return o(this,void 0,void 0,(function*(){const n=yield this.getById(e);n&&(n.removeChannels(t),yield Promise.all(t.map((t=>new Promise(((n,i)=>this.redisClient.srem(this.getUniqueChannelName(t),e,(e=>{e?i(e):n()}))))))),yield n.saveSocketInfo())}))}handle(e){var t;return o(this,void 0,void 0,(function*(){switch(e.method){case r.SocketMethod.CONNECT:{this.logger.debug("Socket connection attempt",e.socketId);const n=yield this.authProvider.getPrincipalResolver().resolvePrincipal((null===(t=e.data)||void 0===t?void 0:t.auth)||"");if(!n&&this.requireAuthentication)throw r.ErrorBuilder.error(r.Errors.AUTHENTICATION_ERROR);const i=yield this.addSocket({id:e.socketId,authInfo:n,channels:[],createdAt:Date.now()},e.data);if(!i)throw r.ErrorBuilder.error(r.Errors.SYSTEM_ERROR,"Socket not found after create: "+e.socketId);this.connectionHandler.onSocketConnect(i);break}case r.SocketMethod.DISCONNECT:{this.logger.debug("Socket disconnect",e);const t=yield this.getById(e.socketId);if(t){const n=yield this.getMountedEndpointInfo();for(const e of t.getChannelsInfo()){const i=n.find((t=>t.endpointMetadata.url===e.name));i&&i.endpoint.controller.onChannelLeave(t)}this.connectionHandler.onSocketDisconnect(t),t.disconnect(),yield this.removeSocket(e.socketId)}break}case r.SocketMethod.MESSAGE:{this.logger.debug("Socket message",e);const t=JSON.parse(e.data),n=yield this.getById(e.socketId);if(n)switch(t.type){case r.MessageType.PING_PONG:null==n||n.sendRaw({type:r.MessageType.PING_PONG,data:void 0});break;case r.MessageType.CHANNEL_JOIN:{const e=t.data,i=[];for(const t of e){let e=!1,o=!1;const s=(yield this.getMountedEndpointInfo()).find((e=>e.endpointMetadata.url===t));if(s){try{const e=new d.HttpRequest({method:r.SocketMethod.MESSAGE,pathName:t,headers:{[c]:l}},s.endpointMetadata);yield this.authProvider.authorize(n.getAuthInfo(),e,s),o=!0}catch(e){}try{const i=new d.HttpRequest({method:r.SocketMethod.MESSAGE,pathName:t,headers:{[c]:u}},s.endpointMetadata);yield this.authProvider.authorize(n.getAuthInfo(),i,s),e=!0}catch(e){}(e||o)&&(this.logger.debug("Adding channel info",t,e,o),i.push({name:t,clientToServerAllowed:e,serverToClientAllowed:o})),s.endpoint.controller.onChannelJoin(n)}}yield this.addSocketToChannel(n.getId(),i),n.sendRaw({type:r.MessageType.CHANNEL_JOIN,data:i.map((e=>e.name))})}break;case r.MessageType.CHANNEL_LEAVE:{const e=t.data;for(const t of e){const e=(yield this.getMountedEndpointInfo()).find((e=>e.endpointMetadata.url===t));e&&e.endpoint.controller.onChannelLeave(n)}yield this.removeSocketFromChannel(n.getId(),e)}break;case r.MessageType.PLAIN:{const e=t.data.channel,i=t.data.message;if(e){if(n.getChannelsInfo().find((t=>t.name===e&&t.clientToServerAllowed))){const t=(yield this.getMountedEndpointInfo()).find((t=>t.endpointMetadata.url===e));if(t){!1!==t.endpoint.controller.onMessage(n,i)&&(this.logger.debug("broadcasting to channel",e,i),this.broadcastToChannel(e,i))}}}else this.connectionHandler.onMessage(n,i)}break;default:this.logger.debug("Invalid message format",t)}else this.logger.debug("Socket not found",e.socketId);break}default:return}}))}getMountedEndpointInfo(){return o(this,void 0,void 0,(function*(){if(!this.mountedEndpointInfo){const e=(0,r.getServiceProvider)().getInjector(),t=e.resolveMultiple(s.AbstractSocketController);yield e.initInstances(),this.mountedEndpointInfo=t.map((e=>({endpoint:{httpMethod:r.SocketMethod.MESSAGE,mount:e.channel,controller:e,handlerFunctionName:e.onMessage.name},endpointMetadata:{httpMethod:r.SocketMethod.MESSAGE,description:"Send / Receive message to / from channel",dataType:r.DataType.OBJECT,url:e.channel,name:e.channel,accessConditions:[h,p]}})))}return this.mountedEndpointInfo}))}}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getEndpointId=void 0;t.getEndpointId=e=>`${e.httpMethod}:${e.mount}`},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HttpRequest=void 0;const i=n(0);t.HttpRequest=class HttpRequest{constructor(e,t){this.valueHolder={},this.method=e.method,this.pathName=e.pathName,this.headers=e.headers||{},this.hash=e.hash||"",this.params=e.params||{},(null==t?void 0:t.paramsValidationDto)&&(this.params=(0,i.validateData)(this.params,null==t?void 0:t.paramsValidationDto)),this.query=e.query||{},(null==t?void 0:t.queriesValidationDto)&&(this.query=(0,i.validateData)(this.jsonParsing(this.query,t.queriesValidationDto),t.queriesValidationDto)),this.body=e.body||{},t&&(t.httpMethod===i.HttpMethod.POST||t.httpMethod===i.HttpMethod.PUT)&&(null==t?void 0:t.bodyValidationDto)&&(this.body=(0,i.validateData)(this.body||{},t.bodyValidationDto))}jsonParsing(e,t){const n=Object.assign({},e);for(const o of t.fields)try{(void 0!==e[o.name]||o.isRequired)&&(n[o.name]=JSON.parse(e[o.name]))}catch(e){throw i.ErrorBuilder.error(i.Errors.VALIDATION_ERROR,`JSON parsing failed for field ${o.name}`)}return n}getAuthInfo(){return this.authInfo}setAuthInfo(e){this.authInfo=e}getHeaders(){return this.headers}getMethod(){return this.method}getHash(){return this.hash}getPathName(){return this.pathName}getValue(e){return this.valueHolder[e]}setValue(e,t){this.valueHolder[e]=t}getParams(){return this.params}getQuery(){return this.query}getBody(){return this.body}}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ResponseBuilder=t.HttpResponse=void 0;class HttpResponse{constructor(){this.code=200,this.headers={},this.cookies={}}}t.HttpResponse=HttpResponse;class ResponseBuilder{constructor(){this.response=new HttpResponse}status(e){return this.response.code=e,this}header(e,t){return this.response.headers[e]=t,this}cookie(e,t){return this.response.headers[e]=t,this}get(){return this.response}static json(e){const t=new ResponseBuilder;return t.response.value=e,t.response.headers["Content-Type"]="application/json",t}static html(e){const t=new ResponseBuilder;return t.response.value=e,t.response.headers["Content-Type"]="text/html; charset=UTF-8",t}static binary(e){const t=new ResponseBuilder;return t.response.value=e,t.response.headers["Content-Type"]="application/octet-stream",t}static success(){const e=new ResponseBuilder;return e.response.code=200,e.response}static notFound(e){const t=new ResponseBuilder;return t.response.code=404,t.response.value=e,t.response}static accessDenied(e){const t=new ResponseBuilder;return t.response.code=400,t.response.value=e,t.response}}t.ResponseBuilder=ResponseBuilder},function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractHttpController=void 0;const o=n(0),r=n(3);t.AbstractHttpController=class AbstractHttpController{constructor(e){this.databaseAdapter=e}createTransaction(){return i(this,void 0,void 0,(function*(){return this.databaseAdapter.createTransaction()}))}getCurrentTransaction(){return i(this,void 0,void 0,(function*(){return(0,r.getTransactionFromContext)(this)}))}getEndpointMetadata(){const e=(0,o.getObjectMetadata)(this.constructor);return e?e.fields.filter((e=>{return!!(t=e).httpMethod||void 0!==t.openAccess||!!t.accessConditions;var t})).map((t=>Object.assign(Object.assign({},t),{permissionGroup:e.permissionGroup}))):[]}}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ExitCode=t.INJECTED_TRANSACTION=void 0,t.INJECTED_TRANSACTION="__INJECTED_TRANSACTION__",t.ExitCode={SIGTERM_INTERUPTION:-1,SIGINT_INTERUPTION:-2,UNCAUGHT_EXCEPTION:-3,UNHANDLED_REJECTION:-4}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Errors=void 0;const i=n(0);t.Errors=Object.assign(Object.assign({},i.Errors),{TFA_REQUIRED:"TFA_REQUIRED"})},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TransactionLink=void 0,function(e){e.CREATE_NEW="create_new",e.INHERIT_OR_CREATE="inherit_or_create",e.INHERIT_OR_THROW="inherit_or_throw"}(t.TransactionLink||(t.TransactionLink={}))},function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractRbacAuthProvider=void 0;const o=n(0),r=n(1),s=n(6);class AbstractRbacAuthProvider extends r.AbstractHttpAuthorizationProvider{constructor(e,t,n){super(),this.authDataResolver=e,this.principalResolver=t,this.logger=n}getPrincipalResolver(){return this.principalResolver}resolvePrincipal(e){return this.principalResolver.resolvePrincipal(this.authDataResolver(e))}authorize(e,t,n){return i(this,void 0,void 0,(function*(){if(n.endpointMetadata.openAccess)return;const i=yield this.getRbacCache();if(!i)throw o.ErrorBuilder.error(o.Errors.SYSTEM_ERROR,"Cannot read rbac cache");const r=yield this.getRolesOfPrincipal(e),a=(i.roles||[]).filter((e=>!!r.find((t=>t===e.roleId))));if(!a.length)throw o.ErrorBuilder.error(o.Errors.ACCESS_DENIED,"No role attached");if(a.find((e=>e.isSuperRole)))return;const d=(i.rolePolicies||[]).filter((e=>!!a.find((t=>t.roleId===e.roleId)))),c=(i.policies||[]).filter((e=>!!d.find((t=>t.policyId===e.policyId)))),l=(i.policyPermissions||[]).filter((e=>!!c.find((t=>t.policyId===e.policyId)))),u=(i.policyPermissionConditions||[]).filter((e=>!!l.find((t=>t.id===e.policyPermissionId)))),h=l.filter((e=>e.permission===(0,s.getEndpointId)(n.endpoint)));if(!h.length)throw o.ErrorBuilder.error(o.Errors.ACCESS_DENIED,`Not permitted: ${(0,s.getEndpointId)(n.endpoint)}`);let p=!1;for(const e of h){const i=u.filter((t=>t.policyPermissionId===e.id));if(i.length){let e=!0;const r=(0,o.getServiceProvider)().getInjector(),s=(n.endpointMetadata.accessConditions||[]).map((e=>r.resolve(e)));yield r.initInstances();for(const n of i){const i=s.find((e=>e.getConditionMetadata().name===n.conditionName));if(!i)continue;const o=yield i.resolveConditionValue(t),r=JSON.parse(n.conditionValue);if(e=yield i.validate(o,r),!e){this.logger.debug("Condition check failed: condition, requested, permitted",n.conditionName,o,r);break}}p=e}else p=!0;if(p)break}if(!p)throw o.ErrorBuilder.error(o.Errors.ACCESS_DENIED,"Condition check failed")}))}}t.AbstractRbacAuthProvider=AbstractRbacAuthProvider},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractFileUploadHandler=void 0;t.AbstractFileUploadHandler=class AbstractFileUploadHandler{}},function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractRepository=void 0;const o=n(0);t.AbstractRepository=class AbstractRepository{constructor(e){this.model=e,this.modelMetadata=(0,o.getObjectMetadata)(this.model)}beforeCreating(e,t){return i(this,void 0,void 0,(function*(){for(const n of t)for(const t of this.modelMetadata.fields)t.userResolver&&e&&(n[t.name]=t.userResolver(e))}))}project(e,t){return t?e.map((e=>t.reduce(((t,n)=>Object.assign(t,{[n]:e[n]})),{}))):e}}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractSocketConnectionHandler=void 0;t.AbstractSocketConnectionHandler=class AbstractSocketConnectionHandler{}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SqlProvider=t.NoSqlProvider=void 0,function(e){e.MONGODB="mongodb",e.DYNAMODB="dynamodb"}(t.NoSqlProvider||(t.NoSqlProvider={})),function(e){e.MYSQL="mysql",e.POSTGRES="postgres"}(t.SqlProvider||(t.SqlProvider={}))},function(e,t){e.exports=require("sequelize")},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractPrincipalResolver=void 0;t.AbstractPrincipalResolver=class AbstractPrincipalResolver{}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CurrentUser=t.UriMapper=t.Raw=t.Socket=t.Headers=t.Queries=t.Params=t.Body=t.AccessCondition=t.TfaRequired=t.OpenAccess=t.ApiResponse=t.Get=t.Del=t.Put=t.Post=t.Endpoint=t.ApiDescription=t.Controller=void 0;const i=n(0);t.Controller=e=>t=>{(0,i.getServiceProvider)().register(t,"singleton");(0,i.initObjectMetadata)(t.prototype).permissionGroup=null==e?void 0:e.permissionGroup};t.ApiDescription=e=>(t,n)=>{(0,i.initFieldMetadata)(t,n).description=e};t.Endpoint=e=>(t,n)=>{const o=(0,i.initFieldMetadata)(t,n);o.httpMethod=e.method,o.url=e.url};t.Post=e=>(n,o,r)=>(0,t.Endpoint)({method:i.HttpMethod.POST,url:e})(n,o);t.Put=e=>(n,o,r)=>(0,t.Endpoint)({method:i.HttpMethod.PUT,url:e})(n,o);t.Del=e=>(n,o,r)=>(0,t.Endpoint)({method:i.HttpMethod.DEL,url:e})(n,o);t.Get=e=>(n,o,r)=>(0,t.Endpoint)({method:i.HttpMethod.GET,url:e})(n,o);t.ApiResponse=e=>(t,n,o)=>{const r=(0,i.initFieldMetadata)(t,n);e===String?r.responseValidationDto={id:"",primitiveType:i.DataType.STRING,fields:[]}:e===Number?r.responseValidationDto={id:"",primitiveType:i.DataType.NUMBER,fields:[]}:e===Boolean?r.responseValidationDto={id:"",primitiveType:i.DataType.BOOLEAN,fields:[]}:r.responseValidationDto=(0,i.getObjectMetadata)(e)};t.OpenAccess=()=>(e,t)=>{(0,i.initFieldMetadata)(e,t).openAccess=!0};t.TfaRequired=()=>(e,t)=>{(0,i.initFieldMetadata)(e,t).tfaRequired=!0};t.AccessCondition=e=>(t,n)=>{(0,i.initFieldMetadata)(t,n).accessConditions=e};const RequestDeco=e=>(t,n,o)=>{const r=(0,i.initFieldMetadata)(t,n),s=Reflect.getMetadata("design:paramtypes",t,n)||[];switch(e){case"body":r.bodyValidationDto=(0,i.getObjectMetadata)(s[o]);break;case"params":r.paramsValidationDto=(0,i.getObjectMetadata)(s[o]);break;case"queries":r.queriesValidationDto=(0,i.getObjectMetadata)(s[o])}r.params||(r.params={}),r.params[o]={source:e,diClass:s[o]}};t.Body=()=>RequestDeco("body");t.Params=()=>RequestDeco("params");t.Queries=()=>RequestDeco("queries");t.Headers=()=>RequestDeco("headers");t.Socket=()=>RequestDeco("socket");t.Raw=()=>RequestDeco("raw");t.UriMapper=e=>(t,n)=>{(0,i.initFieldMetadata)(t,n).uriMapper=e};t.CurrentUser=e=>(t,n)=>{const o=(0,i.initFieldMetadata)(t,n);o.userResolver=e,o.serverValue=!0}},function(e,t){e.exports=require("parseurl")},function(e,t){e.exports=require("query-string")},function(e,t,n){"use strict";var i=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},o=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.FilterModelFieldAccessCondition=void 0;const r=n(0),s=n(4);t.FilterModelFieldAccessCondition=(e,t)=>{let n=class _ extends s.AbstractAccessCondition{resolveConditionValue(e){return o(this,void 0,void 0,(function*(){return t(e)}))}getConditionMetadata(){return{name:"filter_model_field",valueType:r.AccessConditionValueType.CHOICES,valueConstraint:(0,r.getObjectMetadata)(e).fields.map((e=>e.name))}}validate(e,t){return o(this,void 0,void 0,(function*(){return!!e&&e.every((e=>t.includes(e)))}))}};return n=i([(0,r.Register)()],n),n}},function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.Transactional=void 0;const o=n(0),r=n(10),s=n(12),a=n(25);t.Transactional=e=>(t,n,d)=>{const c=(0,o.initObjectMetadata)(t);(0,o.initFieldMetadata)(t,n),c.transactional=!0;const l=d.value;d.value=function(...d){return i(this,void 0,void 0,(function*(){const i=this;let c,u,h;try{c=yield i.getCurrentTransaction()}catch(e){}switch(e){case s.TransactionLink.CREATE_NEW:u=!0,h=yield i.createTransaction();break;case s.TransactionLink.INHERIT_OR_CREATE:u=!c,h=c||(yield i.createTransaction());break;case s.TransactionLink.INHERIT_OR_THROW:if(u=!1,!c)throw o.ErrorBuilder.systemError(`No transaction to inherit when executing ${t.constructor.name}:${n}`);h=c}const p=Object.assign(Object.create(i),i),f=Object.keys(p).filter((e=>{var t,n;return(null===(t=p[e])||void 0===t?void 0:t.constructor)&&(null===(n=(0,o.getObjectMetadata)(p[e].constructor))||void 0===n?void 0:n.transactional)}));for(const e of f){const t=p[e],n=Object.assign(Object.create(t),t,{[r.INJECTED_TRANSACTION]:h});p[e]=n}try{Object.assign(p,{[r.INJECTED_TRANSACTION]:h});let e=yield l.call(p,...d);return h.getState()===a.TransactionState.EXECUTING&&u&&(yield h.commit()),e}catch(e){throw h.getState()===a.TransactionState.EXECUTING&&u&&(yield h.rollback()),e}}))},Object.defineProperty(d.value,"name",{value:n})}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TransactionState=void 0,function(e){e.EXECUTING="executing",e.COMMITTED="commited",e.ROLLED_BACK="rolled_back"}(t.TransactionState||(t.TransactionState={}))},function(e,t,n){"use strict";var i=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},o=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.MaximumQueryLimit=void 0;const r=n(0),s=n(4);let a=class MaximumQueryLimit extends s.AbstractAccessCondition{resolveConditionValue(e){return o(this,void 0,void 0,(function*(){let t=e.getQuery().limit;return t&&(t=parseInt(t)),t||0}))}validate(e,t){return o(this,void 0,void 0,(function*(){return e>0&&e<=t}))}getConditionMetadata(){return{name:"maximum_query_limit",valueType:r.AccessConditionValueType.NUMBER,valueConstraint:JSON.stringify({min:1})}}};a=i([(0,r.Register)()],a),t.MaximumQueryLimit=a},function(e,t,n){"use strict";var i=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},o=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.DtoFieldValidation=void 0;const r=n(0),s=n(4);t.DtoFieldValidation=(e,t,n)=>{let a=class _ extends s.AbstractAccessCondition{resolveConditionValue(e){return o(this,void 0,void 0,(function*(){return t(e)}))}getConditionMetadata(){return{name:n||"dto_field_condition",valueType:r.AccessConditionValueType.DTO,valueConstraint:JSON.stringify((0,r.getObjectMetadata)(e))}}validate(e,t){return o(this,void 0,void 0,(function*(){try{for(const n of e)(0,r.validateData)(n,t);return!0}catch(e){return!1}}))}};return a=i([(0,r.Register)()],a),a}},function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.ModelRepository=void 0;const o=n(0),r=n(3),s=n(14),a=n(15);class ModelRepository extends a.AbstractRepository{constructor(e){super(e),this.model=e}getNestedQueries(e){return this.modelMetadata.fields.filter((e=>e.hasMany)).filter((t=>e.fields&&e.fields[t.name])).map((t=>{const n=t.hasMany.relationDto,i=this.getRequestQueryConditionFromQuery(e.fields[t.name],Object.assign(Object.assign({},n),{fields:n.fields.filter((e=>{var t;return e.name!==(null===(t=e.hasMany)||void 0===t?void 0:t.column)}))}));return{modelId:t.hasMany.relationDto.id,queries:i.length?{_and:i}:{}}}))}getUploadHandler(){return i(this,void 0,void 0,(function*(){if(void 0===this.fileUploadHandler){const e=(0,o.getServiceProvider)().getInjector();this.fileUploadHandler=e.resolveOptional(s.AbstractFileUploadHandler)||null,yield e.initInstances()}return this.fileUploadHandler}))}getRequestQueryConditionFromQuery(e,t){var n;const i=[];for(const s of(0,r.getDirectFields)(t))if(e[s.name])if(s.pk||s.fk||s.isSymbol)i.push({_in:{[s.name]:e[s.name]}});else if(s.enum)i.push({_in:{[s.name]:e[s.name]}});else switch(s.dataType){case o.DataType.STRING:if(s.searchable){const t={[(null==s?void 0:s.searchable.caseSensitive)?(null==s?void 0:s.searchable.accentSensitive)?"_sub":"_usub":(null===(n=null==s?void 0:s.searchable)||void 0===n?void 0:n.accentSensitive)?"_isub":"_iusub"]:{[s.name]:e[s.name]}};i.push(t)}else i.push({_eq:{[s.name]:e[s.name]}});break;case o.DataType.NUMBER:const t=new o.RangeQueryDto;Object.assign(t,e[s.name]),t.min&&(t.minExclusive?i.push({_gt:{[s.name]:t.min}}):i.push({_gte:{[s.name]:t.min}})),t.max&&(t.maxExclusive?i.push({_lt:{[s.name]:t.max}}):i.push({_lte:{[s.name]:t.max}}))}return i}uriHandling(e,t){return i(this,void 0,void 0,(function*(){const n=yield this.getUploadHandler();if(!n)return;const i=t.use(this.model);for(const o of this.modelMetadata.fields)if(o.uriMapper)for(const r of e){const e=r[o.name];if(!e)continue;const s=yield o.uriMapper(t,r,e);s&&(yield n.moveFile(e,s),r[o.name]=s,yield i.updateOne(r))}}))}beforeReturning(e){var t;return i(this,void 0,void 0,(function*(){const n=yield this.getUploadHandler();for(const i of e)for(const e of this.modelMetadata.fields)if(e.uriMapper&&n){if(!i[e.name])continue;i[e.name]=(null===(t=e.mimeProps)||void 0===t?void 0:t.public)?yield n.resolvePublicUrl(i[e.name]):yield n.resolvePrivateUrl(i[e.name])}}))}createMany({principal:e,body:t,tx:n}){return i(this,void 0,void 0,(function*(){const i=t.records;if(!i.length)return{records:[]};const s=(0,r.getDirectFields)(this.modelMetadata),a=this.modelMetadata.fields.filter((e=>!!e.hasMany));t.records=i.map((e=>s.reduce(((t,n)=>Object.assign(t,void 0!==e[n.name]?{[n.name]:e[n.name]}:{})),{}))),yield this.beforeCreating(e,t.records);let d=t.records.length?yield n.use(this.model).createMany(t.records):[];yield this.uriHandling(d,n),yield this.beforeReturning(d);const c=this.modelMetadata.fields.filter((e=>e.pk||e.serverValue||e.mimeProps)).map((e=>e.name));d=this.project(d,c);for(const r of a){const s=d.map(((e,t)=>(i[t][r.name]||[]).map((t=>Object.assign(Object.assign({},t),{[r.hasMany.column]:e.id}))))).reduce(((e,t)=>e.concat(t)),[]);if(s.length){const i=new ModelRepository((0,o.getModelById)(r.hasMany.relationDto.id));t.records=s;const a=yield i.createMany({principal:e,body:t,tx:n});for(let e=0;e<a.records.length;e++)s[e]=Object.assign(Object.assign({},s[e]),a.records[e]);for(let e=0;e<d.length;e++){const t=[];for(let n=0;n<s.length;n++)s[n][r.hasMany.column]===d[e].id&&t.push(a.records[e]);d[e]=Object.assign(Object.assign({},d[e]),{[r.name]:t})}}}return{records:d}}))}updateMany({principal:e,queries:t,body:n,tx:s}){return i(this,void 0,void 0,(function*(){let i={};const a=this.modelMetadata.fields.filter((e=>!!e.hasMany)),d=(0,r.getDirectFields)(this.modelMetadata).filter((e=>void 0!==n.update[e.name])),c=d.reduce(((e,t)=>Object.assign(e,{[t.name]:n.update[t.name]})),{});if(t.fields){const e=this.getRequestQueryConditionFromQuery(t.fields,this.modelMetadata);e.length&&(i={_and:[...e]})}const l=this.getNestedQueries(t);let u=[];if(l.length){const e=yield s.use(this.model).getMany(i,{projection:["id"]},l);u=e.records.map((e=>e.id)),u.length&&d.length&&(yield s.use(this.model).updateMany({_in:{id:u}},c,!1))}else if(d.length)u=yield s.use(this.model).updateMany(i,c,!0);else{const e=yield s.use(this.model).getMany(i,{projection:["id"]});u=e.records.map((e=>e.id))}let h=u.map((e=>Object.assign(Object.assign({},c),{id:e})));yield this.uriHandling(h,s),yield this.beforeReturning(h);for(const t of a){const i=n.update[t.name];if(void 0===i||!u.length)continue;if(u.length>1)throw o.ErrorBuilder.systemError(`Multiple records found while updating @HasMany field: ${t.name}`);const r=h.find((e=>e.id===u[0])),a=(0,o.getModelById)(t.hasMany.relationDto.id),d=s.use(a),c=(yield d.getRecords({_eq:{[t.hasMany.column]:r.id}})).map((e=>e.id)),l=i.map((e=>e.id)).filter((e=>!!e)),p=c.filter((e=>!l.includes(e))),f=i.filter((e=>!e.id)).map((e=>Object.assign(Object.assign({},e),{[t.hasMany.column]:r.id}))),g=i.filter((e=>!!e.id));yield d.deleteMany({_in:{id:p}});const y=new ModelRepository(a),v=yield y.createMany({principal:e,body:{records:f},tx:s}),m=f.map(((e,t)=>Object.assign(Object.assign({},e),v.records[t])));r[t.name]=m.concat(g)}let p=["id"];return t.returning&&(p=[...p,...Object.keys(n.update).filter((e=>void 0!==n.update[e]))]),{modified:this.project(h,p)}}))}getMany({queries:e,queryProvider:t}){var n;return i(this,void 0,void 0,(function*(){const i=[];if(e.fields&&i.push(...this.getRequestQueryConditionFromQuery(e.fields,this.modelMetadata)),e.search){const t=this.modelMetadata.fields.filter((e=>e.searchable)).map((t=>({_iusub:{[t.name]:e.search}})));t.length&&i.push({_or:t})}const r=yield t.use(this.model).getMany(i.length?{_and:i}:{},{limit:e.limit,page:e.page,projection:e.projection,order:null===(n=e.order)||void 0===n?void 0:n.map((e=>{const t=Object.keys(e).find((t=>!!e[t]));return[t,e[t]]}))},this.getNestedQueries(e)),s=r.records.map((e=>e.id));for(const n of this.modelMetadata.fields){if(!n.hasMany||e.projection&&!e.projection.includes(n.name))continue;const i=(0,o.getModelById)(n.hasMany.relationDto.id),a=new ModelRepository(i),d=s.length?yield a.getMany({queries:{fields:{[n.hasMany.column]:s}},queryProvider:t}):{records:[]};for(const e of r.records)e[n.name]=d.records.filter((t=>t[n.hasMany.column]===e.id))}return yield this.beforeReturning(r.records),{total:r.total,records:this.project(r.records,e.projection)}}))}deleteMany({queries:e,tx:t}){return i(this,void 0,void 0,(function*(){let n={};if(e.fields){const t=this.getRequestQueryConditionFromQuery(e.fields,this.modelMetadata);t.length&&(n={_and:[...t]})}const i=this.getNestedQueries(e);let o=[];if(i.length){const e=yield t.use(this.model).getRecords(n,{},i);yield t.use(this.model).deleteMany({_in:{id:e.map((e=>e.id))}}),o=e}else o=yield t.use(this.model).deleteMany(n,e.returning);return{modified:o}}))}}t.ModelRepository=ModelRepository},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractSocketController=void 0;t.AbstractSocketController=class AbstractSocketController{constructor(e){this.channel=e}onChannelJoin(e){}onChannelLeave(e){}onMessage(e,t){}}},function(e,t){e.exports=require("redis")},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractServerSocket=void 0;const i=n(0);t.AbstractServerSocket=class AbstractServerSocket{constructor(e){this.socketInfo=e}getId(){return this.socketInfo.id}getAuthInfo(){return this.socketInfo.authInfo}send(e,t){t?this.socketInfo.channels.find((e=>e.name===t&&e.serverToClientAllowed))&&this.sendRaw({type:i.MessageType.PLAIN,data:{message:e,channel:t}}):this.sendRaw({type:i.MessageType.PLAIN,data:{message:e}})}sendRaw(e){this.physicSend(e)}disconnect(){this.physicClose()}removeChannels(e){this.socketInfo.channels=this.socketInfo.channels.filter((t=>!e.includes(t.name)))}addChannels(e){this.socketInfo.channels.push(...e)}getChannelsInfo(){return this.socketInfo.channels}}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractFileService=void 0;t.AbstractFileService=class AbstractFileService{}},function(e,t){e.exports=require("fs")},function(e,t){e.exports=require("path")},function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractDatabaseAdapter=void 0;const o=n(0);t.AbstractDatabaseAdapter=class AbstractDatabaseAdapter{constructor(){this.modelMetadata=[],this.models=[],this.modelConnections={}}init(){return i(this,void 0,void 0,(function*(){this.models=((0,o.getGlobalStore)().models||[]).slice(),this.modelMetadata=this.models.map((e=>(0,o.getObjectMetadata)(e))),this.modelConnections=this.modelMetadata.reduce(((e,t)=>Object.assign(e,{[t.id]:{connection:void 0}})),{})}))}exit(){}}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractDatabaseMigrator=void 0;t.AbstractDatabaseMigrator=class AbstractDatabaseMigrator{}},function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var o=Object.getOwnPropertyDescriptor(t,n);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,o)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),o=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||i(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),t.QueryTypes=void 0,o(n(38),t),o(n(19),t),o(n(39),t),o(n(40),t),o(n(6),t),o(n(8),t),o(n(20),t),o(n(7),t),o(n(41),t),o(n(9),t),o(n(43),t),o(n(44),t),o(n(2),t),o(n(45),t),o(n(4),t),o(n(23),t),o(n(26),t),o(n(27),t),o(n(1),t),o(n(13),t),o(n(46),t),o(n(47),t),o(n(48),t),o(n(28),t),o(n(49),t),o(n(50),t),o(n(15),t),o(n(5),t),o(n(51),t),o(n(53),t),o(n(55),t),o(n(29),t),o(n(16),t),o(n(14),t),o(n(56),t),o(n(57),t),o(n(58),t),o(n(59),t),o(n(60),t),o(n(65),t),o(n(66),t),o(n(11),t),o(n(67),t),o(n(68),t),o(n(32),t),o(n(24),t),o(n(69),t),o(n(70),t),o(n(71),t),o(n(12),t),o(n(72),t),o(n(17),t),o(n(73),t),o(n(35),t),o(n(74),t),o(n(76),t),o(n(36),t);var r=n(18);Object.defineProperty(t,"QueryTypes",{enumerable:!0,get:function(){return r.QueryTypes}})},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FileOperation=void 0,function(e){e.GET="getObject",e.PUT="putObject",e.DELETE="deleteObject"}(t.FileOperation||(t.FileOperation={}))},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},function(e,t,n){"use strict";var i=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},o=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},r=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))},s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultHttpRequestHandler=void 0;const a=n(0),d=s(n(21)),c=n(42),l=s(n(22)),u=n(8),h=n(7),p=n(1),f=n(2),g=n(11);let y=class DefaultHttpRequestHandler extends f.AbstractHttpRequestHandler{constructor(e,t){super("",e),this.logger=e,this.authorizationProvider=t}accessControl(e,t){return r(this,void 0,void 0,(function*(){if(e.endpointMetadata.httpMethod!==a.SocketMethod.MESSAGE){const n=yield this.authorizationProvider.resolvePrincipal(t);if(t.setAuthInfo(n),!e.endpointMetadata.openAccess&&(yield this.authorizationProvider.authorize(n,t,e),e.endpointMetadata.tfaRequired&&!(null==n?void 0:n.hasTfa)))throw a.ErrorBuilder.error(g.Errors.TFA_REQUIRED)}}))}handleRequest(e,t){return r(this,void 0,void 0,(function*(){yield this.accessControl(e,t);const n=Object.values(e.endpointMetadata.params||{}).map((e=>{switch(e.source){case"body":return t.getBody();case"params":return t.getParams();case"queries":return t.getQuery();case"headers":return t.getHeaders();case"raw":return t}})),i=yield e.endpoint.controller[e.endpointMetadata.name](...n);return e.endpointMetadata.responseValidationDto&&(i.value=(0,a.stripData)(i.value,e.endpointMetadata.responseValidationDto)),i}))}exit(){}handle(e){return r(this,void 0,void 0,(function*(){const t=e.method,n=(0,d.default)({url:e.fullPath});let i={};const o=(yield this.getMountedEndpointInfo()).find((e=>{const o=e.endpointMetadata.httpMethod===t&&(0,c.match)(e.endpointMetadata.url,{decode:decodeURIComponent})(n.pathname);return!!o&&(i=o,!0)}));if(!o)throw this.logger.debug(e),a.ErrorBuilder.error(g.Errors.NOT_FOUND,"Handler not found");const r=new h.HttpRequest({method:t,headers:e.headers,pathName:n.pathname||"",hash:n.hash||"",query:l.default.parse(decodeURIComponent(n.search||"")),params:i.params,body:e.body},o.endpointMetadata);let s;try{for(const e of this.getMiddleware())if(s=yield e.intercept(r),s)break;if(s||(s=yield this.handleRequest(o,r)),!(s&&s instanceof u.HttpResponse))throw a.ErrorBuilder.systemError(`Invalid response value returned ${o.endpoint.httpMethod}:${o.endpoint.mount}, required instance of ${u.HttpResponse.name}, found ${s?null==s?void 0:s.constructor.name:s}`)}catch(e){this.logger.error(e),s=u.ResponseBuilder.json({name:e.name,message:e.message}).status([g.Errors.ACCESS_DENIED,g.Errors.AUTHENTICATION_ERROR,g.Errors.SESSION_EXPIRED].includes(e.name)?401:[g.Errors.SYSTEM_ERROR,g.Errors.CANNOT_LOCK].includes(e.name)?500:400).get()}return s}))}getMiddleware(){return[]}};y=i([(0,a.Injectable)(),o("design:paramtypes",[a.AbstractLogger,p.AbstractHttpAuthorizationProvider])],y),t.DefaultHttpRequestHandler=y},function(e,t){e.exports=require("path-to-regexp")},function(e,t,n){"use strict";var i=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},o=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},r=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}},s=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.CrudHttpController=void 0;const a=n(0),d=n(23),c=n(7),l=n(24),u=n(12),h=n(20),p=n(9),f=n(1),g=n(8),y=n(26),v=n(27);class CrudHttpController extends p.AbstractHttpController{constructor(e,t,n){super(n),this.model=e,this.crudRepository=t,this.databaseAdapter=n,this.modelMetadata=(0,a.getObjectMetadata)(e)}getMountedUrl(){return`/${this.model.name.toLowerCase()}`}static queryFieldDto(e){const t={id:"",fields:CrudHttpController.getRequestQueryFieldFromModel(e)},n={name:"fields",description:"Filter records by value of their fields."};return n.dataType=a.DataType.OBJECT,n.elementDto=t,n}static projectionFieldDto(e){const t={name:"projection",description:"Project the returning records to contain only certain fields. Omit to return all."};return t.dataType=a.DataType.ARRAY,t.vectorProps={superSet:e.fields.map((e=>e.name)),allowDuplicated:!1,minLength:1,elementDataType:a.DataType.STRING},t}static getBodyDtoRecordClass(e,t,n){const i={id:"",fields:[]};let o=e.fields.filter((e=>!e.hasMany));o="get_response"===t||"query"===t?o:"create_response"===t?o.filter((e=>e.pk||e.serverValue)):"create_body"===t||"update_body"===t?o.filter((e=>{var t;return!e.serverValue&&!(null===(t=e.pk)||void 0===t?void 0:t.isAutoIncrement)||!!n&&!n.fields.find((t=>{var n;return(null===(n=t.hasMany)||void 0===n?void 0:n.column)===e.name}))})):[];const r=e.fields.filter((e=>!!e.hasMany));return i.fields.push(...o.map((e=>Object.assign(Object.assign({},e),{elementDto:e.elementDto&&("update_body"===t?(0,a.partialize)(e.elementDto):e.elementDto),isRequired:!("query"===t||"update_body"===t||"get_response"===t&&!n)&&e.isRequired}))),...r.map((n=>{var i;const o=CrudHttpController.getBodyDtoRecordClass(n.hasMany.relationDto,t,e);return{description:`All records of "${null===(i=n.hasMany)||void 0===i?void 0:i.relationDto.id}" table in this relationship.`,name:n.name,dataType:a.DataType.ARRAY,isRequired:"create_response"===t,vectorProps:{elementDataType:a.DataType.OBJECT,minLength:0},elementDto:Object.assign(Object.assign({},o),{fields:("create_body"===t||"update_body"===t?o.fields.filter((e=>{var t;return e.name!==(null===(t=n.hasMany)||void 0===t?void 0:t.column)})):o.fields).map((e=>"update_body"===t?Object.assign(Object.assign({},e),{isRequired:!1,allowNull:!0}):e))})}}))),i}static getRequestQueryFieldFromModel(e){return e.fields.map((e=>{const t={};if(t.name=e.name,t.description=e.description,t.isRequired=!1,e.pk||e.fk||e.isSymbol)t.dataType=a.DataType.ARRAY,t.vectorProps={elementDataType:e.dataType,allowDuplicated:!1,allowNull:e.allowNull,minLength:1};else if(e.hasMany){const n={id:"",fields:CrudHttpController.getRequestQueryFieldFromModel(e.hasMany.relationDto).filter((t=>{var n;return t.name!==(null===(n=e.hasMany)||void 0===n?void 0:n.column)})),relaxed:!0};t.dataType=a.DataType.OBJECT,t.elementDto=n}else if(e.enum)t.dataType=a.DataType.ARRAY,t.vectorProps={superSet:e.enum,allowDuplicated:!1,minLength:1,elementDataType:e.dataType,allowNull:e.allowNull};else switch(e.dataType){case a.DataType.STRING:t.dataType=a.DataType.STRING;break;case a.DataType.NUMBER:t.dataType=a.DataType.OBJECT,t.elementDto=(0,a.getObjectMetadata)(a.RangeQueryDto)}return t}))}getAuthProvider(){return s(this,void 0,void 0,(function*(){if(void 0===this.authProvider){const e=(0,a.getServiceProvider)().getInjector();this.authProvider=e.resolveOptional(f.AbstractHttpAuthorizationProvider)||null,yield e.initInstances()}return this.authProvider}))}createManyEndpoinMetadata(){const e={};return e.httpMethod=a.HttpMethod.POST,e.url=this.getMountedUrl(),e.name=CrudHttpController.prototype.createMany.name,e.displayName="createMany"+this.model.name,e.bodyValidationDto=CrudHttpController.getCreateManyBodyValidator(this.modelMetadata),e.responseValidationDto=CrudHttpController.getCreateManyResponseValidator(this.modelMetadata),e.accessConditions=[(0,v.DtoFieldValidation)(this.model,(e=>e.getBody().records))],e.params={0:{source:"raw"}},e}getManyEndpointMetadata(){const e={};return e.httpMethod=a.HttpMethod.GET,e.url=this.getMountedUrl(),e.name=CrudHttpController.prototype.getMany.name,e.displayName="getAll"+this.model.name,e.queriesValidationDto=CrudHttpController.getGetManyQueryValidator(this.modelMetadata),e.responseValidationDto=CrudHttpController.getGetManyResponseValidator(this.modelMetadata),e.accessConditions=[(0,v.DtoFieldValidation)(this.model,(e=>[e.getQuery().fields])),(0,d.FilterModelFieldAccessCondition)(this.model,(e=>e.getQuery().projection)),y.MaximumQueryLimit],e.params={0:{source:"raw"}},e}updateManyEndpoinMetadata(){const e={};return e.httpMethod=a.HttpMethod.PUT,e.url=this.getMountedUrl(),e.name=CrudHttpController.prototype.updateMany.name,e.displayName="update"+this.model.name,e.queriesValidationDto=CrudHttpController.getUpdateManyQueryValidator(this.modelMetadata),e.bodyValidationDto=CrudHttpController.getUpdateManyBodyValidator(this.modelMetadata),e.responseValidationDto=CrudHttpController.getUpdateManyResponseValidator(this.modelMetadata),e.accessConditions=[(0,d.FilterModelFieldAccessCondition)(this.model,(e=>{const t=e.getBody().update;return t?Object.keys((0,a.leanData)(t)):[]})),(0,v.DtoFieldValidation)(this.model,(e=>[e.getQuery().fields]),"dto_field_validation_query"),(0,v.DtoFieldValidation)(this.model,(e=>[e.getBody().update]),"dto_field_validation_body")],e.params={0:{source:"raw"}},e}deleteManyEndpoinMetadata(){const e={};return e.httpMethod=a.HttpMethod.DEL,e.url=this.getMountedUrl(),e.name=CrudHttpController.prototype.deleteMany.name,e.displayName="delete"+this.model.name,e.queriesValidationDto=CrudHttpController.getUpdateManyQueryValidator(this.modelMetadata),e.responseValidationDto=CrudHttpController.getUpdateManyResponseValidator(this.modelMetadata),e.params={0:{source:"raw"}},e.accessConditions=[(0,v.DtoFieldValidation)(this.model,(e=>[e.getQuery().fields]))],e}static getCreateManyBodyValidator(e){const t={id:"",fields:[]},n={name:"records",description:"Array of records to be created."};return n.dataType=a.DataType.ARRAY,n.isRequired=!0,n.vectorProps={elementDataType:a.DataType.OBJECT,minLength:0},n.elementDto=CrudHttpController.getBodyDtoRecordClass(e,"create_body"),t.fields.push(n),t}static getCreateManyResponseValidator(e){const t={id:"",fields:[]},n={name:"records",description:"Array of records had just been created."};return n.dataType=a.DataType.ARRAY,n.isRequired=!0,n.vectorProps={elementDataType:a.DataType.OBJECT,minLength:0},n.elementDto=CrudHttpController.getBodyDtoRecordClass(e,"create_response"),t.fields.push(n),t}static getGetManyResponseValidator(e){const t={id:"",fields:[]},n={name:"total",description:"Number of records found, zero is returned if the request is not paged."};n.dataType=a.DataType.NUMBER,n.isRequired=!0,t.fields.push(n);const i={name:"records",description:"The found records. All records will be returned if the request is not paged."};return i.dataType=a.DataType.ARRAY,i.isRequired=!0,i.vectorProps={elementDataType:a.DataType.OBJECT,minLength:0},i.elementDto=CrudHttpController.getBodyDtoRecordClass(e,"get_response"),t.fields.push(i),t}static getGetManyQueryValidator(e){const t={id:"",fields:[CrudHttpController.queryFieldDto(e)]},n={name:"search",description:"Filter records for their @Searchable denoted fields."};n.dataType=a.DataType.STRING,t.fields.push(n),t.fields.push(CrudHttpController.projectionFieldDto(e));const i={name:"order",description:"Sort the dataset before getting result by order given in the array. Field appears first in the array will be sorted first."};i.dataType=a.DataType.ARRAY,i.vectorProps={elementDataType:a.DataType.OBJECT,minLength:1};const o={id:"",fields:[]};o.fields.push(...e.fields.filter((e=>!e.hasMany)).map((e=>{const t={};return t.name=e.name,t.isRequired=!1,t.dataType=a.DataType.STRING,t.enum=["asc","desc"],t}))),i.elementDto=o,t.fields.push(i);const r={name:"limit",description:"Limit the number of returning result."};r.dataType=a.DataType.NUMBER,r.rangeProps={min:1},t.fields.push(r);const s={name:"page",description:"Page the returning result, default to 1 if ommited. Has no effect if limit is not set."};return s.dataType=a.DataType.NUMBER,s.rangeProps={min:1},t.fields.push(s),t}static getUpdateManyQueryValidator(e){const t={name:"returning",description:"Whether to return the affected records by this request."};return t.dataType=a.DataType.BOOLEAN,t.isRequired=!1,{id:"",fields:[t,CrudHttpController.queryFieldDto(e)]}}static getUpdateManyBodyValidator(e){const t={id:"",fields:[]},n={name:"update",isRequired:!0,description:"The update data to apply to found records."};return n.dataType=a.DataType.OBJECT,n.elementDto=CrudHttpController.getBodyDtoRecordClass(e,"update_body"),t.fields.push(n),t}static getUpdateManyResponseValidator(e){const t={id:"",fields:[]},n={name:"modified",description:"Array of affected records."};return n.dataType=a.DataType.ARRAY,n.vectorProps={minLength:0,elementDataType:a.DataType.OBJECT},n.elementDto=n.elementDto=CrudHttpController.getBodyDtoRecordClass(e,"get_response"),t.fields.push(n),t}getEndpointMetadata(){var e,t,n,i;let o=super.getEndpointMetadata();const r=[];(null===(e=this.modelMetadata.ignoreCrud)||void 0===e?void 0:e.includes(a.HttpMethod.GET))?o=o.filter((e=>e.name!==CrudHttpController.prototype.getMany.name)):r.push(this.getManyEndpointMetadata()),(null===(t=this.modelMetadata.ignoreCrud)||void 0===t?void 0:t.includes(a.HttpMethod.POST))?o=o.filter((e=>e.name!==CrudHttpController.prototype.createMany.name)):r.push(this.createManyEndpoinMetadata()),(null===(n=this.modelMetadata.ignoreCrud)||void 0===n?void 0:n.includes(a.HttpMethod.PUT))?o=o.filter((e=>e.name!==CrudHttpController.prototype.updateMany.name)):r.push(this.updateManyEndpoinMetadata()),(null===(i=this.modelMetadata.ignoreCrud)||void 0===i?void 0:i.includes(a.HttpMethod.DEL))?o=o.filter((e=>e.name!==CrudHttpController.prototype.deleteMany.name)):r.push(this.deleteManyEndpoinMetadata());for(const e of r){const t=o.findIndex((t=>t.httpMethod===e.httpMethod&&t.url===e.url||t.name===e.name&&(!t.httpMethod||!t.url)));t>=0?o[t]=Object.assign(Object.assign(Object.assign({},e),o[t]),{accessConditions:[...e.accessConditions||[],...o[t].accessConditions||[]]}):o.push(e)}return o}createMany(e){return s(this,void 0,void 0,(function*(){const t=yield this.getCurrentTransaction(),n=yield this.getAuthProvider(),i=n&&(yield n.resolvePrincipal(e)),o=yield this.crudRepository.createMany({principal:i,body:e.getBody(),tx:t});return g.ResponseBuilder.json(o).get()}))}getMany(e){return s(this,void 0,void 0,(function*(){const t=yield this.crudRepository.getMany({queries:e.getQuery(),queryProvider:this.databaseAdapter});return g.ResponseBuilder.json(t).get()}))}updateMany(e){return s(this,void 0,void 0,(function*(){const t=yield this.getCurrentTransaction(),n=yield this.getAuthProvider(),i=n&&(yield n.resolvePrincipal(e)),o=yield this.crudRepository.updateMany({principal:i,queries:e.getQuery(),body:e.getBody(),tx:t});return g.ResponseBuilder.json(o).get()}))}deleteMany(e){return s(this,void 0,void 0,(function*(){const t=yield this.getCurrentTransaction(),n=yield this.crudRepository.deleteMany({queries:e.getQuery(),tx:t});return g.ResponseBuilder.json({modified:n.modified.map((e=>e.id)).map((e=>({id:e})))}).get()}))}}i([(0,l.Transactional)(u.TransactionLink.INHERIT_OR_CREATE),(0,h.ApiDescription)("Create records of this table."),(0,h.AccessCondition)([]),r(0,(0,h.Raw)()),o("design:type",Function),o("design:paramtypes",[c.HttpRequest]),o("design:returntype",Promise)],CrudHttpController.prototype,"createMany",null),i([(0,h.AccessCondition)([]),(0,h.ApiDescription)("Get records of this table."),r(0,(0,h.Raw)()),o("design:type",Function),o("design:paramtypes",[c.HttpRequest]),o("design:returntype",Promise)],CrudHttpController.prototype,"getMany",null),i([(0,l.Transactional)(u.TransactionLink.INHERIT_OR_CREATE),(0,h.ApiDescription)("Find and update records which match search condition."),(0,h.AccessCondition)([]),r(0,(0,h.Raw)()),o("design:type",Function),o("design:paramtypes",[c.HttpRequest]),o("design:returntype",Promise)],CrudHttpController.prototype,"updateMany",null),i([(0,l.Transactional)(u.TransactionLink.INHERIT_OR_CREATE),(0,h.ApiDescription)("Find and remove records which match search condition."),(0,h.AccessCondition)([]),r(0,(0,h.Raw)()),o("design:type",Function),o("design:paramtypes",[c.HttpRequest]),o("design:returntype",Promise)],CrudHttpController.prototype,"deleteMany",null),t.CrudHttpController=CrudHttpController},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractHttpMiddleware=void 0;t.AbstractHttpMiddleware=class AbstractHttpMiddleware{}},function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.RedisRbacAuthProvider=void 0;const o=n(13);class RedisRbacAuthProvider extends o.AbstractRbacAuthProvider{constructor(e,t,n,i,o,r,s,a=3e4){super(i,o,s),this.serviceId=e,this.rbacChannel=t,this.principalChannel=n,this.authDataResolver=i,this.principalResolver=o,this.cacheService=r,this.logger=s,this.redisDataRetentionDurationMs=a,this.lastRbacFetchTimestamp=0,this.principalCache={}}getRbacCache(){return i(this,void 0,void 0,(function*(){if(this.lastRbacFetchTimestamp+this.redisDataRetentionDurationMs<Date.now()){const e=yield this.cacheService.hget(this.rbacChannel,this.serviceId);this.rbacCache=e,this.lastRbacFetchTimestamp=Date.now()}return this.rbacCache}))}getRolesOfPrincipal(e){return i(this,void 0,void 0,(function*(){const t=String(e.id);let n=this.principalCache[t];if(!n||n.lastFetchTimestamp+this.redisDataRetentionDurationMs<Date.now()){const e=yield this.cacheService.hget(this.principalChannel,t),i=e?"string"==typeof e?JSON.parse(e):e:[];n={lastFetchTimestamp:Date.now(),roles:i},this.principalCache[t]=n}return n.roles}))}}t.RedisRbacAuthProvider=RedisRbacAuthProvider},function(e,t,n){"use strict";var i=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},o=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},r=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.SocketRbacAuthProvider=void 0;const s=n(0),a=n(13),d=n(19);let c=class SocketRbacAuthProvider extends a.AbstractRbacAuthProvider{constructor(e,t,n,i,o,r){super(n,i,o),this.rbacCacheChannel=e,this.principalCacheChannel=t,this.authDataResolver=n,this.principalResolver=i,this.logger=o,this.socketProvider=r,this.idResolvers=[]}exit(){var e;null===(e=this.socket)||void 0===e||e.close()}init(){return r(this,void 0,void 0,(function*(){this.socket=yield this.socketProvider(),this.socket.onMessage(((e,t)=>{switch(t){case this.rbacCacheChannel:this.rbacCache=e;break;case this.principalCacheChannel:const{principalId:t,roleIds:n}=e,i=this.idResolvers.find((e=>e.principalId===t));if(i){for(const e of i.resolvers)e(n);i.resolvers=[]}}})),this.socket.joinChannels([this.rbacCacheChannel,this.principalCacheChannel])}))}getRbacCache(){return r(this,void 0,void 0,(function*(){return this.rbacCache}))}getRolesOfPrincipal(e){return r(this,void 0,void 0,(function*(){return new Promise((t=>{var n;let i=this.idResolvers.find((t=>t.principalId===e.id));i||(i={principalId:e.id,resolvers:[]},this.idResolvers.push(i)),i.resolvers.length||null===(n=this.socket)||void 0===n||n.send(e.id,this.principalCacheChannel),i.resolvers.push(t)}))}))}};c=i([(0,s.Initable)(),o("design:paramtypes",[String,String,Function,d.AbstractPrincipalResolver,s.AbstractLogger,Function])],c),t.SocketRbacAuthProvider=c},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.DtoRepository=t.MultipleMap=t.SingleMap=void 0;const o=n(0),r=n(15),s=n(28);t.SingleMap=(e,t,n,i,o)=>({multiple:!1,modelClass:e,forwardQuery:t,forwardMapping:e=>{const t=n(e[0]||{});return t&&[t]},rootMapping:e=>{const t=e&&e[0];return i(t)},nestedMapping:o});t.MultipleMap=(e,t,n,i,o)=>({multiple:!0,modelClass:e,forwardQuery:t,forwardMapping:n,rootMapping:i,nestedMapping:o});class DtoRepository extends r.AbstractRepository{constructor(e,t){super(e),this.model=e,this.dissolver=t}getMapValue(e,t,n,r,s){return i(this,void 0,void 0,(function*(){for(const i of n){const n=yield t(i);let a=r?yield r(i,i.forwardMapping(n),n):i.forwardMapping(n);if(i.nestedMapping&&a)for(const n of a)yield this.getMapValue(e,t,i.nestedMapping(n),r,s);s&&(a=yield s(i,i.forwardMapping(n),n));const d=i.rootMapping(a);(0,o.deepMerge)(e,d)}}))}createMany({principal:e,body:t,tx:n}){return i(this,void 0,void 0,(function*(){const r=[];yield this.beforeCreating(e,t.records);for(const a of t.records)yield this.getMapValue(a,(e=>i(this,void 0,void 0,(function*(){const t=new s.ModelRepository(e.modelClass);return(yield t.getMany({queries:e.forwardQuery(),queryProvider:n})).records}))),this.dissolver(a),((t,r,a)=>i(this,void 0,void 0,(function*(){if(!r)return[];const i=new s.ModelRepository(t.modelClass),d=t.forwardQuery();if(t.multiple){yield i.deleteMany({queries:d,tx:n});return(yield i.createMany({principal:e,body:{records:r},tx:n})).records}{const s=r[0];if(!s)return[];if(0===a.length){return(yield i.createMany({principal:e,body:{records:r},tx:n})).records}if(1===a.length){const t=yield i.updateMany({principal:e,queries:d,body:{update:s},tx:n});return[Object.assign(Object.assign(Object.assign({},a[0]),s),t.modified[0])]}throw o.ErrorBuilder.validationError(`Found multiple record when creating ${t.modelClass.name}`)}})))),r.push(a);return{records:r}}))}updateMany({principal:e,queries:t,body:n,tx:r}){var a;return i(this,void 0,void 0,(function*(){if(!(null===(a=t.fields)||void 0===a?void 0:a.id)||1!==t.fields.id.length)throw o.ErrorBuilder.validationError("Missing required id field in query");const d=Object.assign(Object.assign({},n.update),{id:t.fields.id[0]});yield this.beforeCreating(e,[d]),yield this.getMapValue(d,(e=>i(this,void 0,void 0,(function*(){const t=new s.ModelRepository(e.modelClass);return(yield t.getMany({queries:e.forwardQuery(),queryProvider:r})).records}))),this.dissolver(d),((t,n,o)=>i(this,void 0,void 0,(function*(){if(!n)return[];const i=new s.ModelRepository(t.modelClass),a=t.forwardQuery();if(t.multiple){yield i.deleteMany({queries:a,tx:r});return(yield i.createMany({principal:e,body:{records:n},tx:r})).records}{const t=n[0];return t?0==o.length?[]:(o.length>1?(yield i.deleteMany({queries:a,tx:r}),yield i.createMany({principal:e,body:{records:[t]},tx:r})):yield i.updateMany({principal:e,queries:a,body:{update:t},tx:r}),o.map((e=>Object.assign(Object.assign({},e),t)))):[]}}))));let c=["id"];return t.returning&&(c=[...c,...Object.keys(n.update).filter((e=>void 0!==n.update[e]))]),{modified:d.id?this.project([d],c):[]}}))}getMany({queries:e,queryProvider:t}){var n;return i(this,void 0,void 0,(function*(){if(!(null===(n=e.fields)||void 0===n?void 0:n.id)||1!==e.fields.id.length)throw o.ErrorBuilder.validationError("Missing required id field in query");const r={id:e.fields.id[0]};return yield this.getMapValue(r,(()=>i(this,void 0,void 0,(function*(){return[]}))),this.dissolver(r),(e=>i(this,void 0,void 0,(function*(){const n=new s.ModelRepository(e.modelClass);return(yield n.getMany({queries:e.forwardQuery(),queryProvider:t})).records})))),r.id?{records:this.project([r],e.projection),total:1}:{records:[],total:0}}))}deleteMany({queries:e,tx:t}){var n;return i(this,void 0,void 0,(function*(){if(!(null===(n=e.fields)||void 0===n?void 0:n.id)||1!==e.fields.id.length)throw o.ErrorBuilder.validationError("Missing required id field in query");const r={id:e.fields.id[0]};return yield this.getMapValue(r,(()=>i(this,void 0,void 0,(function*(){return[]}))),this.dissolver(r),void 0,(n=>i(this,void 0,void 0,(function*(){const i=new s.ModelRepository(n.modelClass),o=n.forwardQuery();return(yield i.deleteMany({queries:Object.assign(Object.assign({},o),{returning:e.returning}),tx:t})).modified})))),{modified:r.id?[r]:[]}}))}}t.DtoRepository=DtoRepository},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},function(e,t,n){"use strict";var i=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},o=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},r=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))},s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.LocalSocketManager=void 0;const a=n(0),d=s(n(52)),c=s(n(21)),l=s(n(22)),u=n(30),h=n(5),p=n(16),f=n(31),g=n(1);var y;!function(e){e.SEND="SEND",e.CLOSE="CLOSE",e.SAVE="SAVE"}(y||(y={}));class RedisSocket extends f.AbstractServerSocket{constructor(e,t,n){super(n),this.socketChannelName=e,this.redisClient=t,this.socketInfo=n}physicSend(e){this.redisClient.publish(this.socketChannelName,JSON.stringify({type:y.SEND,data:e}))}physicClose(){this.redisClient.publish(this.socketChannelName,JSON.stringify({type:y.CLOSE}))}saveSocketInfo(){return new Promise(((e,t)=>this.redisClient.publish(this.socketChannelName,JSON.stringify({type:y.SAVE,data:this.socketInfo}),(n=>n?t(n):e))))}}class ExpressSocket extends f.AbstractServerSocket{constructor(e,t,n){super(t),this.socket=e,this.socketInfo=t,this.infoSaver=n}saveSocketInfo(){return r(this,void 0,void 0,(function*(){yield this.infoSaver(this.socketInfo)}))}physicSend(e){this.socket.send(JSON.stringify(e))}physicClose(){this.socket.close()}}let v=class LocalSocketManager extends h.AbstractServerSocketManager{constructor(e,t,n,i,o){super(e,n,t,o,i),this.authenticationRequired=e,this.redisClient=t,this.logger=n,this.authProvider=i,this.connectionHandler=o,this.allSockets=[],this.subClient=this.redisClient.duplicate(),this.channelSubClient=this.redisClient.duplicate(),this.sendClient=this.redisClient.duplicate(),this.channelSubClient.on("message",((e,t)=>{this.logger.debug("channelSubClient",e,t,typeof t);e.substring(this.getUniqueChannelPrefix().length);const n=JSON.parse(t);n.type===a.MessageType.PLAIN&&this.allSockets.forEach((e=>{e.send(n.data.message,n.data.channel)}))})),this.subClient.on("message",((e,t)=>{this.logger.debug("Receiving message from remote socket channel",e,t);const n=e.substring(this.getSocketChannelKeyPrefix().length),i=this.allSockets.find((e=>e.getId()===n));if(i){const e=JSON.parse(t);switch(e.type){case y.SEND:i.physicSend(e.data);break;case y.SAVE:i.socketInfo.channels=e.data,i.saveSocketInfo();break;case y.CLOSE:i.disconnect();break;default:this.logger.debug("Invalid remote command",e)}}}))}init(){return r(this,void 0,void 0,(function*(){}))}exit(){this.redisClient.quit(),this.subClient.quit(),this.sendClient.quit(),this.channelSubClient.quit()}getSocketChannelKeyPrefix(){return"SOCKET_CHANNEL:"}getSocketInfoHashKey(){return"__SOCKET_INFO__"}getSocketChannelKey(e){return`${this.getSocketChannelKeyPrefix()}${e}`}createCustomChannel(e){return r(this,void 0,void 0,(function*(){}))}broadcastToChannel(e,t){return r(this,void 0,void 0,(function*(){const n=this.formatBroadcastData(e,t);return new Promise(((t,i)=>this.redisClient.publish(this.getUniqueChannelName(e),JSON.stringify(n),(e=>e?i(e):t()))))}))}addSocketToChannel(e,t){const n=Object.create(null,{addSocketToChannel:{get:()=>super.addSocketToChannel}});return r(this,void 0,void 0,(function*(){yield n.addSocketToChannel.call(this,e,t),yield Promise.all(t.map((e=>new Promise(((t,n)=>this.channelSubClient.subscribe(this.getUniqueChannelName(e.name),(e=>e?n(e):t())))))))}))}removeSocketFromChannel(e,t){const n=Object.create(null,{removeSocketFromChannel:{get:()=>super.removeSocketFromChannel}});return r(this,void 0,void 0,(function*(){yield n.removeSocketFromChannel.call(this,e,t),yield Promise.all(t.map((e=>new Promise(((t,n)=>this.channelSubClient.unsubscribe(this.getUniqueChannelName(e),(e=>e?n(e):t())))))))}))}addSocket(e,{socket:t}){return r(this,void 0,void 0,(function*(){const n=new ExpressSocket(t,e,(e=>new Promise(((t,n)=>this.redisClient.hset(this.getSocketInfoHashKey(),e.id,JSON.stringify(e),(e=>e?n(e):t())))))),i=this.getSocketChannelKey(e.id);return this.subClient.subscribe(i),this.allSockets.push(n),n}))}removeSocket(e){return r(this,void 0,void 0,(function*(){this.redisClient.hdel(this.getSocketInfoHashKey(),e),this.allSockets=this.allSockets.filter((t=>t.getId()!==e))}))}getById(e){return r(this,void 0,void 0,(function*(){let t=this.allSockets.find((t=>t.getId()===e));if(!t){const n=yield new Promise((t=>this.redisClient.hget(this.getSocketInfoHashKey(),e,((e,n)=>t(n?JSON.parse(n):void 0)))));n&&(t=new RedisSocket(this.getSocketChannelKey(e),this.sendClient,n))}return t}))}getSocketsByChannel(e){return r(this,void 0,void 0,(function*(){const t=yield this.getSocketIdsOfChannel(e);return(yield Promise.all(t.map((e=>this.getById(e))))).filter((e=>!!e))}))}configure(e){if(!e)return;this.logger.debug("Local socket manager configure");new d.default.Server({server:e}).on("connection",((e,t)=>{const n=t.headers["sec-websocket-key"],i=(0,c.default)({url:t.url}),o=l.default.parse(decodeURIComponent(i.search||""));this.handle({method:a.SocketMethod.CONNECT,socketId:n,data:{auth:o.auth,socket:e}}).catch((t=>{e.close(1e3,t.name)})),e.onmessage=e=>{this.handle({method:a.SocketMethod.MESSAGE,socketId:n,data:e.data}).catch((e=>{this.logger.error(e)}))},e.onclose=()=>{this.handle({method:a.SocketMethod.DISCONNECT,socketId:n}).catch((e=>{this.logger.error(e)}))}}))}};v=i([(0,a.Initable)(),o("design:paramtypes",[Boolean,u.RedisClient,a.AbstractLogger,g.AbstractHttpAuthorizationProvider,p.AbstractSocketConnectionHandler])],v),t.LocalSocketManager=v},function(e,t){e.exports=require("ws")},function(e,t,n){"use strict";var i=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},o=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},r=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))},s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.AwsSocketManager=void 0;const a=n(0),d=n(30),c=s(n(54)),l=n(2),u=n(5),h=n(31),p=n(1),f=n(16);class ApiGatewaySocket extends h.AbstractServerSocket{constructor(e,t,n,i,o,r){super(n),this.socketManager=e,this.logger=t,this.socketInfo=n,this.apiGateway=i,this.socketNamespace=o,this.redisClient=r}saveSocketInfo(){return r(this,void 0,void 0,(function*(){return new Promise(((e,t)=>this.redisClient.hset(this.socketNamespace,this.socketInfo.id,JSON.stringify(this.socketInfo),(n=>n?t(n):e()))))}))}physicSend(e){this.socketManager.physicSend(this.getId(),e).catch((e=>this.logger.debug("Send error",e)))}physicClose(){this.apiGateway.deleteConnection({ConnectionId:this.getId()}).promise().catch((e=>this.logger.error(e)))}serialize(){return JSON.stringify(this.socketInfo)}}let g=class AwsSocketManager extends u.AbstractServerSocketManager{constructor(e,t,n,i,o,r,s,a){super(e,a,i,o,s),this.authenticationRequired=e,this.region=t,this.socketDomainUrl=n,this.redisClient=i,this.connectionHandler=o,this.httpRequestHandler=r,this.authorizationProvider=s,this.logger=a,this.apiGatewayManagement=new c.default.ApiGatewayManagementApi({region:t,apiVersion:"2018-11-29",endpoint:n})}init(){return r(this,void 0,void 0,(function*(){}))}exit(){this.redisClient.quit()}getSocketInfoHashKey(){return"__SOCKET_INFO__"}physicSend(e,t){return r(this,void 0,void 0,(function*(){try{yield this.apiGatewayManagement.postToConnection({ConnectionId:e,Data:JSON.stringify(t)}).promise(),this.logger.debug(`Socket ${e} send OK`,t)}catch(t){throw this.logger.debug(`Socket ${e} post error`,t),410===t.statusCode&&(this.logger.debug(`Stale socket ${e}`),this.logger.debug(`Disconnecting ${e}`),this.logger.debug(`Removing socket ${e}`),yield this.removeSocket(e),this.logger.debug(`Socket removed ${e}`)),t}}))}configure(e){this.logger.debug("Aws socket manager configure")}createCustomChannel(e){return r(this,void 0,void 0,(function*(){}))}getSocketsByChannel(e){return r(this,void 0,void 0,(function*(){const t=yield this.getSocketIdsOfChannel(e);return(yield new Promise(((e,n)=>this.redisClient.hmget(this.getSocketInfoHashKey(),t,((t,i)=>t?n(t):e(i)))))).filter((e=>!!e)).map((e=>this.getSocketBySerialized(e)))}))}broadcastToChannel(e,t){return r(this,void 0,void 0,(function*(){const n=yield this.getSocketIdsOfChannel(e),i=this.formatBroadcastData(e,t);yield Promise.all(n.map((e=>this.physicSend(e,i))))}))}addSocket(e,t){return r(this,void 0,void 0,(function*(){const t=new ApiGatewaySocket(this,this.logger,e,this.apiGatewayManagement,this.getSocketInfoHashKey(),this.redisClient);return t.saveSocketInfo(),t}))}removeSocket(e){return new Promise(((t,n)=>this.redisClient.hdel(this.getSocketInfoHashKey(),e,(e=>e?n(e):t()))))}getSocketBySerialized(e){return new ApiGatewaySocket(this,this.logger,JSON.parse(e),this.apiGatewayManagement,this.getSocketInfoHashKey(),this.redisClient)}getById(e){return r(this,void 0,void 0,(function*(){const t=yield new Promise(((t,n)=>this.redisClient.hget(this.getSocketInfoHashKey(),e,((e,i)=>e?n(e):t(i)))));if(!t)throw a.ErrorBuilder.error(a.Errors.NOT_FOUND,"Cannot find socket with id: "+e);return this.logger.debug("Serialized aws socket",t),this.getSocketBySerialized(t)}))}};g=i([(0,a.Initable)(),o("design:paramtypes",[Boolean,String,String,d.RedisClient,f.AbstractSocketConnectionHandler,l.AbstractHttpRequestHandler,p.AbstractHttpAuthorizationProvider,a.AbstractLogger])],g),t.AwsSocketManager=g},function(e,t){e.exports=require("aws-sdk")},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},function(e,t,n){"use strict";var i=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},o=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},r=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.FileUploadHandler=void 0;const s=n(0),a=n(32),d=n(14);let c=class FileUploadHandler extends d.AbstractFileUploadHandler{constructor(e){super(),this.fileService=e}moveFile(e,t){return r(this,void 0,void 0,(function*(){yield this.fileService.moveObject(e,t)}))}removeFile(e){return r(this,void 0,void 0,(function*(){yield this.fileService.removeObject(e)}))}resolvePublicUrl(e){return r(this,void 0,void 0,(function*(){return this.fileService.getAccessUrl(e,!0)}))}resolvePrivateUrl(e){return r(this,void 0,void 0,(function*(){return this.fileService.getAccessUrl(e,!1)}))}};c=i([(0,s.Injectable)(),o("design:paramtypes",[a.AbstractFileService])],c),t.FileUploadHandler=c},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},function(e,t,n){"use strict";var i,o=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},r=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},s=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.FileLogMedium=void 0;const d=a(n(33)),c=a(n(34)),l=n(0);let u=i=class FileLogMedium{constructor(e){const t=e.separated?i.levels.map((t=>c.default.join(e.destination,t+".log"))):[e.destination];this.destination=t.map((e=>(d.default.existsSync(c.default.dirname(e))||d.default.mkdirSync(c.default.dirname(e),{recursive:!0}),d.default.openSync(e,"a")))),this.separated=!!e.separated}init(){return s(this,void 0,void 0,(function*(){}))}exit(){this.destination.forEach((e=>d.default.closeSync(e)))}write(e,t){const n=this.separated?this.destination[i.levels.indexOf(e)]:0;d.default.appendFileSync(n,t)}};u.levels=Object.values(l.LogLevel),u=i=o([(0,l.Initable)(),r("design:paramtypes",[Object])],u),t.FileLogMedium=u},function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.ClaireServer=void 0;const o=n(0),r=n(10),s=n(6);class ClaireServer extends o.ClaireApp{constructor(e,t,n){super(),this.logger=e,this.httpRequestHandler=t,this.socketManager=n,this.booted=!1}init(){return i(this,void 0,void 0,(function*(){if(this.booted)return;const e=[];if(this.httpRequestHandler){const t=yield this.httpRequestHandler.getMountedEndpointInfo();e.push(...t)}if(this.socketManager){const t=yield this.socketManager.getMountedEndpointInfo();e.push(...t)}for(const t of e)this.logger.info(`Mounting: ${(0,s.getEndpointId)(t.endpoint)}`);(0,o.getGlobalStore)().mountedEndpointInfo=e,this.logger.debug("Claire server initing"),this.logger.debug("Setting up exception handlers"),process.on("SIGTERM",(()=>(this.logger.warn("SIGTERM interrupt signal"),this.stop(r.ExitCode.SIGTERM_INTERUPTION)))),process.on("SIGINT",(()=>(this.logger.warn("SIGINT interrupt signal"),this.stop(r.ExitCode.SIGTERM_INTERUPTION)))),process.on("uncaughtException",(e=>{this.logger.error("uncaughtException",e.name,e.stack)})),process.on("unhandledRejection",(e=>{this.logger.error("unhandledRejection",e.name,e.stack)})),this.booted=!0}))}exit(){super.exit()}stop(e){this.logger.debug("Server is shutting down"),this.exit(),process.exit(e)}}t.ClaireServer=ClaireServer},function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ExpressWrapper=void 0;const r=n(0),s=o(n(61)),a=o(n(62)),d=o(n(63)),c=o(n(64)),l=n(5),u=n(2);t.ExpressWrapper=class ExpressWrapper{constructor(e,t){this.injector=(0,r.getServiceProvider)().getInjector(),this.server=e,this.config=t,this.logger=this.injector.resolve(r.AbstractLogger),this.socketManager=this.injector.resolveOptional(l.AbstractServerSocketManager),this.httpRequestHandler=this.injector.resolveOptional(u.AbstractHttpRequestHandler)}close(){var e;null===(e=this.httpServer)||void 0===e||e.close(),this.server.exit()}listen(e){var t,n;return i(this,void 0,void 0,(function*(){yield this.server.init(),yield this.injector.initInstances();const o=(0,s.default)(),l=a.default.createServer(o);return null===(t=this.socketManager)||void 0===t||t.configure(l),o.use((0,d.default)()),o.use(s.default.raw({limit:1024*((null===(n=this.config)||void 0===n?void 0:n.maxBodySizeKB)||4096)})),o.use((0,c.default)()),o.use(((e,t,n)=>{e.files&&(e.body||(e.body={}),Object.keys(e.files).forEach((t=>{e.body[t]=e.files[t]}))),n()})),o.use(s.default.urlencoded({extended:!1})),o.use(s.default.json()),o.all("*",((e,t)=>{(()=>i(this,void 0,void 0,(function*(){if(!!e.headers["x-amzn-apigateway-api-id"]){if(!this.socketManager)throw r.ErrorBuilder.systemError("Socket manager not found");const n={socketId:e.body.connectionId,data:e.body.data,method:e.body.type.toLowerCase()};yield this.socketManager.handle(n),t.status(200).send()}else{if(!this.httpRequestHandler)throw r.ErrorBuilder.systemError("Http request handler not found");const n={fullPath:e.url,method:e.method.toLowerCase(),headers:e.headers,body:e.body},i=yield this.httpRequestHandler.handle(n);i.headers&&Object.keys(i.headers).forEach((e=>{t.set(e,i.headers[e])})),t.status(i.code).send(i.value)}})))().catch((e=>{this.logger.error(e),t.status(400).json({name:e.name,message:e.message})}))})),new Promise(((t,n)=>{this.httpServer=l.listen(e,t).on("error",n)}))}))}}},function(e,t){e.exports=require("express")},function(e,t){e.exports=require("http")},function(e,t){e.exports=require("cors")},function(e,t){e.exports=require("express-fileupload")},function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.LambdaWrapper=void 0;const o=n(0),r=n(2),s=n(5),a=n(11),toApiGatewayFormat=(e,t)=>({statusCode:e,body:t&&JSON.stringify(t),headers:{"Access-Control-Allow-Headers":"*","Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"*","Content-Type":"application/json"}});t.LambdaWrapper=class LambdaWrapper{constructor(e,t){this.server=e,this.requestMapper=t,this.handler=this.handler.bind(this),this.injector=(0,o.getServiceProvider)().getInjector(),this.socketManager=this.injector.resolveOptional(s.AbstractServerSocketManager),this.httpRequestHandler=this.injector.resolveOptional(r.AbstractHttpRequestHandler)}handler(e){var t;return i(this,void 0,void 0,(function*(){yield this.server.init(),yield this.injector.initInstances(),null===(t=this.socketManager)||void 0===t||t.configure();const n=this.requestMapper(e);if(!n)return toApiGatewayFormat(400,"Cannot resolve event");if(n.method===o.HttpMethod.OPTIONS)return toApiGatewayFormat(200);try{if(Object.values(o.HttpMethod).includes(n.method)){if(!this.httpRequestHandler)throw o.ErrorBuilder.error(a.Errors.SYSTEM_ERROR,"Http request handler not found");const e={fullPath:n.rawPath,method:n.method,headers:n.headers,body:n.body},t=yield this.httpRequestHandler.handle(e);return toApiGatewayFormat(t.code,t.value)}if(!Object.values(o.SocketMethod).includes(n.method))throw o.ErrorBuilder.error(a.Errors.HTTP_REQUEST_ERROR,"Not allow request method: "+n.method);{if(!this.socketManager)throw o.ErrorBuilder.error(a.Errors.SYSTEM_ERROR,"Socket manager not found");const e={socketId:n.rawPath,method:n.method,data:n.body};yield this.socketManager.handle(e)}return toApiGatewayFormat(200)}catch(e){return toApiGatewayFormat(400,{name:e.name,message:e.message})}}))}}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractService=void 0;const o=n(3);t.AbstractService=class AbstractService{constructor(e){this.databaseAdapter=e}createTransaction(){return this.databaseAdapter.createTransaction()}getCurrentTransaction(){return i(this,void 0,void 0,(function*(){return(0,o.getTransactionFromContext)(this)}))}}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractCacheService=void 0;t.AbstractCacheService=class AbstractCacheService{}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t._is=t._join=t._max=t._min=t._avg=t._sum=t._count=void 0;t._count=(e,t)=>({fn:"count",field:e,args:t});t._sum=e=>({fn:"sum",field:e});t._avg=e=>({fn:"avg",field:e});t._min=e=>({fn:"min",field:e});t._max=e=>({fn:"max",field:e});t._join=(e,t)=>({fn:"join",field:e,args:t});t._is=e=>({fn:"is",field:e})},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},function(e,t,n){"use strict";var i=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},o=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},r=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSqlDatabaseAdapter=void 0;const s=n(0),a=n(18),d=n(25),c=n(35),l=n(75),u=n(17),h=n(3),getModelId=e=>{const t=(0,s.getObjectMetadata)(e);if(!t)throw s.ErrorBuilder.systemError(`Metadata for ${e.name} not found, check @Model decorator`);return t.id},p=["_and","_or"],convertOp=e=>[a.Op.and,a.Op.or,a.Op.eq,a.Op.ne,a.Op.gt,a.Op.lt,a.Op.gte,a.Op.lte,a.Op.regexp,a.Op.like,a.Op.in][["_and","_or","_eq","_neq","_gt","_lt","_gte","_lte","_regex","_sub","_in"].indexOf(e)],safetifyColumn=(e,t)=>{const n=t===u.SqlProvider.MYSQL?"`":'"';return e.split(".").map((e=>`${n}${e}${n}`)).join(".")},getAggregatorColumn=(e,t)=>{const n=safetifyColumn(e.field,t);switch(e.fn){case"count":return`${!0===e.args?`COUNT(DISTINCT(${n}))`:`COUNT(${n})`}${t===u.SqlProvider.POSTGRES?"::int":""}`;case"sum":return`SUM(${n})`;case"avg":return`AVG(${n})`;case"min":return`MIN(${n})`;case"max":return`MAX(${n})`;case"join":return t===u.SqlProvider.POSTGRES?`string_agg(${n}, '${e.args}')`:`GROUP_CONCAT(${n} SEPARATOR '${e.args}')`;case"is":return n;default:throw s.ErrorBuilder.systemError(`Not supported agg function: ${e.fn}`)}};class Joiner{constructor(e){this.adapter=e,this.joinInfo=[],this.columnId=0}join(e,t,n,i){return this.joinInfo.push({rightModel:e,leftField:t,rightField:n,joinMode:i||"inner"}),this}where(e){return this.queryCondition=e,this}groupBy(e){return this.groupByFields=e,this}having(e){return this.havingCondition=e,this}getExecuteCondition(){const e=[],t=this.convertHavingCondition(this.havingCondition||{},e);return{conditions:{where:this.adapter.getQueryObjectFromQueryConditions(this.queryCondition,!0),transaction:this.adapter.transaction,include:this.joinInfo.map((e=>{const t=(0,s.getTableName)(e.rightModel);return{attributes:[],model:this.adapter.modelConnections[t].connection,duplicating:!1,required:"inner"===e.joinMode,on:{[`$${e.leftField}$`]:{[convertOp("_eq")]:a.Sequelize.col(e.rightField)}}}})),group:this.groupByFields,attributes:this.adapter.sqlProvider===u.SqlProvider.POSTGRES?[]:e.map((e=>[a.Sequelize.literal(e.sequelizeColumn),e.columnId])),having:t,raw:!0},collector:e}}countWithCondition(e){var t;return r(this,void 0,void 0,(function*(){e.offset=0,e.limit=this.adapter.sqlProvider===u.SqlProvider.POSTGRES?1:0,e.attributes=[...this.adapter.sqlProvider===u.SqlProvider.MYSQL&&e.attributes||[],[this.adapter.sqlProvider===u.SqlProvider.POSTGRES?a.Sequelize.literal("(COUNT(*) OVER ())::int"):a.Sequelize.literal("COUNT(*)"),"count"]];const n=this.adapter.sqlProvider===u.SqlProvider.POSTGRES?yield this.adapter.getCurrentConnection().findAll(e):yield this.adapter.getCurrentConnection().count(e);return(null===(t=n[0])||void 0===t?void 0:t.count)||0}))}count(){return r(this,void 0,void 0,(function*(){const{conditions:e}=this.getExecuteCondition();return this.countWithCondition(e)}))}rows(e,t){return r(this,void 0,void 0,(function*(){const{conditions:n,collector:i}=this.getExecuteCondition();n.attributes=[...n.attributes||[],...Object.keys(e).map((t=>[a.Sequelize.literal(getAggregatorColumn(e[t],this.adapter.sqlProvider)),t]))],n.limit=null==t?void 0:t.limit,n.offset=(null==t?void 0:t.limit)&&t.limit*((t.page||1)-1);const o=yield this.adapter.getCurrentConnection().findAll(n);return{total:yield this.countWithCondition(Object.assign(Object.assign({},n),{attributes:i.map((e=>[a.Sequelize.literal(e.sequelizeColumn),e.columnId]))})),records:o}}))}convertHavingOperation(e,t){const n=getAggregatorColumn(t[0],this.adapter.sqlProvider);return{columnId:"col__"+this.columnId++,sequelizeColumn:n,sequelizeOps:{[convertOp(e)]:t[1]}}}convertHavingCondition(e,t){if(!e)return{};const n=Object.keys(e);if(!n.length)return{};const i=n.map((n=>{if(p.includes(n))return{[convertOp(n)]:e[n].map((e=>this.convertHavingCondition(e,t)))};{const i=this.convertHavingOperation(n,e[n]);return t.push(i),this.adapter.sqlProvider===u.SqlProvider.POSTGRES?a.Sequelize.where(a.Sequelize.literal(i.sequelizeColumn),i.sequelizeOps):{[i.columnId]:i.sequelizeOps}}}));return i.length>1?{[convertOp("_and")]:i}:i[0]}}class ModelAdapter extends l.AbstractQuery{constructor(e){super(e.model),this.dbConnection=e.dbConnection,this.modelConnections=e.modelConnections,this.transaction=e.transaction,this.sqlProvider=e.sqlProvider,this.logger=null==e?void 0:e.logger}getCurrentConnection(){const e=(0,s.getObjectMetadata)(this.model).id;return this.modelConnections[e].connection}resolveNestedIncludes(e){return e&&e.map((e=>({model:this.modelConnections[e.modelId].connection,where:this.getQueryObjectFromQueryConditions(e.queries)})))}join(e,t,n,i){const o=new Joiner(this);return o.join(e,t,n,i),o}count(e,t,n){return r(this,void 0,void 0,(function*(){const i={where:this.getQueryObjectFromQueryConditions(e),transaction:this.transaction,include:this.resolveNestedIncludes(n)};return(null==t?void 0:t.distinct)&&Object.assign(i,{distinct:!0,col:t.distinct}),yield this.getCurrentConnection().count(i)}))}getById(e,t){return this.getOne({_eq:{id:e}},t)}getByIds(e,t){return this.getRecords({_in:{id:e}},t)}getOne(e,t){return r(this,void 0,void 0,(function*(){const n=yield this.getMany(e,{limit:1});return n.records.length?this.convertToLogicObjects(n.records,null==t?void 0:t.projection)[0]:void 0}))}getRecords(e,t,n){return r(this,void 0,void 0,(function*(){return(yield this.getMany(e,t,n)).records}))}getMany(e,t,n){return r(this,void 0,void 0,(function*(){let i={where:this.getQueryObjectFromQueryConditions(e),transaction:this.transaction,include:this.resolveNestedIncludes(n)};if((null==t?void 0:t.order)&&Object.assign(i,{order:t.order}),(null==t?void 0:t.projection)&&Object.assign(i,{attributes:t.projection}),(null==t?void 0:t.limit)&&(i=Object.assign(i,{limit:t.limit}),t.page&&(i=Object.assign(i,{offset:t.limit*(t.page-1)}))),1!==(null==t?void 0:t.limit)||t.page){if(null==t?void 0:t.limit){const{count:e,rows:n}=yield this.getCurrentConnection().findAndCountAll(i);return{total:e,records:this.convertToLogicObjects(n,null==t?void 0:t.projection)}}{const e=yield this.getCurrentConnection().findAll(i);return{total:0,records:this.convertToLogicObjects(e,null==t?void 0:t.projection)}}}{const e=yield this.getCurrentConnection().findOne(i);return{total:0,records:e?this.convertToLogicObjects([e],t.projection):[]}}}))}createOne(e){return r(this,void 0,void 0,(function*(){return(yield this.createMany([e]))[0]}))}createMany(e){return r(this,void 0,void 0,(function*(){let t=yield this.getCurrentConnection().bulkCreate(this.convertToDataObjects(e),{transaction:this.transaction});return this.convertToLogicObjects(t)}))}updateOne(e){return r(this,void 0,void 0,(function*(){return yield this.getCurrentConnection().update(this.convertToDataObjects([e],!0)[0],{where:this.getQueryObjectFromQueryConditions({_eq:{id:e.id}}),transaction:this.transaction}),e}))}updateMany(e,t,n){return r(this,void 0,void 0,(function*(){if(n){const n=yield this.getRecords(e,{projection:["id"]});if(!n.length)return[];const i=n.map((e=>e.id));return yield this.getCurrentConnection().update(this.convertToDataObjects([t],!0)[0],{where:this.getQueryObjectFromQueryConditions({_in:{id:i}}),transaction:this.transaction}),i}return yield this.getCurrentConnection().update(this.convertToDataObjects([t],!0)[0],{where:this.getQueryObjectFromQueryConditions(e),transaction:this.transaction}),[]}))}deleteOne(e){return r(this,void 0,void 0,(function*(){return yield this.deleteMany({_eq:{id:e.id}}),e}))}deleteMany(e,t){return r(this,void 0,void 0,(function*(){if(t){const t=yield this.getMany(e);if(!t.records.length)return[];const n=t.records.map((e=>e.id));return yield this.getCurrentConnection().destroy({where:this.getQueryObjectFromQueryConditions({_in:{id:n}}),transaction:this.transaction}),t.records}return yield this.getCurrentConnection().destroy({where:this.getQueryObjectFromQueryConditions(e),transaction:this.transaction}),[]}))}rawQuery(...e){return r(this,void 0,void 0,(function*(){const t=e[0],n=e[1]||{};if("string"!=typeof t)throw s.ErrorBuilder.error(s.Errors.QUERY_ERROR,"First argument of raw sql expected to be string");return this.dbConnection.query(t,Object.assign({transaction:this.transaction,raw:!0},n))}))}mapToSequelizeOperator(e,t,n,i,o){const r=o?a.Sequelize.literal(safetifyColumn(n,e)):a.Sequelize.col(n);switch(t){case"_sub":switch(this.sqlProvider){case u.SqlProvider.MYSQL:return a.Sequelize.where(r,{[a.Op.like]:a.Sequelize.literal(`${this.dbConnection.escape(`%${i}%`)} COLLATE utf8mb4_0900_as_cs`)});default:return a.Sequelize.where(r,{[a.Op.like]:`%${i}%`})}case"_isub":switch(this.sqlProvider){case u.SqlProvider.POSTGRES:return a.Sequelize.where(r,{[a.Op.iLike]:`%${i}%`});case u.SqlProvider.MYSQL:return a.Sequelize.where(r,{[a.Op.like]:a.Sequelize.literal(`${this.dbConnection.escape(`%${i}%`)} COLLATE utf8mb4_0900_as_ci`)})}case"_usub":switch(this.sqlProvider){case u.SqlProvider.POSTGRES:return a.Sequelize.where(a.Sequelize.fn("unaccent",r),{[a.Op.like]:a.Sequelize.literal(`unaccent(${this.dbConnection.escape(`%${i}%`)})`)});case u.SqlProvider.MYSQL:return a.Sequelize.where(a.Sequelize.fn("unaccent",r),{[a.Op.like]:a.Sequelize.literal(`unaccent(${this.dbConnection.escape(`%${i}%`)}) COLLATE utf8mb4_0900_as_cs`)})}case"_iusub":switch(this.sqlProvider){case u.SqlProvider.POSTGRES:return a.Sequelize.where(a.Sequelize.fn("unaccent",r),{[a.Op.iLike]:a.Sequelize.literal(`unaccent(${this.dbConnection.escape(`%${i}%`)})`)});case u.SqlProvider.MYSQL:return a.Sequelize.where(r,{[a.Op.like]:a.Sequelize.literal(`${this.dbConnection.escape(`%${i}%`)} COLLATE utf8mb4_0900_ai_ci`)})}case"_in":const e=i||[],n=e.filter((e=>null!==e));return n.length<e.length?a.Sequelize.or(a.Sequelize.where(r,{[a.Op.eq]:null}),...n.length?[a.Sequelize.where(r,{[a.Op.in]:n})]:[]):a.Sequelize.where(r,{[a.Op.in]:e});default:return a.Sequelize.where(r,{[convertOp(t)]:i})}}getQueryObjectFromQueryConditions(e,t){if(!e)return{};const n=Object.keys(e);if(!n.length)return{};const i=n.map((n=>p.includes(n)?{[convertOp(n)]:e[n].map((e=>this.getQueryObjectFromQueryConditions(e)))}:{[convertOp("_and")]:Object.keys(e[n]).map((i=>this.mapToSequelizeOperator(this.sqlProvider,n,i,e[n][i],t)))}));return i.length>1?{[convertOp("_and")]:i}:i[0]}}class TransactionAdapter{constructor(e){this.modelAdapters={},this.transaction=e.transaction,this.dbConnection=e.dbConnection,this.logger=e.logger,this.modelConnections=e.modelConnections,this.sqlProvider=e.sqlProvider,this.transactionState=d.TransactionState.EXECUTING}use(e){const t=getModelId(e);let n=this.modelAdapters[t];return n||(this.modelAdapters,n=new ModelAdapter({model:e,dbConnection:this.dbConnection,modelConnections:this.modelConnections,logger:this.logger,transaction:this.transaction,sqlProvider:this.sqlProvider}),this.modelAdapters[t]=n),n}commit(){return r(this,void 0,void 0,(function*(){return this.transactionState=d.TransactionState.COMMITTED,this.transaction.commit()}))}rollback(){return r(this,void 0,void 0,(function*(){return this.transactionState=d.TransactionState.ROLLED_BACK,this.transaction.rollback()}))}getState(){return this.transactionState}}let f=class DefaultSqlDatabaseAdapter extends c.AbstractDatabaseAdapter{constructor(e,t,n){super(),this.logger=n,this.injector=(0,s.getServiceProvider)().getInjector(),this.modelAdapters={},this.sqlProvider=e,this.dbConnection=new a.Sequelize(`${e}://${t}`,{dialect:this.sqlProvider,logging:e=>this.logger.debug(e),define:{timestamps:!1}})}createTransaction(){return r(this,void 0,void 0,(function*(){let e=yield this.dbConnection.transaction();return new TransactionAdapter({transaction:e,dbConnection:this.dbConnection,logger:this.logger,modelConnections:this.modelConnections,sqlProvider:this.sqlProvider})}))}init(){const e=Object.create(null,{init:{get:()=>super.init}});var t,n,i,o;return r(this,void 0,void 0,(function*(){yield e.init.call(this),yield this.injector.initInstances(),null===(t=this.logger)||void 0===t||t.debug("Connecting to database"),yield this.dbConnection.authenticate(),null===(n=this.logger)||void 0===n||n.debug("Generating in-memory schema");for(const e of this.modelMetadata){const t=this.generateSchemaObject(e);this.modelConnections[e.id].connection=t}for(const e of this.modelMetadata){const t=this.modelConnections[e.id].connection,n=e.fields.filter((e=>e.fk));for(const o of n){const n=null===(i=o.fk)||void 0===i?void 0:i.dtoId;if(!n)throw s.ErrorBuilder.systemError(`FK model id not resolved for ${e.id}:${o.name}`);const r=this.modelConnections[n].connection;t.belongsTo(r,{foreignKey:o.name}),r.hasMany(t,{foreignKey:o.name})}}null===(o=this.logger)||void 0===o||o.debug("Database adapter init succeeded")}))}exit(){var e;return null===(e=this.logger)||void 0===e||e.debug("Closing connection to database"),this.dbConnection.close(),0}use(e){const t=getModelId(e);let n=this.modelAdapters[t];return n||(n=new ModelAdapter({model:e,dbConnection:this.dbConnection,modelConnections:this.modelConnections,logger:this.logger,sqlProvider:this.sqlProvider}),this.modelAdapters[t]=n),n}generateSchemaObject(e){let t={};const n=(0,h.getDirectFields)(e);for(const e of n){switch(t[e.name]={},e.dataType){case s.DataType.NUMBER:e.floating?t[e.name].type=a.DataTypes.FLOAT:e.isBigInt?t[e.name].type=a.DataTypes.BIGINT:t[e.name].type=a.DataTypes.INTEGER;break;case s.DataType.STRING:e.textLength?t[e.name].type=a.DataTypes.STRING(e.textLength):t[e.name].type=a.DataTypes.STRING;break;case s.DataType.BOOLEAN:t[e.name].type=a.DataTypes.BOOLEAN;break;case s.DataType.ARRAY:case s.DataType.OBJECT:t[e.name].type=a.DataTypes.TEXT}e.pk&&(t[e.name].primaryKey=!0,e.pk.isAutoIncrement&&(t[e.name].autoIncrement=!0)),void 0!==e.defaultValue&&(t[e.name].defaultValue=e.defaultValue),t[e.name].allowNull=!e.isRequired}return this.dbConnection.define(e.id,t,{tableName:e.id,freezeTableName:!0,name:{singular:e.id,plural:e.id}})}};f=i([(0,s.Initable)(),(0,s.Injectable)(),o("design:paramtypes",[String,String,s.AbstractLogger])],f),t.DefaultSqlDatabaseAdapter=f},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractQuery=void 0;const i=n(0);t.AbstractQuery=class AbstractQuery{constructor(e){const t=(0,i.getObjectMetadata)(e);this.model=(0,i.getModelById)(t.id)||e,this.metadata=(0,i.getObjectMetadata)(this.model)}convertToLogicObjects(e,t){return e.map((e=>{let n=new this.model;return this.metadata.fields.filter((e=>!t||t.includes(e.name))).forEach((t=>{const i=e[t.name];void 0!==i&&(t.isBigInt?n[t.name]=Number(i):t.vectorProps?n[t.name]=JSON.parse(i):n[t.name]=i)})),n}))}convertToDataObjects(e,t){const n=Date.now();return e.map((e=>{let i=new this.model;for(const o of this.metadata.fields){let r=e[o.name];o.vectorProps?r=JSON.stringify(r):(o.modificationTimestamp||o.creationTimestamp&&!t)&&(r=n),i[o.name]=r}return i}))}}},function(e,t,n){"use strict";var i,o=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},r=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},s=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSqlDatabaseMigrator=void 0;const d=a(n(34)),c=a(n(33)),l=n(77),u=n(0),h=n(18),p=n(17),f=n(3),g=n(36),uniqueGroupComparator=(e,t)=>!e.groupName&&!t.groupName&&e.fieldNames[0]===t.fieldNames[0]||!!e.groupName&&e.groupName===t.groupName;let y=i=class DefaultSqlDatabaseMigrator extends g.AbstractDatabaseMigrator{constructor(e,t,n,i){super(),this.cliPath=e,this.sqlProvider=t,this.connectionString=n,this.logger=i,this.injector=(0,u.getServiceProvider)().getInjector(),this.cliPath=e,this.databaseURL=`${t}://${n}`,this.modelMetadata=((0,u.getGlobalStore)().models||[]).map((e=>(0,u.getObjectMetadata)(e)))}init(){return s(this,void 0,void 0,(function*(){yield this.injector.initInstances()}))}exit(){}getUniqueConstraintGroups(e){const t=[],n=(0,f.getDirectFields)(e).filter((e=>!!e.unique));for(const e of n)if(e.unique.groupName){let n=t.find((t=>t.groupName===e.unique.groupName));n||(n={groupName:e.unique.groupName,fieldNames:[]},t.push(n)),n.fieldNames.push(e.name)}else t.push({fieldNames:[e.name]});return t}generateFieldPropertiesQuery(e){let t="{";if(e.pk&&(t+="primaryKey:true,",e.pk.isAutoIncrement&&(t+="autoIncrement:true,")),void 0!==e.defaultValue&&(t+=`defaultValue:${JSON.stringify(e.defaultValue)},`),t+=`allowNull:${e.isRequired?"false":"true"},`,void 0!==e.dataType)switch(e.dataType){case u.DataType.STRING:e.textLength?t+=`type:Sequelize.STRING(${e.textLength}),`:t+="type:Sequelize.TEXT,";break;case u.DataType.NUMBER:e.floating?t+="type:Sequelize.FLOAT,":e.isBigInt?t+="type:Sequelize.BIGINT,":t+="type:Sequelize.INTEGER,";break;case u.DataType.BOOLEAN:t+="type:Sequelize.BOOLEAN,";break;case u.DataType.ARRAY:case u.DataType.OBJECT:t+="type:Sequelize.TEXT,"}return t+="}",t}getUniqueConstraintUpDown(e,t){const n=`${e}_${t.groupName||t.fieldNames[0]}_un`;return[`queryInterface.addConstraint("${e}",{fields:${JSON.stringify(t.fieldNames)},type:"unique",name:"${n}","transaction":t})`,`queryInterface.removeConstraint("${e}","${n}",{"transaction":t})`]}getSqlCascadeAction(e){switch(e){case"delete":return"CASCADE";case"restrict":return"RESTRICT";case"nullify":return"SET NULL";default:return"RESTRICT"}}getForeignKeyConstraintUpDown(e,t,n){var i,o,r;if(!e)throw u.ErrorBuilder.systemError(`Refer table ${null===(i=n.fk)||void 0===i?void 0:i.dtoId} not found at ${t}:${n.name}`);const s=`${t}_${n.name}_fk`;return[`queryInterface.addConstraint("${t}",{fields:["${n.name}"],type:"foreign key",name:"${s}",references:{table:"${e.id}",field:"id"},onDelete:'${this.getSqlCascadeAction(null===(o=n.fk)||void 0===o?void 0:o.cascade)}',onUpdate:'${this.getSqlCascadeAction(null===(r=n.fk)||void 0===r?void 0:r.cascade)}',"transaction":t})`,`queryInterface.removeConstraint("${t}","${s}",{"transaction":t})`]}getAddColumnUpDown(e,t){return[`queryInterface.addColumn('${e}','${t.name}',${this.generateFieldPropertiesQuery(t)},{"transaction":t})`,`queryInterface.removeColumn('${e}','${t.name}',{"transaction":t})`]}generateCreateTableQuery(e){let t={upTableAdd:[],downTableRemove:[],upConstraintAdd:[],downConstraintRemove:[],upTableRemove:[],downTableAdd:[],upConstraintRemove:[],downConstraintAdd:[]},n="",i="";n+="{\n";for(const t of(0,f.getDirectFields)(e)){let e=this.generateFieldPropertiesQuery(t);n+=`${t.name}:${e},\n`}n+="}\n",i+='{charset:"utf8",transaction:t}',t.upTableAdd.push(`queryInterface.createTable("${e.id}",${n},{charset:"utf8",transaction:t})`),t.downTableRemove.push(`queryInterface.dropTable("${e.id}",{"transaction":t})`);const o=this.getUniqueConstraintGroups(e);for(const n of o){const[i,o]=this.getUniqueConstraintUpDown(e.id,n);t.upConstraintAdd.push(i),t.downConstraintRemove.push(o)}for(const n of(0,f.getDirectFields)(e))if(n.fk){let i=this.modelMetadata.find((e=>{var t;return e.id===(null===(t=n.fk)||void 0===t?void 0:t.dtoId)}));const[o,r]=this.getForeignKeyConstraintUpDown(i,e.id,n);t.upConstraintAdd.push(o),t.downConstraintRemove.push(r)}return t}isBooleanDiff(e,t){return!!e&&!t||!!t&&!e}runProcess(e){return s(this,void 0,void 0,(function*(){return new Promise(((t,n)=>{(0,l.exec)(e,{env:process.env},(e=>(e&&n(e),t())))}))}))}rollback(e){return s(this,void 0,void 0,(function*(){let t=d.default.join(e,"scripts");if(!c.default.existsSync)throw u.ErrorBuilder.systemError("Migration directory not found");this.logger.debug("Rolling back last migration"),yield this.runProcess(`${this.cliPath} --url=${this.databaseURL} --migrations-path=${t} db:migrate:undo`),this.logger.debug("Rollback completed")}))}migrate(e){var t,n,o,r,a,l,g,y;return s(this,void 0,void 0,(function*(){let v=d.default.join(e,"metadata.json"),m=d.default.join(e,"scripts");c.default.existsSync(m)||(this.logger.debug("Migration directory not exists, creating empty folder"),c.default.mkdirSync(m,{recursive:!0})),c.default.existsSync(v)||(this.logger.debug("Migration metadata does not exist, creating one"),c.default.writeFileSync(v,JSON.stringify([]))),this.logger.debug("Parsing migration metadata file");let b=JSON.parse(String(c.default.readFileSync(v)));this.logger.debug("Calculating differences...");const C=this.modelMetadata.filter((e=>!b.find((t=>e.id===t.id)))),M=this.modelMetadata.filter((e=>b.find((t=>t.id===e.id)))).map((e=>e.id));let S=[];S.push(...C.map((e=>this.generateCreateTableQuery(e))));for(const e of M){const i=b.find((t=>t.id===e)),s=this.modelMetadata.find((t=>t.id===e));i.id!==s.id&&S.push({upTableAdd:[`queryInterface.query("ALTER TABLE ${i.id} RENAME TO ${s.id}",{"transaction":t})`],downTableRemove:[`queryInterface.query("ALTER TABLE ${s.id} RENAME TO ${i.id}",{"transaction":t})`],upConstraintAdd:[],downConstraintRemove:[],upTableRemove:[],downTableAdd:[],upConstraintRemove:[],downConstraintAdd:[]});let d={upTableAdd:[],downTableRemove:[],upConstraintAdd:[],downConstraintRemove:[],upTableRemove:[],downTableAdd:[],upConstraintRemove:[],downConstraintAdd:[]};const c=(0,f.getDirectFields)(i).filter((e=>!(0,f.getDirectFields)(s).find((t=>e.name===t.name))));for(const e of c){const[t,n]=this.getAddColumnUpDown(s.id,e);if(d.upTableRemove.push(n),d.downTableAdd.push(t),e.fk){let t=this.modelMetadata.find((t=>{var n;return t.id===(null===(n=e.fk)||void 0===n?void 0:n.dtoId)}));const[n,i]=this.getForeignKeyConstraintUpDown(t,s.id,e);d.upConstraintRemove.push(i),d.downConstraintAdd.push(n)}}const u=(0,f.getDirectFields)(s).filter((e=>!(0,f.getDirectFields)(i).find((t=>e.name===t.name))));for(const e of u){const[t,n]=this.getAddColumnUpDown(s.id,e);if(d.upTableAdd.push(t),d.downTableRemove.push(n),e.fk){let t=this.modelMetadata.find((t=>{var n;return t.id===(null===(n=e.fk)||void 0===n?void 0:n.dtoId)}));const[n,i]=this.getForeignKeyConstraintUpDown(t,s.id,e);d.upConstraintAdd.push(n),d.downConstraintRemove.push(i)}}const h=(0,f.getDirectFields)(s).filter((e=>(0,f.getDirectFields)(i).find((t=>e.name===t.name)))).map((e=>e.name));for(const e of h){const c=(0,f.getFieldByName)(i,e),u=(0,f.getFieldByName)(s,e);if((this.isBooleanDiff(c.floating,u.floating)||this.isBooleanDiff(c.isBigInt,u.isBigInt)||this.isBooleanDiff(c.isRequired,u.isRequired)||this.isBooleanDiff(null===(t=c.pk)||void 0===t?void 0:t.isAutoIncrement,null===(n=u.pk)||void 0===n?void 0:n.isAutoIncrement)||c.dataType!==u.dataType||c.textLength!==u.textLength||c.defaultValue!==u.defaultValue)&&(d.upTableAdd.push(`queryInterface.changeColumn("${s.id}","${u.name}",${this.generateFieldPropertiesQuery(u)},{"transaction":t})`),d.downTableRemove.push(`queryInterface.changeColumn("${s.id}","${c.name}",${this.generateFieldPropertiesQuery(c)},{"transaction":t})`)),(null===(o=c.fk)||void 0===o?void 0:o.dtoId)!==(null===(r=u.fk)||void 0===r?void 0:r.dtoId)||(null===(a=c.fk)||void 0===a?void 0:a.cascade)!==(null===(l=u.fk)||void 0===l?void 0:l.cascade)){if(null===(g=c.fk)||void 0===g?void 0:g.dtoId){const e=this.modelMetadata.find((e=>{var t;return e.id===(null===(t=c.fk)||void 0===t?void 0:t.dtoId)})),[t,n]=this.getForeignKeyConstraintUpDown(e,s.id,c);d.upTableAdd.push(n),d.downTableRemove.push(t)}if(null===(y=u.fk)||void 0===y?void 0:y.dtoId){const e=this.modelMetadata.find((e=>{var t;return e.id===(null===(t=u.fk)||void 0===t?void 0:t.dtoId)})),[t,n]=this.getForeignKeyConstraintUpDown(e,s.id,u);d.upTableAdd.push(t),d.downTableRemove.push(n)}}}const p=this.getUniqueConstraintGroups(i),v=this.getUniqueConstraintGroups(s),m=p.filter((e=>!!v.find((t=>uniqueGroupComparator(e,t))))),C=p.filter((e=>!m.find((t=>uniqueGroupComparator(e,t)))));for(const e of C){const[t,n]=this.getUniqueConstraintUpDown(s.id,e);d.upConstraintRemove.push(n),d.downConstraintAdd.push(t)}const M=v.filter((e=>!m.find((t=>uniqueGroupComparator(e,t)))));for(const e of M){const[t,n]=this.getUniqueConstraintUpDown(s.id,e);d.upConstraintAdd.push(t),d.downConstraintRemove.push(n)}for(const e of m){const t=p.find((t=>uniqueGroupComparator(t,e))),n=v.find((t=>uniqueGroupComparator(t,e)));if(t.fieldNames.length!==n.fieldNames.length||t.fieldNames.some((e=>!n.fieldNames.includes(e)))){const[e,i]=this.getUniqueConstraintUpDown(s.id,t),[o,r]=this.getUniqueConstraintUpDown(s.id,n);d.upConstraintRemove.push(i),d.upConstraintAdd.push(o),d.downConstraintRemove.push(r),d.downConstraintAdd.push(e)}}(d.upTableAdd.length||d.downTableRemove.length||d.upConstraintAdd.length||d.downConstraintRemove.length||d.upConstraintRemove.length||d.downConstraintAdd.length||d.upTableRemove.length||d.downTableAdd.length)&&S.push(d)}if(S.length){let e=`${Date.now()}-auto-migration.js`;const getTransactionalScript=e=>`const t = await queryInterface.sequelize.transaction({autoCommit: false}); \n try {\n ${e.reduce(((e,t)=>e+`await ${t};`),"")}\n await t.commit();\n } catch(err){\n await t.rollback(); \n throw(err);\n }`,migrationFunction=(e,t)=>s(this,void 0,void 0,(function*(){if(!e.up.length&&!e.down.length)return;let n=d.default.join(m,t),o=i.MIGRATION_TEMPLATE,r=new RegExp(i.COMMENT_BLOCK_REGEX_PATTERN),s=getTransactionalScript(e.up),a=getTransactionalScript(e.down);o=o.replace(r,s),o=o.replace(r,a),this.logger.debug("Writing to file",n),c.default.writeFileSync(n,o)}));throw yield migrationFunction({up:[...S.reduce(((e,t)=>e.concat(t.upConstraintRemove)),[]),...S.reduce(((e,t)=>e.concat(t.upTableRemove)),[]),...S.reduce(((e,t)=>e.concat(t.upTableAdd)),[]),...S.reduce(((e,t)=>e.concat(t.upConstraintAdd)),[])],down:[...S.reduce(((e,t)=>e.concat(t.downConstraintRemove)),[]).reverse(),...S.reduce(((e,t)=>e.concat(t.downTableRemove)),[]).reverse(),...S.reduce(((e,t)=>e.concat(t.downTableAdd)),[]).reverse(),...S.reduce(((e,t)=>e.concat(t.downConstraintAdd)),[]).reverse()]},e),this.logger.debug("Updating metadata file"),c.default.writeFileSync(v,JSON.stringify(this.modelMetadata.map((e=>this.getLeanModelMetadata(e))))),u.ErrorBuilder.systemError(`Migration review needed: ${e}`)}this.logger.debug("No difference, running migration"),this.logger.debug("Create database if not exist");try{yield this.runProcess(`${this.cliPath} --url=${this.databaseURL} db:create`)}catch(e){if(String(e).indexOf("already exists")<0)throw e}if(this.logger.debug("Running migration"),this.sqlProvider===p.SqlProvider.POSTGRES){this.logger.debug("Creating unaccent extension for postgres");const e=new h.Sequelize(this.databaseURL);yield e.query("CREATE EXTENSION IF NOT EXISTS unaccent;")}else if(this.sqlProvider===p.SqlProvider.MYSQL){this.logger.debug("Creating unaccent function for mysql");const e=new h.Sequelize(this.databaseURL,{dialectOptions:{multipleStatements:!0}}),t="ĂÂÀÁẢÃẠẰẮẲẴẶẦẤẨẪẬÔƠÒÓỎÕỌỒỐỔỖỘỜỚỞỠỢÈÉẺẼẸÊỀẾỂỄỆÙÚỦŨỤƯỪỨỬỮỰÌÍỈĨỊỲÝỶỸỴ",n="AAAAAAAAAAAAAAAAAOOOOOOOOOOOOOOOOOEEEEEEEEEEEUUUUUUUUUUUIIIIIYYYYY",i=`SET GLOBAL log_bin_trust_function_creators = 1; \nDROP FUNCTION IF EXISTS unaccent; \nCREATE FUNCTION unaccent( textvalue TEXT ) RETURNS TEXT \nBEGIN \nSET @textvalue = textvalue; \nSET @withaccents = 'ŠšŽžÄÅÆÇËÎÏÑÖØÛÜŸÞäåæçëîïñõöøûüÿþƒ${t}${t.toLowerCase()}'; \nSET @withoutaccents = 'SsZzAAACEIINOOUUYBaaaceiinooouuybf${n}${n.toLowerCase()}'; \nSET @count = LENGTH(@withaccents); \nWHILE @count > 0 DO \nSET @textvalue = REPLACE(@textvalue, SUBSTRING(@withaccents, @count, 1), SUBSTRING(@withoutaccents, @count, 1)); \nSET @count = @count - 1; \nEND WHILE; \nRETURN @textvalue; \nEND; \n`;yield e.query(i,{type:h.QueryTypes.RAW})}yield this.runProcess(`${this.cliPath} --url=${this.databaseURL} --migrations-path=${m} db:migrate`),this.logger.debug("Migration finished")}))}remove(e,t){return Object.keys(e).filter((e=>!t.includes(e))).reduce(((t,n)=>Object.assign(t,{[n]:e[n]})),{})}getLeanModelMetadata(e){return{id:e.id,fields:(0,f.getDirectFields)(e).map((e=>Object.assign({},this.remove(e,["vectorProps","stateMachineTransition","serverValue","searchable","regex","rangeProps","modificationTimestamp","mimeProps","isTimestamp","isSymbol","isLabel","injecteeSuperClass","hasMany","elementDto","creationTimestamp"]))))}}};y.COMMENT_BLOCK_REGEX_PATTERN="/\\*(\\*(?!/)|[^*])*\\*\\/",y.MIGRATION_TEMPLATE="'use strict';\n module.exports = {\n up: async (queryInterface, Sequelize) => {\n /**\n */\n },\n \n down: async (queryInterface, Sequelize) => {\n /**\n */\n }\n };",y=i=o([(0,u.Injectable)(),r("design:paramtypes",[String,String,String,u.AbstractLogger])],y),t.DefaultSqlDatabaseMigrator=y},function(e,t){e.exports=require("child_process")}])}));
|
|
1
|
+
!function webpackUniversalModuleDefinition(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var n=t();for(var i in n)("object"==typeof exports?exports:e)[i]=n[i]}}(global,(function(){return function(e){var t={};function __webpack_require__(n){if(t[n])return t[n].exports;var i=t[n]={i:n,l:!1,exports:{}};return e[n].call(i.exports,i,i.exports,__webpack_require__),i.l=!0,i.exports}return __webpack_require__.m=e,__webpack_require__.c=t,__webpack_require__.d=function(e,t,n){__webpack_require__.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},__webpack_require__.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},__webpack_require__.t=function(e,t){if(1&t&&(e=__webpack_require__(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(__webpack_require__.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var i in e)__webpack_require__.d(n,i,function(t){return e[t]}.bind(null,i));return n},__webpack_require__.n=function(e){var t=e&&e.__esModule?function getDefault(){return e.default}:function getModuleExports(){return e};return __webpack_require__.d(t,"a",t),t},__webpack_require__.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},__webpack_require__.p="",__webpack_require__(__webpack_require__.s=37)}([function(e,t){e.exports=require("@clairejs/core")},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractHttpAuthorizationProvider=void 0;t.AbstractHttpAuthorizationProvider=class AbstractHttpAuthorizationProvider{}},function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractHttpRequestHandler=void 0;const o=n(0),r=n(6),s=n(9);t.AbstractHttpRequestHandler=class AbstractHttpRequestHandler{constructor(e,t){this.mountPoint=e,this.logger=t}resolverMountPoint(e,t){if(!e)return"";const n=[];return n.push(...t),n.reduce(((e,t)=>`${e}/${t}`),"").replace(/(\/)\/+/g,"$1")}getMountedEndpointInfo(){var e,t,n;return i(this,void 0,void 0,(function*(){if(!this.mountedEndpointInfo){const i=[],a=(0,o.getServiceProvider)().getInjector(),d=a.resolveMultiple(s.AbstractHttpController);yield a.initInstances();for(const e of d){const t=(0,o.getObjectMetadata)(e.constructor),n=e.getEndpointMetadata();for(const r of n){const n={mount:r.httpMethod===o.SocketMethod.MESSAGE?r.url:this.resolverMountPoint(t,[this.mountPoint||"/",r.url]),httpMethod:r.httpMethod,controller:e,handlerFunctionName:r.name};i.push({endpointMetadata:r,endpoint:n})}}const c=[];for(const o of i){const i=c.find((e=>e.endpoint.mount===o.endpoint.mount&&e.endpoint.httpMethod===o.endpoint.httpMethod));i?null===(e=this.logger)||void 0===e||e.warn(`Implicit overriding endpoint: ${(0,r.getEndpointId)(i.endpoint)} of ${null===(t=i.endpoint.controller)||void 0===t?void 0:t.constructor.name}:${i.endpoint.handlerFunctionName}`,`Ignore ${(0,r.getEndpointId)(o.endpoint)} of ${null===(n=o.endpoint.controller)||void 0===n?void 0:n.constructor.name}:${o.endpoint.handlerFunctionName}`):c.push(o)}this.mountedEndpointInfo=c}return this.mountedEndpointInfo}))}}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getDirectFields=t.getFieldByName=t.getTransactionFromContext=void 0;const i=n(0),o=n(10);t.getTransactionFromContext=e=>{const t=e[o.INJECTED_TRANSACTION];if(!t)throw i.ErrorBuilder.systemError("Cannot get transaction from current context");return t};t.getFieldByName=(e,t)=>e.fields.find((e=>e.name===t));t.getDirectFields=e=>e.fields.filter((e=>!e.hasMany))},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractAccessCondition=void 0;t.AbstractAccessCondition=class AbstractAccessCondition{}},function(e,t,n){"use strict";var i=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},o=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractServerSocketManager=void 0;const r=n(0),s=n(29),a=n(4),d=n(7),c="x-socket-action",l="read",u="write";let h=class SocketReadCondition extends a.AbstractAccessCondition{resolveConditionValue(e){return o(this,void 0,void 0,(function*(){return e.getHeaders()["x-socket-action"]===l}))}validate(e){return o(this,void 0,void 0,(function*(){return!!e}))}getConditionMetadata(){return{name:"socket_read",description:"Can receive message from channel",valueType:r.AccessConditionValueType.BOOLEAN}}};h=i([(0,r.Register)()],h);let p=class SocketWriteCondition extends a.AbstractAccessCondition{resolveConditionValue(e){return o(this,void 0,void 0,(function*(){return e.getHeaders()["x-socket-action"]===u}))}validate(e){return o(this,void 0,void 0,(function*(){return!!e}))}getConditionMetadata(){return{name:"socket_write",description:"Can send message to channel",valueType:r.AccessConditionValueType.BOOLEAN}}};p=i([(0,r.Register)()],p);t.AbstractServerSocketManager=class AbstractServerSocketManager{constructor(e,t,n,i,o){this.requireAuthentication=e,this.logger=t,this.redisClient=n,this.connectionHandler=i,this.authProvider=o}getUniqueChannelPrefix(){return"CHANNEL:"}formatBroadcastData(e,t){return{type:r.MessageType.PLAIN,data:{channel:e,message:t}}}getUniqueChannelName(e){return`${this.getUniqueChannelPrefix()}${e}`}getSocketIdsOfChannel(e){return o(this,void 0,void 0,(function*(){return yield new Promise(((t,n)=>this.redisClient.smembers(this.getUniqueChannelName(e),((e,i)=>{e?n(e):t(i)}))))}))}addSocketToChannel(e,t){return o(this,void 0,void 0,(function*(){const n=yield this.getById(e);n&&(n.addChannels(t),yield Promise.all(t.map((t=>new Promise(((n,i)=>this.redisClient.sadd(this.getUniqueChannelName(t.name),e,(e=>{e?i(e):n()}))))))),yield n.saveSocketInfo())}))}removeSocketFromChannel(e,t){return o(this,void 0,void 0,(function*(){const n=yield this.getById(e);n&&(n.removeChannels(t),yield Promise.all(t.map((t=>new Promise(((n,i)=>this.redisClient.srem(this.getUniqueChannelName(t),e,(e=>{e?i(e):n()}))))))),yield n.saveSocketInfo())}))}handle(e){var t;return o(this,void 0,void 0,(function*(){switch(e.method){case r.SocketMethod.CONNECT:{this.logger.debug("Socket connection attempt",e.socketId);const n=yield this.authProvider.getPrincipalResolver().resolvePrincipal((null===(t=e.data)||void 0===t?void 0:t.auth)||"");if(!n&&this.requireAuthentication)throw r.ErrorBuilder.error(r.Errors.AUTHENTICATION_ERROR);const i=yield this.addSocket({id:e.socketId,authInfo:n,channels:[],createdAt:Date.now()},e.data);if(!i)throw r.ErrorBuilder.error(r.Errors.SYSTEM_ERROR,"Socket not found after create: "+e.socketId);this.connectionHandler.onSocketConnect(i);break}case r.SocketMethod.DISCONNECT:{this.logger.debug("Socket disconnect",e);const t=yield this.getById(e.socketId);if(t){const n=yield this.getMountedEndpointInfo();for(const e of t.getChannelsInfo()){const i=n.find((t=>t.endpointMetadata.url===e.name));i&&i.endpoint.controller.onChannelLeave(t)}this.connectionHandler.onSocketDisconnect(t),t.disconnect(),yield this.removeSocket(e.socketId)}break}case r.SocketMethod.MESSAGE:{this.logger.debug("Socket message",e);const t=JSON.parse(e.data),n=yield this.getById(e.socketId);if(n)switch(t.type){case r.MessageType.PING_PONG:null==n||n.sendRaw({type:r.MessageType.PING_PONG,data:void 0});break;case r.MessageType.CHANNEL_JOIN:{const e=t.data,i=[];for(const t of e){let e=!1,o=!1;const s=(yield this.getMountedEndpointInfo()).find((e=>e.endpointMetadata.url===t));if(s){try{const e=new d.HttpRequest({method:r.SocketMethod.MESSAGE,pathName:t,headers:{[c]:l}},s.endpointMetadata);yield this.authProvider.authorize(n.getAuthInfo(),e,s),o=!0}catch(e){}try{const i=new d.HttpRequest({method:r.SocketMethod.MESSAGE,pathName:t,headers:{[c]:u}},s.endpointMetadata);yield this.authProvider.authorize(n.getAuthInfo(),i,s),e=!0}catch(e){}(e||o)&&(this.logger.debug("Adding channel info",t,e,o),i.push({name:t,clientToServerAllowed:e,serverToClientAllowed:o})),s.endpoint.controller.onChannelJoin(n)}}yield this.addSocketToChannel(n.getId(),i),n.sendRaw({type:r.MessageType.CHANNEL_JOIN,data:i.map((e=>e.name))})}break;case r.MessageType.CHANNEL_LEAVE:{const e=t.data;for(const t of e){const e=(yield this.getMountedEndpointInfo()).find((e=>e.endpointMetadata.url===t));e&&e.endpoint.controller.onChannelLeave(n)}yield this.removeSocketFromChannel(n.getId(),e)}break;case r.MessageType.PLAIN:{const e=t.data.channel,i=t.data.message;if(e){if(n.getChannelsInfo().find((t=>t.name===e&&t.clientToServerAllowed))){const t=(yield this.getMountedEndpointInfo()).find((t=>t.endpointMetadata.url===e));if(t){!1!==t.endpoint.controller.onMessage(n,i)&&(this.logger.debug("broadcasting to channel",e,i),this.broadcastToChannel(e,i))}}}else this.connectionHandler.onMessage(n,i)}break;default:this.logger.debug("Invalid message format",t)}else this.logger.debug("Socket not found",e.socketId);break}default:return}}))}getMountedEndpointInfo(){return o(this,void 0,void 0,(function*(){if(!this.mountedEndpointInfo){const e=(0,r.getServiceProvider)().getInjector(),t=e.resolveMultiple(s.AbstractSocketController);yield e.initInstances(),this.mountedEndpointInfo=t.map((e=>({endpoint:{httpMethod:r.SocketMethod.MESSAGE,mount:e.channel,controller:e,handlerFunctionName:e.onMessage.name},endpointMetadata:{httpMethod:r.SocketMethod.MESSAGE,description:"Send / Receive message to / from channel",dataType:r.DataType.OBJECT,url:e.channel,name:e.channel,accessConditions:[h,p]}})))}return this.mountedEndpointInfo}))}}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getEndpointId=void 0;t.getEndpointId=e=>`${e.httpMethod}:${e.mount}`},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HttpRequest=void 0;const i=n(0);t.HttpRequest=class HttpRequest{constructor(e,t){this.valueHolder={},this.method=e.method,this.pathName=e.pathName,this.headers=e.headers||{},this.hash=e.hash||"",this.params=e.params||{},(null==t?void 0:t.paramsValidationDto)&&(this.params=(0,i.validateData)(this.params,null==t?void 0:t.paramsValidationDto)),this.query=e.query||{},(null==t?void 0:t.queriesValidationDto)&&(this.query=(0,i.validateData)(this.jsonParsing(this.query,t.queriesValidationDto),t.queriesValidationDto)),this.body=e.body||{},t&&(t.httpMethod===i.HttpMethod.POST||t.httpMethod===i.HttpMethod.PUT)&&(null==t?void 0:t.bodyValidationDto)&&(this.body=(0,i.validateData)(this.body||{},t.bodyValidationDto))}jsonParsing(e,t){const n=Object.assign({},e);for(const o of t.fields)try{(void 0!==e[o.name]||o.isRequired)&&(n[o.name]=JSON.parse(e[o.name]))}catch(e){throw i.ErrorBuilder.error(i.Errors.VALIDATION_ERROR,`JSON parsing failed for field ${o.name}`)}return n}getAuthInfo(){return this.authInfo}setAuthInfo(e){this.authInfo=e}getHeaders(){return this.headers}getMethod(){return this.method}getHash(){return this.hash}getPathName(){return this.pathName}getValue(e){return this.valueHolder[e]}setValue(e,t){this.valueHolder[e]=t}getParams(){return this.params}getQuery(){return this.query}getBody(){return this.body}}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ResponseBuilder=t.HttpResponse=void 0;class HttpResponse{constructor(){this.code=200,this.headers={},this.cookies={}}}t.HttpResponse=HttpResponse;class ResponseBuilder{constructor(){this.response=new HttpResponse}status(e){return this.response.code=e,this}header(e,t){return this.response.headers[e]=t,this}cookie(e,t){return this.response.headers[e]=t,this}get(){return this.response}static json(e){const t=new ResponseBuilder;return t.response.value=e,t.response.headers["Content-Type"]="application/json",t}static html(e){const t=new ResponseBuilder;return t.response.value=e,t.response.headers["Content-Type"]="text/html; charset=UTF-8",t}static binary(e){const t=new ResponseBuilder;return t.response.value=e,t.response.headers["Content-Type"]="application/octet-stream",t}static success(){const e=new ResponseBuilder;return e.response.code=200,e.response}static notFound(e){const t=new ResponseBuilder;return t.response.code=404,t.response.value=e,t.response}static accessDenied(e){const t=new ResponseBuilder;return t.response.code=400,t.response.value=e,t.response}}t.ResponseBuilder=ResponseBuilder},function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractHttpController=void 0;const o=n(0),r=n(3);t.AbstractHttpController=class AbstractHttpController{constructor(e){this.databaseAdapter=e}createTransaction(){return i(this,void 0,void 0,(function*(){return this.databaseAdapter.createTransaction()}))}getCurrentTransaction(){return i(this,void 0,void 0,(function*(){return(0,r.getTransactionFromContext)(this)}))}getEndpointMetadata(){const e=(0,o.getObjectMetadata)(this.constructor);return e?e.fields.filter((e=>{return!!(t=e).httpMethod||void 0!==t.openAccess||!!t.accessConditions;var t})).map((t=>Object.assign(Object.assign({},t),{permissionGroup:e.permissionGroup}))):[]}}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ExitCode=t.INJECTED_TRANSACTION=void 0,t.INJECTED_TRANSACTION="__INJECTED_TRANSACTION__",t.ExitCode={SIGTERM_INTERUPTION:-1,SIGINT_INTERUPTION:-2,UNCAUGHT_EXCEPTION:-3,UNHANDLED_REJECTION:-4}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Errors=void 0;const i=n(0);t.Errors=Object.assign(Object.assign({},i.Errors),{TFA_REQUIRED:"TFA_REQUIRED"})},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TransactionLink=void 0,function(e){e.CREATE_NEW="create_new",e.INHERIT_OR_CREATE="inherit_or_create",e.INHERIT_OR_THROW="inherit_or_throw"}(t.TransactionLink||(t.TransactionLink={}))},function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractRbacAuthProvider=void 0;const o=n(0),r=n(1),s=n(6);class AbstractRbacAuthProvider extends r.AbstractHttpAuthorizationProvider{constructor(e,t,n){super(),this.authDataResolver=e,this.principalResolver=t,this.logger=n}getPrincipalResolver(){return this.principalResolver}resolvePrincipal(e){return this.principalResolver.resolvePrincipal(this.authDataResolver(e))}authorize(e,t,n){return i(this,void 0,void 0,(function*(){if(n.endpointMetadata.openAccess)return;const i=yield this.getRbacCache();if(!i)throw o.ErrorBuilder.error(o.Errors.SYSTEM_ERROR,"Cannot read rbac cache");let r=[];if(e){const t=yield this.getRolesOfPrincipal(e);r=(i.roles||[]).filter((e=>!!t.find((t=>t===e.roleId))))}else r=(i.roles||[]).filter((e=>e.isAnonymousRole));if(!r.length)throw o.ErrorBuilder.error(o.Errors.ACCESS_DENIED,"No role attached");if(r.find((e=>e.isSuperRole)))return;const a=(i.rolePolicies||[]).filter((e=>!!r.find((t=>t.roleId===e.roleId)))),d=(i.policies||[]).filter((e=>!!a.find((t=>t.policyId===e.policyId)))),c=(i.policyPermissions||[]).filter((e=>!!d.find((t=>t.policyId===e.policyId)))),l=(i.policyPermissionConditions||[]).filter((e=>!!c.find((t=>t.id===e.policyPermissionId)))),u=c.filter((e=>e.permission===(0,s.getEndpointId)(n.endpoint)));if(!u.length)throw o.ErrorBuilder.error(o.Errors.ACCESS_DENIED,`Not permitted: ${(0,s.getEndpointId)(n.endpoint)}`);let h=!1;for(const e of u){const i=l.filter((t=>t.policyPermissionId===e.id));if(i.length){let e=!0;const r=(0,o.getServiceProvider)().getInjector(),s=(n.endpointMetadata.accessConditions||[]).map((e=>r.resolve(e)));yield r.initInstances();for(const n of i){const i=s.find((e=>e.getConditionMetadata().name===n.conditionName));if(!i)continue;const o=yield i.resolveConditionValue(t),r=JSON.parse(n.conditionValue);if(e=yield i.validate(o,r),!e){this.logger.debug("Condition check failed: condition, requested, permitted",n.conditionName,o,r);break}}h=e}else h=!0;if(h)break}if(!h)throw o.ErrorBuilder.error(o.Errors.ACCESS_DENIED,"Condition check failed")}))}}t.AbstractRbacAuthProvider=AbstractRbacAuthProvider},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractFileUploadHandler=void 0;t.AbstractFileUploadHandler=class AbstractFileUploadHandler{}},function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractRepository=void 0;const o=n(0);t.AbstractRepository=class AbstractRepository{constructor(e){this.model=e,this.modelMetadata=(0,o.getObjectMetadata)(this.model)}beforeCreating(e,t){return i(this,void 0,void 0,(function*(){for(const n of t)for(const t of this.modelMetadata.fields)t.userResolver&&e&&(n[t.name]=t.userResolver(e))}))}project(e,t){return t?e.map((e=>t.reduce(((t,n)=>Object.assign(t,{[n]:e[n]})),{}))):e}}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractSocketConnectionHandler=void 0;t.AbstractSocketConnectionHandler=class AbstractSocketConnectionHandler{}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SqlProvider=t.NoSqlProvider=void 0,function(e){e.MONGODB="mongodb",e.DYNAMODB="dynamodb"}(t.NoSqlProvider||(t.NoSqlProvider={})),function(e){e.MYSQL="mysql",e.POSTGRES="postgres"}(t.SqlProvider||(t.SqlProvider={}))},function(e,t){e.exports=require("sequelize")},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractPrincipalResolver=void 0;t.AbstractPrincipalResolver=class AbstractPrincipalResolver{}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CurrentUser=t.UriMapper=t.Raw=t.Socket=t.Headers=t.Queries=t.Params=t.Body=t.AccessCondition=t.TfaRequired=t.OpenAccess=t.ApiResponse=t.Get=t.Del=t.Put=t.Post=t.Endpoint=t.ApiDescription=t.Controller=void 0;const i=n(0);t.Controller=e=>t=>{(0,i.getServiceProvider)().register(t,"singleton");(0,i.initObjectMetadata)(t.prototype).permissionGroup=null==e?void 0:e.permissionGroup};t.ApiDescription=e=>(t,n)=>{(0,i.initFieldMetadata)(t,n).description=e};t.Endpoint=e=>(t,n)=>{const o=(0,i.initFieldMetadata)(t,n);o.httpMethod=e.method,o.url=e.url};t.Post=e=>(n,o,r)=>(0,t.Endpoint)({method:i.HttpMethod.POST,url:e})(n,o);t.Put=e=>(n,o,r)=>(0,t.Endpoint)({method:i.HttpMethod.PUT,url:e})(n,o);t.Del=e=>(n,o,r)=>(0,t.Endpoint)({method:i.HttpMethod.DEL,url:e})(n,o);t.Get=e=>(n,o,r)=>(0,t.Endpoint)({method:i.HttpMethod.GET,url:e})(n,o);t.ApiResponse=e=>(t,n,o)=>{const r=(0,i.initFieldMetadata)(t,n);e===String?r.responseValidationDto={id:"",primitiveType:i.DataType.STRING,fields:[]}:e===Number?r.responseValidationDto={id:"",primitiveType:i.DataType.NUMBER,fields:[]}:e===Boolean?r.responseValidationDto={id:"",primitiveType:i.DataType.BOOLEAN,fields:[]}:r.responseValidationDto=(0,i.getObjectMetadata)(e)};t.OpenAccess=()=>(e,t)=>{(0,i.initFieldMetadata)(e,t).openAccess=!0};t.TfaRequired=()=>(e,t)=>{(0,i.initFieldMetadata)(e,t).tfaRequired=!0};t.AccessCondition=e=>(t,n)=>{(0,i.initFieldMetadata)(t,n).accessConditions=e};const RequestDeco=e=>(t,n,o)=>{const r=(0,i.initFieldMetadata)(t,n),s=Reflect.getMetadata("design:paramtypes",t,n)||[];switch(e){case"body":r.bodyValidationDto=(0,i.getObjectMetadata)(s[o]);break;case"params":r.paramsValidationDto=(0,i.getObjectMetadata)(s[o]);break;case"queries":r.queriesValidationDto=(0,i.getObjectMetadata)(s[o])}r.params||(r.params={}),r.params[o]={source:e,diClass:s[o]}};t.Body=()=>RequestDeco("body");t.Params=()=>RequestDeco("params");t.Queries=()=>RequestDeco("queries");t.Headers=()=>RequestDeco("headers");t.Socket=()=>RequestDeco("socket");t.Raw=()=>RequestDeco("raw");t.UriMapper=e=>(t,n)=>{(0,i.initFieldMetadata)(t,n).uriMapper=e};t.CurrentUser=e=>(t,n)=>{const o=(0,i.initFieldMetadata)(t,n);o.userResolver=e,o.serverValue=!0}},function(e,t){e.exports=require("parseurl")},function(e,t){e.exports=require("query-string")},function(e,t,n){"use strict";var i=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},o=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.FilterModelFieldAccessCondition=void 0;const r=n(0),s=n(4);t.FilterModelFieldAccessCondition=(e,t)=>{let n=class _ extends s.AbstractAccessCondition{resolveConditionValue(e){return o(this,void 0,void 0,(function*(){return t(e)}))}getConditionMetadata(){return{name:"filter_model_field",valueType:r.AccessConditionValueType.CHOICES,valueConstraint:(0,r.getObjectMetadata)(e).fields.map((e=>e.name))}}validate(e,t){return o(this,void 0,void 0,(function*(){return!!e&&e.every((e=>t.includes(e)))}))}};return n=i([(0,r.Register)()],n),n}},function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.Transactional=void 0;const o=n(0),r=n(10),s=n(12),a=n(25);t.Transactional=e=>(t,n,d)=>{const c=(0,o.initObjectMetadata)(t);(0,o.initFieldMetadata)(t,n),c.transactional=!0;const l=d.value;d.value=function(...d){return i(this,void 0,void 0,(function*(){const i=this;let c,u,h;try{c=yield i.getCurrentTransaction()}catch(e){}switch(e){case s.TransactionLink.CREATE_NEW:u=!0,h=yield i.createTransaction();break;case s.TransactionLink.INHERIT_OR_CREATE:u=!c,h=c||(yield i.createTransaction());break;case s.TransactionLink.INHERIT_OR_THROW:if(u=!1,!c)throw o.ErrorBuilder.systemError(`No transaction to inherit when executing ${t.constructor.name}:${n}`);h=c}const p=Object.assign(Object.create(i),i),f=Object.keys(p).filter((e=>{var t,n;return(null===(t=p[e])||void 0===t?void 0:t.constructor)&&(null===(n=(0,o.getObjectMetadata)(p[e].constructor))||void 0===n?void 0:n.transactional)}));for(const e of f){const t=p[e],n=Object.assign(Object.create(t),t,{[r.INJECTED_TRANSACTION]:h});p[e]=n}try{Object.assign(p,{[r.INJECTED_TRANSACTION]:h});let e=yield l.call(p,...d);return h.getState()===a.TransactionState.EXECUTING&&u&&(yield h.commit()),e}catch(e){throw h.getState()===a.TransactionState.EXECUTING&&u&&(yield h.rollback()),e}}))},Object.defineProperty(d.value,"name",{value:n})}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TransactionState=void 0,function(e){e.EXECUTING="executing",e.COMMITTED="commited",e.ROLLED_BACK="rolled_back"}(t.TransactionState||(t.TransactionState={}))},function(e,t,n){"use strict";var i=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},o=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.MaximumQueryLimit=void 0;const r=n(0),s=n(4);let a=class MaximumQueryLimit extends s.AbstractAccessCondition{resolveConditionValue(e){return o(this,void 0,void 0,(function*(){let t=e.getQuery().limit;return t&&(t=parseInt(t)),t||0}))}validate(e,t){return o(this,void 0,void 0,(function*(){return e>0&&e<=t}))}getConditionMetadata(){return{name:"maximum_query_limit",valueType:r.AccessConditionValueType.NUMBER,valueConstraint:JSON.stringify({min:1})}}};a=i([(0,r.Register)()],a),t.MaximumQueryLimit=a},function(e,t,n){"use strict";var i=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},o=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.DtoFieldValidation=void 0;const r=n(0),s=n(4);t.DtoFieldValidation=(e,t,n)=>{let a=class _ extends s.AbstractAccessCondition{resolveConditionValue(e){return o(this,void 0,void 0,(function*(){return t(e)}))}getConditionMetadata(){return{name:n||"dto_field_condition",valueType:r.AccessConditionValueType.DTO,valueConstraint:JSON.stringify((0,r.getObjectMetadata)(e))}}validate(e,t){return o(this,void 0,void 0,(function*(){try{for(const n of e)(0,r.validateData)(n,t);return!0}catch(e){return!1}}))}};return a=i([(0,r.Register)()],a),a}},function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.ModelRepository=void 0;const o=n(0),r=n(3),s=n(14),a=n(15);class ModelRepository extends a.AbstractRepository{constructor(e){super(e),this.model=e}getNestedQueries(e){return this.modelMetadata.fields.filter((e=>e.hasMany)).filter((t=>(null==e?void 0:e.fields)&&e.fields[t.name])).map((t=>{const n=t.hasMany.relationDto,i=this.getRequestQueryConditionFromQuery(null==e?void 0:e.fields[t.name],Object.assign(Object.assign({},n),{fields:n.fields.filter((e=>{var t;return e.name!==(null===(t=e.hasMany)||void 0===t?void 0:t.column)}))}));return{modelId:t.hasMany.relationDto.id,queries:i.length?{_and:i}:{}}}))}getUploadHandler(){return i(this,void 0,void 0,(function*(){if(void 0===this.fileUploadHandler){const e=(0,o.getServiceProvider)().getInjector();this.fileUploadHandler=e.resolveOptional(s.AbstractFileUploadHandler)||null,yield e.initInstances()}return this.fileUploadHandler}))}getRequestQueryConditionFromQuery(e,t){var n;const i=[];for(const s of(0,r.getDirectFields)(t))if(e[s.name])if(s.pk||s.fk||s.isSymbol)i.push({_in:{[s.name]:e[s.name]}});else if(s.enum)i.push({_in:{[s.name]:e[s.name]}});else switch(s.dataType){case o.DataType.STRING:if(s.searchable){const t={[(null==s?void 0:s.searchable.caseSensitive)?(null==s?void 0:s.searchable.accentSensitive)?"_sub":"_usub":(null===(n=null==s?void 0:s.searchable)||void 0===n?void 0:n.accentSensitive)?"_isub":"_iusub"]:{[s.name]:e[s.name]}};i.push(t)}else i.push({_eq:{[s.name]:e[s.name]}});break;case o.DataType.NUMBER:const t=new o.RangeQueryDto;Object.assign(t,e[s.name]),t.min&&(t.minExclusive?i.push({_gt:{[s.name]:t.min}}):i.push({_gte:{[s.name]:t.min}})),t.max&&(t.maxExclusive?i.push({_lt:{[s.name]:t.max}}):i.push({_lte:{[s.name]:t.max}}))}return i}uriHandling(e,t){return i(this,void 0,void 0,(function*(){const n=yield this.getUploadHandler();if(!n)return;const i=t.use(this.model);for(const o of this.modelMetadata.fields)if(o.uriMapper)for(const r of e){const e=r[o.name];if(!e)continue;const s=yield o.uriMapper(t,r,e);s&&(yield n.moveFile(e,s),r[o.name]=s,yield i.updateOne(r))}}))}beforeReturning(e){var t;return i(this,void 0,void 0,(function*(){const n=yield this.getUploadHandler();for(const i of e)for(const e of this.modelMetadata.fields)if(e.uriMapper&&n){if(!i[e.name])continue;i[e.name]=(null===(t=e.mimeProps)||void 0===t?void 0:t.public)?yield n.resolvePublicUrl(i[e.name]):yield n.resolvePrivateUrl(i[e.name])}}))}createMany({principal:e,body:t,tx:n}){return i(this,void 0,void 0,(function*(){const i=t.records;if(!i.length)return{records:[]};const s=(0,r.getDirectFields)(this.modelMetadata),a=this.modelMetadata.fields.filter((e=>!!e.hasMany));t.records=i.map((e=>s.reduce(((t,n)=>Object.assign(t,void 0!==e[n.name]?{[n.name]:e[n.name]}:{})),{}))),yield this.beforeCreating(e,t.records);let d=t.records.length?yield n.use(this.model).createMany(t.records):[];yield this.uriHandling(d,n),yield this.beforeReturning(d);const c=this.modelMetadata.fields.filter((e=>e.pk||e.serverValue||e.mimeProps)).map((e=>e.name));d=this.project(d,c);for(const r of a){const s=d.map(((e,t)=>(i[t][r.name]||[]).map((t=>Object.assign(Object.assign({},t),{[r.hasMany.column]:e.id}))))).reduce(((e,t)=>e.concat(t)),[]);if(s.length){const i=new ModelRepository((0,o.getModelById)(r.hasMany.relationDto.id));t.records=s;const a=yield i.createMany({principal:e,body:t,tx:n});for(let e=0;e<a.records.length;e++)s[e]=Object.assign(Object.assign({},s[e]),a.records[e]);for(let e=0;e<d.length;e++){const t=[];for(let n=0;n<s.length;n++)s[n][r.hasMany.column]===d[e].id&&t.push(a.records[e]);d[e]=Object.assign(Object.assign({},d[e]),{[r.name]:t})}}}return{records:d}}))}updateMany({principal:e,ops:t,queries:n,body:s,tx:a}){return i(this,void 0,void 0,(function*(){const i=t||[],d=this.modelMetadata.fields.filter((e=>!!e.hasMany)),c=(0,r.getDirectFields)(this.modelMetadata).filter((e=>void 0!==s.update[e.name])),l=c.reduce(((e,t)=>Object.assign(e,{[t.name]:s.update[t.name]})),{});if(null==n?void 0:n.fields){const e=this.getRequestQueryConditionFromQuery(n.fields,this.modelMetadata);e.length&&i.push(...e)}const u=i.length?{_and:[...i]}:{},h=this.getNestedQueries(n);let p=[];if(h.length){const e=yield a.use(this.model).getMany(u,{projection:["id"]},h);p=e.records.map((e=>e.id)),p.length&&c.length&&(yield a.use(this.model).updateMany({_in:{id:p}},l,!1))}else if(c.length)p=yield a.use(this.model).updateMany(u,l,!0);else{const e=yield a.use(this.model).getMany(u,{projection:["id"]});p=e.records.map((e=>e.id))}let f=p.map((e=>Object.assign(Object.assign({},l),{id:e})));yield this.uriHandling(f,a),yield this.beforeReturning(f);for(const t of d){const n=s.update[t.name];if(void 0===n||!p.length)continue;if(p.length>1)throw o.ErrorBuilder.systemError(`Multiple records found while updating @HasMany field: ${t.name}`);const i=f.find((e=>e.id===p[0])),r=(0,o.getModelById)(t.hasMany.relationDto.id),d=a.use(r),c=(yield d.getRecords({_eq:{[t.hasMany.column]:i.id}})).map((e=>e.id)),l=n.map((e=>e.id)).filter((e=>!!e)),u=c.filter((e=>!l.includes(e))),h=n.filter((e=>!e.id)).map((e=>Object.assign(Object.assign({},e),{[t.hasMany.column]:i.id}))),g=n.filter((e=>!!e.id));yield d.deleteMany({_in:{id:u}});const y=new ModelRepository(r),v=yield y.createMany({principal:e,body:{records:h},tx:a}),m=h.map(((e,t)=>Object.assign(Object.assign({},e),v.records[t])));i[t.name]=m.concat(g)}let g=["id"];return(null==n?void 0:n.returning)&&(g=[...g,...Object.keys(s.update).filter((e=>void 0!==s.update[e]))]),{modified:this.project(f,g)}}))}getMany({queries:e,ops:t,queryProvider:n}){var r;return i(this,void 0,void 0,(function*(){const i=t||[];if((null==e?void 0:e.fields)&&i.push(...this.getRequestQueryConditionFromQuery(e.fields,this.modelMetadata)),null==e?void 0:e.search){const t=this.modelMetadata.fields.filter((e=>e.searchable)).map((t=>({_iusub:{[t.name]:e.search}})));t.length&&i.push({_or:t})}const s=yield n.use(this.model).getMany(i.length?{_and:i}:{},{limit:null==e?void 0:e.limit,page:null==e?void 0:e.page,projection:null==e?void 0:e.projection,order:null===(r=null==e?void 0:e.order)||void 0===r?void 0:r.map((e=>{const t=Object.keys(e).find((t=>!!e[t]));return[t,e[t]]}))},this.getNestedQueries(e)),a=s.records.map((e=>e.id));for(const t of this.modelMetadata.fields){if(!t.hasMany||(null==e?void 0:e.projection)&&!e.projection.includes(t.name))continue;const i=(0,o.getModelById)(t.hasMany.relationDto.id),r=new ModelRepository(i),d=a.length?yield r.getMany({queries:{fields:{[t.hasMany.column]:a}},queryProvider:n}):{records:[]};for(const e of s.records)e[t.name]=d.records.filter((n=>n[t.hasMany.column]===e.id))}return yield this.beforeReturning(s.records),{total:s.total,records:this.project(s.records,null==e?void 0:e.projection)}}))}deleteMany({queries:e,ops:t,tx:n}){return i(this,void 0,void 0,(function*(){let i=t||[];if(null==e?void 0:e.fields){const t=this.getRequestQueryConditionFromQuery(e.fields,this.modelMetadata);t.length&&i.push(...t)}const o=i.length?{_and:[...i,...t||[]]}:{},r=this.getNestedQueries(e);let s=[];if(r.length){const e=yield n.use(this.model).getRecords(o,{},r);yield n.use(this.model).deleteMany({_in:{id:e.map((e=>e.id))}}),s=e}else s=yield n.use(this.model).deleteMany(o,null==e?void 0:e.returning);return{modified:s}}))}}t.ModelRepository=ModelRepository},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractSocketController=void 0;t.AbstractSocketController=class AbstractSocketController{constructor(e){this.channel=e}onChannelJoin(e){}onChannelLeave(e){}onMessage(e,t){}}},function(e,t){e.exports=require("redis")},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractServerSocket=void 0;const i=n(0);t.AbstractServerSocket=class AbstractServerSocket{constructor(e){this.socketInfo=e}getId(){return this.socketInfo.id}getAuthInfo(){return this.socketInfo.authInfo}send(e,t){t?this.socketInfo.channels.find((e=>e.name===t&&e.serverToClientAllowed))&&this.sendRaw({type:i.MessageType.PLAIN,data:{message:e,channel:t}}):this.sendRaw({type:i.MessageType.PLAIN,data:{message:e}})}sendRaw(e){this.physicSend(e)}disconnect(){this.physicClose()}removeChannels(e){this.socketInfo.channels=this.socketInfo.channels.filter((t=>!e.includes(t.name)))}addChannels(e){this.socketInfo.channels.push(...e)}getChannelsInfo(){return this.socketInfo.channels}}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractFileService=void 0;t.AbstractFileService=class AbstractFileService{}},function(e,t){e.exports=require("fs")},function(e,t){e.exports=require("path")},function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractDatabaseAdapter=void 0;const o=n(0);t.AbstractDatabaseAdapter=class AbstractDatabaseAdapter{constructor(){this.modelMetadata=[],this.models=[],this.modelConnections={}}init(){return i(this,void 0,void 0,(function*(){this.models=((0,o.getGlobalStore)().models||[]).slice(),this.modelMetadata=this.models.map((e=>(0,o.getObjectMetadata)(e))),this.modelConnections=this.modelMetadata.reduce(((e,t)=>Object.assign(e,{[t.id]:{connection:void 0}})),{})}))}exit(){}}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractDatabaseMigrator=void 0;t.AbstractDatabaseMigrator=class AbstractDatabaseMigrator{}},function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var o=Object.getOwnPropertyDescriptor(t,n);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,o)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),o=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||i(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),t.QueryTypes=void 0,o(n(38),t),o(n(19),t),o(n(39),t),o(n(40),t),o(n(6),t),o(n(8),t),o(n(20),t),o(n(7),t),o(n(41),t),o(n(9),t),o(n(43),t),o(n(44),t),o(n(2),t),o(n(45),t),o(n(4),t),o(n(23),t),o(n(26),t),o(n(27),t),o(n(1),t),o(n(13),t),o(n(46),t),o(n(47),t),o(n(48),t),o(n(28),t),o(n(49),t),o(n(50),t),o(n(15),t),o(n(5),t),o(n(51),t),o(n(53),t),o(n(55),t),o(n(29),t),o(n(16),t),o(n(14),t),o(n(56),t),o(n(57),t),o(n(58),t),o(n(59),t),o(n(60),t),o(n(65),t),o(n(66),t),o(n(11),t),o(n(67),t),o(n(68),t),o(n(32),t),o(n(24),t),o(n(69),t),o(n(70),t),o(n(71),t),o(n(12),t),o(n(72),t),o(n(17),t),o(n(73),t),o(n(35),t),o(n(74),t),o(n(76),t),o(n(36),t);var r=n(18);Object.defineProperty(t,"QueryTypes",{enumerable:!0,get:function(){return r.QueryTypes}})},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FileOperation=void 0,function(e){e.GET="getObject",e.PUT="putObject",e.DELETE="deleteObject"}(t.FileOperation||(t.FileOperation={}))},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},function(e,t,n){"use strict";var i=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},o=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},r=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))},s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultHttpRequestHandler=void 0;const a=n(0),d=s(n(21)),c=n(42),l=s(n(22)),u=n(8),h=n(7),p=n(1),f=n(2),g=n(11);let y=class DefaultHttpRequestHandler extends f.AbstractHttpRequestHandler{constructor(e,t){super("",e),this.logger=e,this.authorizationProvider=t}accessControl(e,t){return r(this,void 0,void 0,(function*(){if(e.endpointMetadata.httpMethod!==a.SocketMethod.MESSAGE){const n=yield this.authorizationProvider.resolvePrincipal(t);if(t.setAuthInfo(n),!e.endpointMetadata.openAccess&&(yield this.authorizationProvider.authorize(n,t,e),e.endpointMetadata.tfaRequired&&!(null==n?void 0:n.hasTfa)))throw a.ErrorBuilder.error(g.Errors.TFA_REQUIRED)}}))}handleRequest(e,t){return r(this,void 0,void 0,(function*(){yield this.accessControl(e,t);const n=Object.values(e.endpointMetadata.params||{}).map((e=>{switch(e.source){case"body":return t.getBody();case"params":return t.getParams();case"queries":return t.getQuery();case"headers":return t.getHeaders();case"raw":return t}})),i=yield e.endpoint.controller[e.endpointMetadata.name](...n);return e.endpointMetadata.responseValidationDto&&(i.value=(0,a.stripData)(i.value,e.endpointMetadata.responseValidationDto)),i}))}exit(){}handle(e){return r(this,void 0,void 0,(function*(){const t=e.method,n=(0,d.default)({url:e.fullPath});let i={};const o=(yield this.getMountedEndpointInfo()).find((e=>{const o=e.endpointMetadata.httpMethod===t&&(0,c.match)(e.endpointMetadata.url,{decode:decodeURIComponent})(n.pathname);return!!o&&(i=o,!0)}));if(!o)throw this.logger.debug(e),a.ErrorBuilder.error(g.Errors.NOT_FOUND,"Handler not found");const r=new h.HttpRequest({method:t,headers:e.headers,pathName:n.pathname||"",hash:n.hash||"",query:l.default.parse(decodeURIComponent(n.search||"")),params:i.params,body:e.body},o.endpointMetadata);let s;try{for(const e of this.getMiddleware())if(s=yield e.intercept(r),s)break;if(s||(s=yield this.handleRequest(o,r)),!(s&&s instanceof u.HttpResponse))throw a.ErrorBuilder.systemError(`Invalid response value returned ${o.endpoint.httpMethod}:${o.endpoint.mount}, required instance of ${u.HttpResponse.name}, found ${s?null==s?void 0:s.constructor.name:s}`)}catch(e){this.logger.error(e),s=u.ResponseBuilder.json({name:e.name,message:e.message}).status([g.Errors.ACCESS_DENIED,g.Errors.AUTHENTICATION_ERROR,g.Errors.SESSION_EXPIRED].includes(e.name)?401:[g.Errors.SYSTEM_ERROR,g.Errors.CANNOT_LOCK].includes(e.name)?500:400).get()}return s}))}getMiddleware(){return[]}};y=i([(0,a.Injectable)(),o("design:paramtypes",[a.AbstractLogger,p.AbstractHttpAuthorizationProvider])],y),t.DefaultHttpRequestHandler=y},function(e,t){e.exports=require("path-to-regexp")},function(e,t,n){"use strict";var i=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},o=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},r=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}},s=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.CrudHttpController=void 0;const a=n(0),d=n(23),c=n(7),l=n(24),u=n(12),h=n(20),p=n(9),f=n(1),g=n(8),y=n(26),v=n(27);class CrudHttpController extends p.AbstractHttpController{constructor(e,t,n){super(n),this.model=e,this.crudRepository=t,this.databaseAdapter=n,this.modelMetadata=(0,a.getObjectMetadata)(e)}getMountedUrl(){return`/${this.model.name.toLowerCase()}`}static queryFieldDto(e){const t={id:"",fields:CrudHttpController.getRequestQueryFieldFromModel(e)},n={name:"fields",description:"Filter records by value of their fields."};return n.dataType=a.DataType.OBJECT,n.elementDto=t,n}static projectionFieldDto(e){const t={name:"projection",description:"Project the returning records to contain only certain fields. Omit to return all."};return t.dataType=a.DataType.ARRAY,t.vectorProps={superSet:e.fields.map((e=>e.name)),allowDuplicated:!1,minLength:1,elementDataType:a.DataType.STRING},t}static getBodyDtoRecordClass(e,t,n){const i={id:"",fields:[]};let o=e.fields.filter((e=>!e.hasMany));o="get_response"===t||"query"===t?o:"create_response"===t?o.filter((e=>e.pk||e.serverValue)):"create_body"===t||"update_body"===t?o.filter((e=>{var t;return!e.serverValue&&!(null===(t=e.pk)||void 0===t?void 0:t.isAutoIncrement)||!!n&&!n.fields.find((t=>{var n;return(null===(n=t.hasMany)||void 0===n?void 0:n.column)===e.name}))})):[];const r=e.fields.filter((e=>!!e.hasMany));return i.fields.push(...o.map((e=>Object.assign(Object.assign({},e),{elementDto:e.elementDto&&("update_body"===t?(0,a.partialize)(e.elementDto):e.elementDto),isRequired:!("query"===t||"update_body"===t||"get_response"===t&&!n)&&e.isRequired}))),...r.map((n=>{var i;const o=CrudHttpController.getBodyDtoRecordClass(n.hasMany.relationDto,t,e);return{description:`All records of "${null===(i=n.hasMany)||void 0===i?void 0:i.relationDto.id}" table in this relationship.`,name:n.name,dataType:a.DataType.ARRAY,isRequired:"create_response"===t,vectorProps:{elementDataType:a.DataType.OBJECT,minLength:0},elementDto:Object.assign(Object.assign({},o),{fields:("create_body"===t||"update_body"===t?o.fields.filter((e=>{var t;return e.name!==(null===(t=n.hasMany)||void 0===t?void 0:t.column)})):o.fields).map((e=>"update_body"===t?Object.assign(Object.assign({},e),{isRequired:!1,allowNull:!0}):e))})}}))),i}static getRequestQueryFieldFromModel(e){return e.fields.map((e=>{const t={};if(t.name=e.name,t.description=e.description,t.isRequired=!1,e.pk||e.fk||e.isSymbol)t.dataType=a.DataType.ARRAY,t.vectorProps={elementDataType:e.dataType,allowDuplicated:!1,allowNull:e.allowNull,minLength:1};else if(e.hasMany){const n={id:"",fields:CrudHttpController.getRequestQueryFieldFromModel(e.hasMany.relationDto).filter((t=>{var n;return t.name!==(null===(n=e.hasMany)||void 0===n?void 0:n.column)})),relaxed:!0};t.dataType=a.DataType.OBJECT,t.elementDto=n}else if(e.enum)t.dataType=a.DataType.ARRAY,t.vectorProps={superSet:e.enum,allowDuplicated:!1,minLength:1,elementDataType:e.dataType,allowNull:e.allowNull};else switch(e.dataType){case a.DataType.STRING:t.dataType=a.DataType.STRING;break;case a.DataType.NUMBER:t.dataType=a.DataType.OBJECT,t.elementDto=(0,a.getObjectMetadata)(a.RangeQueryDto)}return t}))}getAuthProvider(){return s(this,void 0,void 0,(function*(){if(void 0===this.authProvider){const e=(0,a.getServiceProvider)().getInjector();this.authProvider=e.resolveOptional(f.AbstractHttpAuthorizationProvider)||null,yield e.initInstances()}return this.authProvider}))}createManyEndpoinMetadata(){const e={};return e.httpMethod=a.HttpMethod.POST,e.url=this.getMountedUrl(),e.name=CrudHttpController.prototype.createMany.name,e.displayName="createMany"+this.model.name,e.bodyValidationDto=CrudHttpController.getCreateManyBodyValidator(this.modelMetadata),e.responseValidationDto=CrudHttpController.getCreateManyResponseValidator(this.modelMetadata),e.accessConditions=[(0,v.DtoFieldValidation)(this.model,(e=>e.getBody().records))],e.params={0:{source:"raw"}},e}getManyEndpointMetadata(){const e={};return e.httpMethod=a.HttpMethod.GET,e.url=this.getMountedUrl(),e.name=CrudHttpController.prototype.getMany.name,e.displayName="getAll"+this.model.name,e.queriesValidationDto=CrudHttpController.getGetManyQueryValidator(this.modelMetadata),e.responseValidationDto=CrudHttpController.getGetManyResponseValidator(this.modelMetadata),e.accessConditions=[(0,v.DtoFieldValidation)(this.model,(e=>[e.getQuery().fields])),(0,d.FilterModelFieldAccessCondition)(this.model,(e=>e.getQuery().projection)),y.MaximumQueryLimit],e.params={0:{source:"raw"}},e}updateManyEndpoinMetadata(){const e={};return e.httpMethod=a.HttpMethod.PUT,e.url=this.getMountedUrl(),e.name=CrudHttpController.prototype.updateMany.name,e.displayName="update"+this.model.name,e.queriesValidationDto=CrudHttpController.getUpdateManyQueryValidator(this.modelMetadata),e.bodyValidationDto=CrudHttpController.getUpdateManyBodyValidator(this.modelMetadata),e.responseValidationDto=CrudHttpController.getUpdateManyResponseValidator(this.modelMetadata),e.accessConditions=[(0,d.FilterModelFieldAccessCondition)(this.model,(e=>{const t=e.getBody().update;return t?Object.keys((0,a.leanData)(t)):[]})),(0,v.DtoFieldValidation)(this.model,(e=>[e.getQuery().fields]),"dto_field_validation_query"),(0,v.DtoFieldValidation)(this.model,(e=>[e.getBody().update]),"dto_field_validation_body")],e.params={0:{source:"raw"}},e}deleteManyEndpoinMetadata(){const e={};return e.httpMethod=a.HttpMethod.DEL,e.url=this.getMountedUrl(),e.name=CrudHttpController.prototype.deleteMany.name,e.displayName="delete"+this.model.name,e.queriesValidationDto=CrudHttpController.getUpdateManyQueryValidator(this.modelMetadata),e.responseValidationDto=CrudHttpController.getUpdateManyResponseValidator(this.modelMetadata),e.params={0:{source:"raw"}},e.accessConditions=[(0,v.DtoFieldValidation)(this.model,(e=>[e.getQuery().fields]))],e}static getCreateManyBodyValidator(e){const t={id:"",fields:[]},n={name:"records",description:"Array of records to be created."};return n.dataType=a.DataType.ARRAY,n.isRequired=!0,n.vectorProps={elementDataType:a.DataType.OBJECT,minLength:0},n.elementDto=CrudHttpController.getBodyDtoRecordClass(e,"create_body"),t.fields.push(n),t}static getCreateManyResponseValidator(e){const t={id:"",fields:[]},n={name:"records",description:"Array of records had just been created."};return n.dataType=a.DataType.ARRAY,n.isRequired=!0,n.vectorProps={elementDataType:a.DataType.OBJECT,minLength:0},n.elementDto=CrudHttpController.getBodyDtoRecordClass(e,"create_response"),t.fields.push(n),t}static getGetManyResponseValidator(e){const t={id:"",fields:[]},n={name:"total",description:"Number of records found, zero is returned if the request is not paged."};n.dataType=a.DataType.NUMBER,n.isRequired=!0,t.fields.push(n);const i={name:"records",description:"The found records. All records will be returned if the request is not paged."};return i.dataType=a.DataType.ARRAY,i.isRequired=!0,i.vectorProps={elementDataType:a.DataType.OBJECT,minLength:0},i.elementDto=CrudHttpController.getBodyDtoRecordClass(e,"get_response"),t.fields.push(i),t}static getGetManyQueryValidator(e){const t={id:"",fields:[CrudHttpController.queryFieldDto(e)]},n={name:"search",description:"Filter records for their @Searchable denoted fields."};n.dataType=a.DataType.STRING,t.fields.push(n),t.fields.push(CrudHttpController.projectionFieldDto(e));const i={name:"order",description:"Sort the dataset before getting result by order given in the array. Field appears first in the array will be sorted first."};i.dataType=a.DataType.ARRAY,i.vectorProps={elementDataType:a.DataType.OBJECT,minLength:1};const o={id:"",fields:[]};o.fields.push(...e.fields.filter((e=>!e.hasMany)).map((e=>{const t={};return t.name=e.name,t.isRequired=!1,t.dataType=a.DataType.STRING,t.enum=["asc","desc"],t}))),i.elementDto=o,t.fields.push(i);const r={name:"limit",description:"Limit the number of returning result."};r.dataType=a.DataType.NUMBER,r.rangeProps={min:1},t.fields.push(r);const s={name:"page",description:"Page the returning result, default to 1 if ommited. Has no effect if limit is not set."};return s.dataType=a.DataType.NUMBER,s.rangeProps={min:1},t.fields.push(s),t}static getUpdateManyQueryValidator(e){const t={name:"returning",description:"Whether to return the affected records by this request."};return t.dataType=a.DataType.BOOLEAN,t.isRequired=!1,{id:"",fields:[t,CrudHttpController.queryFieldDto(e)]}}static getUpdateManyBodyValidator(e){const t={id:"",fields:[]},n={name:"update",isRequired:!0,description:"The update data to apply to found records."};return n.dataType=a.DataType.OBJECT,n.elementDto=CrudHttpController.getBodyDtoRecordClass(e,"update_body"),t.fields.push(n),t}static getUpdateManyResponseValidator(e){const t={id:"",fields:[]},n={name:"modified",description:"Array of affected records."};return n.dataType=a.DataType.ARRAY,n.vectorProps={minLength:0,elementDataType:a.DataType.OBJECT},n.elementDto=n.elementDto=CrudHttpController.getBodyDtoRecordClass(e,"get_response"),t.fields.push(n),t}getEndpointMetadata(){var e,t,n,i;let o=super.getEndpointMetadata();const r=[];(null===(e=this.modelMetadata.ignoreCrud)||void 0===e?void 0:e.includes(a.HttpMethod.GET))?o=o.filter((e=>e.name!==CrudHttpController.prototype.getMany.name)):r.push(this.getManyEndpointMetadata()),(null===(t=this.modelMetadata.ignoreCrud)||void 0===t?void 0:t.includes(a.HttpMethod.POST))?o=o.filter((e=>e.name!==CrudHttpController.prototype.createMany.name)):r.push(this.createManyEndpoinMetadata()),(null===(n=this.modelMetadata.ignoreCrud)||void 0===n?void 0:n.includes(a.HttpMethod.PUT))?o=o.filter((e=>e.name!==CrudHttpController.prototype.updateMany.name)):r.push(this.updateManyEndpoinMetadata()),(null===(i=this.modelMetadata.ignoreCrud)||void 0===i?void 0:i.includes(a.HttpMethod.DEL))?o=o.filter((e=>e.name!==CrudHttpController.prototype.deleteMany.name)):r.push(this.deleteManyEndpoinMetadata());for(const e of r){const t=o.findIndex((t=>t.httpMethod===e.httpMethod&&t.url===e.url||t.name===e.name&&(!t.httpMethod||!t.url)));t>=0?o[t]=Object.assign(Object.assign(Object.assign({},e),o[t]),{accessConditions:[...e.accessConditions||[],...o[t].accessConditions||[]]}):o.push(e)}return o}createMany(e){return s(this,void 0,void 0,(function*(){const t=yield this.getCurrentTransaction(),n=yield this.getAuthProvider(),i=n&&(yield n.resolvePrincipal(e)),o=yield this.crudRepository.createMany({principal:i,body:e.getBody(),tx:t});return g.ResponseBuilder.json(o).get()}))}getMany(e){return s(this,void 0,void 0,(function*(){const t=yield this.crudRepository.getMany({queries:e.getQuery(),queryProvider:this.databaseAdapter});return g.ResponseBuilder.json(t).get()}))}updateMany(e){return s(this,void 0,void 0,(function*(){const t=yield this.getCurrentTransaction(),n=yield this.getAuthProvider(),i=n&&(yield n.resolvePrincipal(e)),o=yield this.crudRepository.updateMany({principal:i,queries:e.getQuery(),body:e.getBody(),tx:t});return g.ResponseBuilder.json(o).get()}))}deleteMany(e){return s(this,void 0,void 0,(function*(){const t=yield this.getCurrentTransaction(),n=yield this.crudRepository.deleteMany({queries:e.getQuery(),tx:t});return g.ResponseBuilder.json({modified:n.modified.map((e=>e.id)).map((e=>({id:e})))}).get()}))}}i([(0,l.Transactional)(u.TransactionLink.INHERIT_OR_CREATE),(0,h.ApiDescription)("Create records of this table."),(0,h.AccessCondition)([]),r(0,(0,h.Raw)()),o("design:type",Function),o("design:paramtypes",[c.HttpRequest]),o("design:returntype",Promise)],CrudHttpController.prototype,"createMany",null),i([(0,h.AccessCondition)([]),(0,h.ApiDescription)("Get records of this table."),r(0,(0,h.Raw)()),o("design:type",Function),o("design:paramtypes",[c.HttpRequest]),o("design:returntype",Promise)],CrudHttpController.prototype,"getMany",null),i([(0,l.Transactional)(u.TransactionLink.INHERIT_OR_CREATE),(0,h.ApiDescription)("Find and update records which match search condition."),(0,h.AccessCondition)([]),r(0,(0,h.Raw)()),o("design:type",Function),o("design:paramtypes",[c.HttpRequest]),o("design:returntype",Promise)],CrudHttpController.prototype,"updateMany",null),i([(0,l.Transactional)(u.TransactionLink.INHERIT_OR_CREATE),(0,h.ApiDescription)("Find and remove records which match search condition."),(0,h.AccessCondition)([]),r(0,(0,h.Raw)()),o("design:type",Function),o("design:paramtypes",[c.HttpRequest]),o("design:returntype",Promise)],CrudHttpController.prototype,"deleteMany",null),t.CrudHttpController=CrudHttpController},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractHttpMiddleware=void 0;t.AbstractHttpMiddleware=class AbstractHttpMiddleware{}},function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.RedisRbacAuthProvider=void 0;const o=n(13);class RedisRbacAuthProvider extends o.AbstractRbacAuthProvider{constructor(e,t,n,i,o,r,s,a=3e4){super(i,o,s),this.serviceId=e,this.rbacChannel=t,this.principalChannel=n,this.authDataResolver=i,this.principalResolver=o,this.cacheService=r,this.logger=s,this.redisDataRetentionDurationMs=a,this.lastRbacFetchTimestamp=0,this.principalCache={}}getRbacCache(){return i(this,void 0,void 0,(function*(){if(this.lastRbacFetchTimestamp+this.redisDataRetentionDurationMs<Date.now()){const e=yield this.cacheService.hget(this.rbacChannel,this.serviceId);this.rbacCache=e,this.lastRbacFetchTimestamp=Date.now()}return this.rbacCache}))}getRolesOfPrincipal(e){return i(this,void 0,void 0,(function*(){const t=String(e.id);let n=this.principalCache[t];if(!n||n.lastFetchTimestamp+this.redisDataRetentionDurationMs<Date.now()){const e=yield this.cacheService.hget(this.principalChannel,t),i=e?"string"==typeof e?JSON.parse(e):e:[];n={lastFetchTimestamp:Date.now(),roles:i},this.principalCache[t]=n}return n.roles}))}}t.RedisRbacAuthProvider=RedisRbacAuthProvider},function(e,t,n){"use strict";var i=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},o=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},r=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.SocketRbacAuthProvider=void 0;const s=n(0),a=n(13),d=n(19);let c=class SocketRbacAuthProvider extends a.AbstractRbacAuthProvider{constructor(e,t,n,i,o,r){super(n,i,o),this.rbacCacheChannel=e,this.principalCacheChannel=t,this.authDataResolver=n,this.principalResolver=i,this.logger=o,this.socketProvider=r,this.idResolvers=[]}exit(){var e;null===(e=this.socket)||void 0===e||e.close()}init(){return r(this,void 0,void 0,(function*(){this.socket=yield this.socketProvider(),this.socket.onMessage(((e,t)=>{switch(t){case this.rbacCacheChannel:this.rbacCache=e;break;case this.principalCacheChannel:const{principalId:t,roleIds:n}=e,i=this.idResolvers.find((e=>e.principalId===t));if(i){for(const e of i.resolvers)e(n);i.resolvers=[]}}})),this.socket.joinChannels([this.rbacCacheChannel,this.principalCacheChannel])}))}getRbacCache(){return r(this,void 0,void 0,(function*(){return this.rbacCache}))}getRolesOfPrincipal(e){return r(this,void 0,void 0,(function*(){return new Promise((t=>{var n;let i=this.idResolvers.find((t=>t.principalId===e.id));i||(i={principalId:e.id,resolvers:[]},this.idResolvers.push(i)),i.resolvers.length||null===(n=this.socket)||void 0===n||n.send(e.id,this.principalCacheChannel),i.resolvers.push(t)}))}))}};c=i([(0,s.Initable)(),o("design:paramtypes",[String,String,Function,d.AbstractPrincipalResolver,s.AbstractLogger,Function])],c),t.SocketRbacAuthProvider=c},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.DtoRepository=t.MultipleMap=t.SingleMap=void 0;const o=n(0),r=n(15),s=n(28);t.SingleMap=(e,t,n,i,o)=>({multiple:!1,modelClass:e,forwardOps:t,forwardMapping:e=>{const t=n(e[0]||{});return t&&[t]},rootMapping:e=>{const t=e&&e[0];return i(t)},nestedMapping:o});t.MultipleMap=(e,t,n,i,o)=>({multiple:!0,modelClass:e,forwardOps:t,forwardMapping:n,rootMapping:i,nestedMapping:o});class DtoRepository extends r.AbstractRepository{constructor(e,t){super(e),this.model=e,this.dissolver=t}getMapValue(e,t,n,r,s){return i(this,void 0,void 0,(function*(){for(const i of n){const n=yield t(i);let a=r?yield r(i,i.forwardMapping(n),n):i.forwardMapping(n);if(i.nestedMapping&&a)for(const n of a)yield this.getMapValue(e,t,i.nestedMapping(n),r,s);s&&(a=yield s(i,i.forwardMapping(n),n));const d=i.rootMapping(a);(0,o.deepMerge)(e,d)}}))}createMany({principal:e,body:t,tx:n}){return i(this,void 0,void 0,(function*(){const r=[];yield this.beforeCreating(e,t.records);for(const a of t.records)yield this.getMapValue(a,(e=>i(this,void 0,void 0,(function*(){const t=new s.ModelRepository(e.modelClass);return(yield t.getMany({ops:e.forwardOps(),queryProvider:n})).records}))),this.dissolver(a),((t,r,a)=>i(this,void 0,void 0,(function*(){if(!r)return[];const i=new s.ModelRepository(t.modelClass),d=t.forwardOps();if(t.multiple){yield i.deleteMany({ops:d,tx:n});return(yield i.createMany({principal:e,body:{records:r},tx:n})).records}{const s=r[0];if(!s)return[];if(0===a.length){return(yield i.createMany({principal:e,body:{records:r},tx:n})).records}if(1===a.length){const t=yield i.updateMany({principal:e,ops:d,body:{update:s},tx:n});return[Object.assign(Object.assign(Object.assign({},a[0]),s),t.modified[0])]}throw o.ErrorBuilder.validationError(`Found multiple record when creating ${t.modelClass.name}`)}})))),r.push(a);return{records:r}}))}updateMany({principal:e,queries:t,ops:n,body:r,tx:a}){var d;return i(this,void 0,void 0,(function*(){if(!(null===(d=null==t?void 0:t.fields)||void 0===d?void 0:d.id)||1!==t.fields.id.length)throw o.ErrorBuilder.validationError("Missing required id field in query");const c=Object.assign(Object.assign({},r.update),{id:t.fields.id[0]});yield this.beforeCreating(e,[c]),yield this.getMapValue(c,(e=>i(this,void 0,void 0,(function*(){const t=new s.ModelRepository(e.modelClass);return(yield t.getMany({ops:e.forwardOps(n),queryProvider:a})).records}))),this.dissolver(c),((t,o,r)=>i(this,void 0,void 0,(function*(){if(!o)return[];const i=new s.ModelRepository(t.modelClass),d=t.forwardOps(n);if(t.multiple){yield i.deleteMany({ops:d,tx:a});return(yield i.createMany({principal:e,body:{records:o},tx:a})).records}{const t=o[0];return t?0==r.length?[]:(r.length>1?(yield i.deleteMany({ops:d,tx:a}),yield i.createMany({principal:e,body:{records:[t]},tx:a})):yield i.updateMany({principal:e,ops:d,body:{update:t},tx:a}),r.map((e=>Object.assign(Object.assign({},e),t)))):[]}}))));let l=["id"];return t.returning&&(l=[...l,...Object.keys(r.update).filter((e=>void 0!==r.update[e]))]),{modified:c.id?this.project([c],l):[]}}))}getMany({queries:e,ops:t,queryProvider:n}){var r;return i(this,void 0,void 0,(function*(){if(!(null===(r=null==e?void 0:e.fields)||void 0===r?void 0:r.id)||1!==e.fields.id.length)throw o.ErrorBuilder.validationError("Missing required id field in query");const a={id:e.fields.id[0]};return yield this.getMapValue(a,(()=>i(this,void 0,void 0,(function*(){return[]}))),this.dissolver(a),(e=>i(this,void 0,void 0,(function*(){const i=new s.ModelRepository(e.modelClass);return(yield i.getMany({ops:e.forwardOps(t),queryProvider:n})).records})))),a.id?{records:this.project([a],e.projection),total:1}:{records:[],total:0}}))}deleteMany({queries:e,ops:t,tx:n}){var r;return i(this,void 0,void 0,(function*(){if(!(null===(r=null==e?void 0:e.fields)||void 0===r?void 0:r.id)||1!==e.fields.id.length)throw o.ErrorBuilder.validationError("Missing required id field in query");const a={id:e.fields.id[0]};return yield this.getMapValue(a,(()=>i(this,void 0,void 0,(function*(){return[]}))),this.dissolver(a),void 0,(o=>i(this,void 0,void 0,(function*(){const i=new s.ModelRepository(o.modelClass),r=o.forwardOps(t);return(yield i.deleteMany({queries:{returning:null==e?void 0:e.returning},ops:r,tx:n})).modified})))),{modified:a.id?[a]:[]}}))}}t.DtoRepository=DtoRepository},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},function(e,t,n){"use strict";var i=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},o=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},r=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))},s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.LocalSocketManager=void 0;const a=n(0),d=s(n(52)),c=s(n(21)),l=s(n(22)),u=n(30),h=n(5),p=n(16),f=n(31),g=n(1);var y;!function(e){e.SEND="SEND",e.CLOSE="CLOSE",e.SAVE="SAVE"}(y||(y={}));class RedisSocket extends f.AbstractServerSocket{constructor(e,t,n){super(n),this.socketChannelName=e,this.redisClient=t,this.socketInfo=n}physicSend(e){this.redisClient.publish(this.socketChannelName,JSON.stringify({type:y.SEND,data:e}))}physicClose(){this.redisClient.publish(this.socketChannelName,JSON.stringify({type:y.CLOSE}))}saveSocketInfo(){return new Promise(((e,t)=>this.redisClient.publish(this.socketChannelName,JSON.stringify({type:y.SAVE,data:this.socketInfo}),(n=>n?t(n):e))))}}class ExpressSocket extends f.AbstractServerSocket{constructor(e,t,n){super(t),this.socket=e,this.socketInfo=t,this.infoSaver=n}saveSocketInfo(){return r(this,void 0,void 0,(function*(){yield this.infoSaver(this.socketInfo)}))}physicSend(e){this.socket.send(JSON.stringify(e))}physicClose(){this.socket.close()}}let v=class LocalSocketManager extends h.AbstractServerSocketManager{constructor(e,t,n,i,o){super(e,n,t,o,i),this.authenticationRequired=e,this.redisClient=t,this.logger=n,this.authProvider=i,this.connectionHandler=o,this.allSockets=[],this.subClient=this.redisClient.duplicate(),this.channelSubClient=this.redisClient.duplicate(),this.sendClient=this.redisClient.duplicate(),this.channelSubClient.on("message",((e,t)=>{this.logger.debug("channelSubClient",e,t,typeof t);e.substring(this.getUniqueChannelPrefix().length);const n=JSON.parse(t);n.type===a.MessageType.PLAIN&&this.allSockets.forEach((e=>{e.send(n.data.message,n.data.channel)}))})),this.subClient.on("message",((e,t)=>{this.logger.debug("Receiving message from remote socket channel",e,t);const n=e.substring(this.getSocketChannelKeyPrefix().length),i=this.allSockets.find((e=>e.getId()===n));if(i){const e=JSON.parse(t);switch(e.type){case y.SEND:i.physicSend(e.data);break;case y.SAVE:i.socketInfo.channels=e.data,i.saveSocketInfo();break;case y.CLOSE:i.disconnect();break;default:this.logger.debug("Invalid remote command",e)}}}))}init(){return r(this,void 0,void 0,(function*(){}))}exit(){this.redisClient.quit(),this.subClient.quit(),this.sendClient.quit(),this.channelSubClient.quit()}getSocketChannelKeyPrefix(){return"SOCKET_CHANNEL:"}getSocketInfoHashKey(){return"__SOCKET_INFO__"}getSocketChannelKey(e){return`${this.getSocketChannelKeyPrefix()}${e}`}createCustomChannel(e){return r(this,void 0,void 0,(function*(){}))}broadcastToChannel(e,t){return r(this,void 0,void 0,(function*(){const n=this.formatBroadcastData(e,t);return new Promise(((t,i)=>this.redisClient.publish(this.getUniqueChannelName(e),JSON.stringify(n),(e=>e?i(e):t()))))}))}addSocketToChannel(e,t){const n=Object.create(null,{addSocketToChannel:{get:()=>super.addSocketToChannel}});return r(this,void 0,void 0,(function*(){yield n.addSocketToChannel.call(this,e,t),yield Promise.all(t.map((e=>new Promise(((t,n)=>this.channelSubClient.subscribe(this.getUniqueChannelName(e.name),(e=>e?n(e):t())))))))}))}removeSocketFromChannel(e,t){const n=Object.create(null,{removeSocketFromChannel:{get:()=>super.removeSocketFromChannel}});return r(this,void 0,void 0,(function*(){yield n.removeSocketFromChannel.call(this,e,t),yield Promise.all(t.map((e=>new Promise(((t,n)=>this.channelSubClient.unsubscribe(this.getUniqueChannelName(e),(e=>e?n(e):t())))))))}))}addSocket(e,{socket:t}){return r(this,void 0,void 0,(function*(){const n=new ExpressSocket(t,e,(e=>new Promise(((t,n)=>this.redisClient.hset(this.getSocketInfoHashKey(),e.id,JSON.stringify(e),(e=>e?n(e):t())))))),i=this.getSocketChannelKey(e.id);return this.subClient.subscribe(i),this.allSockets.push(n),n}))}removeSocket(e){return r(this,void 0,void 0,(function*(){this.redisClient.hdel(this.getSocketInfoHashKey(),e),this.allSockets=this.allSockets.filter((t=>t.getId()!==e))}))}getById(e){return r(this,void 0,void 0,(function*(){let t=this.allSockets.find((t=>t.getId()===e));if(!t){const n=yield new Promise((t=>this.redisClient.hget(this.getSocketInfoHashKey(),e,((e,n)=>t(n?JSON.parse(n):void 0)))));n&&(t=new RedisSocket(this.getSocketChannelKey(e),this.sendClient,n))}return t}))}getSocketsByChannel(e){return r(this,void 0,void 0,(function*(){const t=yield this.getSocketIdsOfChannel(e);return(yield Promise.all(t.map((e=>this.getById(e))))).filter((e=>!!e))}))}configure(e){if(!e)return;this.logger.debug("Local socket manager configure");new d.default.Server({server:e}).on("connection",((e,t)=>{const n=t.headers["sec-websocket-key"],i=(0,c.default)({url:t.url}),o=l.default.parse(decodeURIComponent(i.search||""));this.handle({method:a.SocketMethod.CONNECT,socketId:n,data:{auth:o.auth,socket:e}}).catch((t=>{e.close(1e3,t.name)})),e.onmessage=e=>{this.handle({method:a.SocketMethod.MESSAGE,socketId:n,data:e.data}).catch((e=>{this.logger.error(e)}))},e.onclose=()=>{this.handle({method:a.SocketMethod.DISCONNECT,socketId:n}).catch((e=>{this.logger.error(e)}))}}))}};v=i([(0,a.Initable)(),o("design:paramtypes",[Boolean,u.RedisClient,a.AbstractLogger,g.AbstractHttpAuthorizationProvider,p.AbstractSocketConnectionHandler])],v),t.LocalSocketManager=v},function(e,t){e.exports=require("ws")},function(e,t,n){"use strict";var i=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},o=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},r=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))},s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.AwsSocketManager=void 0;const a=n(0),d=n(30),c=s(n(54)),l=n(2),u=n(5),h=n(31),p=n(1),f=n(16);class ApiGatewaySocket extends h.AbstractServerSocket{constructor(e,t,n,i,o,r){super(n),this.socketManager=e,this.logger=t,this.socketInfo=n,this.apiGateway=i,this.socketNamespace=o,this.redisClient=r}saveSocketInfo(){return r(this,void 0,void 0,(function*(){return new Promise(((e,t)=>this.redisClient.hset(this.socketNamespace,this.socketInfo.id,JSON.stringify(this.socketInfo),(n=>n?t(n):e()))))}))}physicSend(e){this.socketManager.physicSend(this.getId(),e).catch((e=>this.logger.debug("Send error",e)))}physicClose(){this.apiGateway.deleteConnection({ConnectionId:this.getId()}).promise().catch((e=>this.logger.error(e)))}serialize(){return JSON.stringify(this.socketInfo)}}let g=class AwsSocketManager extends u.AbstractServerSocketManager{constructor(e,t,n,i,o,r,s,a){super(e,a,i,o,s),this.authenticationRequired=e,this.region=t,this.socketDomainUrl=n,this.redisClient=i,this.connectionHandler=o,this.httpRequestHandler=r,this.authorizationProvider=s,this.logger=a,this.apiGatewayManagement=new c.default.ApiGatewayManagementApi({region:t,apiVersion:"2018-11-29",endpoint:n})}init(){return r(this,void 0,void 0,(function*(){}))}exit(){this.redisClient.quit()}getSocketInfoHashKey(){return"__SOCKET_INFO__"}physicSend(e,t){return r(this,void 0,void 0,(function*(){try{yield this.apiGatewayManagement.postToConnection({ConnectionId:e,Data:JSON.stringify(t)}).promise(),this.logger.debug(`Socket ${e} send OK`,t)}catch(t){throw this.logger.debug(`Socket ${e} post error`,t),410===t.statusCode&&(this.logger.debug(`Stale socket ${e}`),this.logger.debug(`Disconnecting ${e}`),this.logger.debug(`Removing socket ${e}`),yield this.removeSocket(e),this.logger.debug(`Socket removed ${e}`)),t}}))}configure(e){this.logger.debug("Aws socket manager configure")}createCustomChannel(e){return r(this,void 0,void 0,(function*(){}))}getSocketsByChannel(e){return r(this,void 0,void 0,(function*(){const t=yield this.getSocketIdsOfChannel(e);return(yield new Promise(((e,n)=>this.redisClient.hmget(this.getSocketInfoHashKey(),t,((t,i)=>t?n(t):e(i)))))).filter((e=>!!e)).map((e=>this.getSocketBySerialized(e)))}))}broadcastToChannel(e,t){return r(this,void 0,void 0,(function*(){const n=yield this.getSocketIdsOfChannel(e),i=this.formatBroadcastData(e,t);yield Promise.all(n.map((e=>this.physicSend(e,i))))}))}addSocket(e,t){return r(this,void 0,void 0,(function*(){const t=new ApiGatewaySocket(this,this.logger,e,this.apiGatewayManagement,this.getSocketInfoHashKey(),this.redisClient);return t.saveSocketInfo(),t}))}removeSocket(e){return new Promise(((t,n)=>this.redisClient.hdel(this.getSocketInfoHashKey(),e,(e=>e?n(e):t()))))}getSocketBySerialized(e){return new ApiGatewaySocket(this,this.logger,JSON.parse(e),this.apiGatewayManagement,this.getSocketInfoHashKey(),this.redisClient)}getById(e){return r(this,void 0,void 0,(function*(){const t=yield new Promise(((t,n)=>this.redisClient.hget(this.getSocketInfoHashKey(),e,((e,i)=>e?n(e):t(i)))));if(!t)throw a.ErrorBuilder.error(a.Errors.NOT_FOUND,"Cannot find socket with id: "+e);return this.logger.debug("Serialized aws socket",t),this.getSocketBySerialized(t)}))}};g=i([(0,a.Initable)(),o("design:paramtypes",[Boolean,String,String,d.RedisClient,f.AbstractSocketConnectionHandler,l.AbstractHttpRequestHandler,p.AbstractHttpAuthorizationProvider,a.AbstractLogger])],g),t.AwsSocketManager=g},function(e,t){e.exports=require("aws-sdk")},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},function(e,t,n){"use strict";var i=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},o=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},r=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.FileUploadHandler=void 0;const s=n(0),a=n(32),d=n(14);let c=class FileUploadHandler extends d.AbstractFileUploadHandler{constructor(e){super(),this.fileService=e}moveFile(e,t){return r(this,void 0,void 0,(function*(){yield this.fileService.moveObject(e,t)}))}removeFile(e){return r(this,void 0,void 0,(function*(){yield this.fileService.removeObject(e)}))}resolvePublicUrl(e){return r(this,void 0,void 0,(function*(){return this.fileService.getAccessUrl(e,!0)}))}resolvePrivateUrl(e){return r(this,void 0,void 0,(function*(){return this.fileService.getAccessUrl(e,!1)}))}};c=i([(0,s.Injectable)(),o("design:paramtypes",[a.AbstractFileService])],c),t.FileUploadHandler=c},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},function(e,t,n){"use strict";var i,o=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},r=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},s=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.FileLogMedium=void 0;const d=a(n(33)),c=a(n(34)),l=n(0);let u=i=class FileLogMedium{constructor(e){const t=e.separated?i.levels.map((t=>c.default.join(e.destination,t+".log"))):[e.destination];this.destination=t.map((e=>(d.default.existsSync(c.default.dirname(e))||d.default.mkdirSync(c.default.dirname(e),{recursive:!0}),d.default.openSync(e,"a")))),this.separated=!!e.separated}init(){return s(this,void 0,void 0,(function*(){}))}exit(){this.destination.forEach((e=>d.default.closeSync(e)))}write(e,t){const n=this.separated?this.destination[i.levels.indexOf(e)]:0;d.default.appendFileSync(n,t)}};u.levels=Object.values(l.LogLevel),u=i=o([(0,l.Initable)(),r("design:paramtypes",[Object])],u),t.FileLogMedium=u},function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.ClaireServer=void 0;const o=n(0),r=n(10),s=n(6);class ClaireServer extends o.ClaireApp{constructor(e,t,n){super(),this.logger=e,this.httpRequestHandler=t,this.socketManager=n,this.booted=!1}init(){return i(this,void 0,void 0,(function*(){if(this.booted)return;const e=[];if(this.httpRequestHandler){const t=yield this.httpRequestHandler.getMountedEndpointInfo();e.push(...t)}if(this.socketManager){const t=yield this.socketManager.getMountedEndpointInfo();e.push(...t)}for(const t of e)this.logger.info(`Mounting: ${(0,s.getEndpointId)(t.endpoint)}`);(0,o.getGlobalStore)().mountedEndpointInfo=e,this.logger.debug("Claire server initing"),this.logger.debug("Setting up exception handlers"),process.on("SIGTERM",(()=>(this.logger.warn("SIGTERM interrupt signal"),this.stop(r.ExitCode.SIGTERM_INTERUPTION)))),process.on("SIGINT",(()=>(this.logger.warn("SIGINT interrupt signal"),this.stop(r.ExitCode.SIGTERM_INTERUPTION)))),process.on("uncaughtException",(e=>{this.logger.error("uncaughtException",e.name,e.stack)})),process.on("unhandledRejection",(e=>{this.logger.error("unhandledRejection",e.name,e.stack)})),this.booted=!0}))}exit(){super.exit()}stop(e){this.logger.debug("Server is shutting down"),this.exit(),process.exit(e)}}t.ClaireServer=ClaireServer},function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ExpressWrapper=void 0;const r=n(0),s=o(n(61)),a=o(n(62)),d=o(n(63)),c=o(n(64)),l=n(5),u=n(2);t.ExpressWrapper=class ExpressWrapper{constructor(e,t){this.injector=(0,r.getServiceProvider)().getInjector(),this.server=e,this.config=t,this.logger=this.injector.resolve(r.AbstractLogger),this.socketManager=this.injector.resolveOptional(l.AbstractServerSocketManager),this.httpRequestHandler=this.injector.resolveOptional(u.AbstractHttpRequestHandler)}close(){var e;null===(e=this.httpServer)||void 0===e||e.close(),this.server.exit()}listen(e){var t,n;return i(this,void 0,void 0,(function*(){yield this.server.init(),yield this.injector.initInstances();const o=(0,s.default)(),l=a.default.createServer(o);return null===(t=this.socketManager)||void 0===t||t.configure(l),o.use((0,d.default)()),o.use(s.default.raw({limit:1024*((null===(n=this.config)||void 0===n?void 0:n.maxBodySizeKB)||4096)})),o.use((0,c.default)()),o.use(((e,t,n)=>{e.files&&(e.body||(e.body={}),Object.keys(e.files).forEach((t=>{e.body[t]=e.files[t]}))),n()})),o.use(s.default.urlencoded({extended:!1})),o.use(s.default.json()),o.all("*",((e,t)=>{(()=>i(this,void 0,void 0,(function*(){if(!!e.headers["x-amzn-apigateway-api-id"]){if(!this.socketManager)throw r.ErrorBuilder.systemError("Socket manager not found");const n={socketId:e.body.connectionId,data:e.body.data,method:e.body.type.toLowerCase()};yield this.socketManager.handle(n),t.status(200).send()}else{if(!this.httpRequestHandler)throw r.ErrorBuilder.systemError("Http request handler not found");const n={fullPath:e.url,method:e.method.toLowerCase(),headers:e.headers,body:e.body},i=yield this.httpRequestHandler.handle(n);i.headers&&Object.keys(i.headers).forEach((e=>{t.set(e,i.headers[e])})),t.status(i.code).send(i.value)}})))().catch((e=>{this.logger.error(e),t.status(400).json({name:e.name,message:e.message})}))})),new Promise(((t,n)=>{this.httpServer=l.listen(e,t).on("error",n)}))}))}}},function(e,t){e.exports=require("express")},function(e,t){e.exports=require("http")},function(e,t){e.exports=require("cors")},function(e,t){e.exports=require("express-fileupload")},function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.LambdaWrapper=void 0;const o=n(0),r=n(2),s=n(5),a=n(11),toApiGatewayFormat=(e,t)=>({statusCode:e,body:t&&JSON.stringify(t),headers:{"Access-Control-Allow-Headers":"*","Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"*","Content-Type":"application/json"}});t.LambdaWrapper=class LambdaWrapper{constructor(e,t){this.server=e,this.requestMapper=t,this.handler=this.handler.bind(this),this.injector=(0,o.getServiceProvider)().getInjector(),this.socketManager=this.injector.resolveOptional(s.AbstractServerSocketManager),this.httpRequestHandler=this.injector.resolveOptional(r.AbstractHttpRequestHandler)}handler(e){var t;return i(this,void 0,void 0,(function*(){yield this.server.init(),yield this.injector.initInstances(),null===(t=this.socketManager)||void 0===t||t.configure();const n=this.requestMapper(e);if(!n)return toApiGatewayFormat(400,"Cannot resolve event");if(n.method===o.HttpMethod.OPTIONS)return toApiGatewayFormat(200);try{if(Object.values(o.HttpMethod).includes(n.method)){if(!this.httpRequestHandler)throw o.ErrorBuilder.error(a.Errors.SYSTEM_ERROR,"Http request handler not found");const e={fullPath:n.rawPath,method:n.method,headers:n.headers,body:n.body},t=yield this.httpRequestHandler.handle(e);return toApiGatewayFormat(t.code,t.value)}if(!Object.values(o.SocketMethod).includes(n.method))throw o.ErrorBuilder.error(a.Errors.HTTP_REQUEST_ERROR,"Not allow request method: "+n.method);{if(!this.socketManager)throw o.ErrorBuilder.error(a.Errors.SYSTEM_ERROR,"Socket manager not found");const e={socketId:n.rawPath,method:n.method,data:n.body};yield this.socketManager.handle(e)}return toApiGatewayFormat(200)}catch(e){return toApiGatewayFormat(400,{name:e.name,message:e.message})}}))}}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractService=void 0;const o=n(3);t.AbstractService=class AbstractService{constructor(e){this.databaseAdapter=e}createTransaction(){return this.databaseAdapter.createTransaction()}getCurrentTransaction(){return i(this,void 0,void 0,(function*(){return(0,o.getTransactionFromContext)(this)}))}}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractCacheService=void 0;t.AbstractCacheService=class AbstractCacheService{}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t._is=t._join=t._max=t._min=t._avg=t._sum=t._count=void 0;t._count=(e,t)=>({fn:"count",field:e,args:t});t._sum=e=>({fn:"sum",field:e});t._avg=e=>({fn:"avg",field:e});t._min=e=>({fn:"min",field:e});t._max=e=>({fn:"max",field:e});t._join=(e,t)=>({fn:"join",field:e,args:t});t._is=e=>({fn:"is",field:e})},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},function(e,t,n){"use strict";var i=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},o=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},r=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSqlDatabaseAdapter=void 0;const s=n(0),a=n(18),d=n(25),c=n(35),l=n(75),u=n(17),h=n(3),getModelId=e=>{const t=(0,s.getObjectMetadata)(e);if(!t)throw s.ErrorBuilder.systemError(`Metadata for ${e.name} not found, check @Model decorator`);return t.id},p=["_and","_or"],convertOp=e=>[a.Op.and,a.Op.or,a.Op.eq,a.Op.ne,a.Op.gt,a.Op.lt,a.Op.gte,a.Op.lte,a.Op.regexp,a.Op.like,a.Op.in][["_and","_or","_eq","_neq","_gt","_lt","_gte","_lte","_regex","_sub","_in"].indexOf(e)],safetifyColumn=(e,t)=>{const n=t===u.SqlProvider.MYSQL?"`":'"';return e.split(".").map((e=>`${n}${e}${n}`)).join(".")},getAggregatorColumn=(e,t)=>{const n=safetifyColumn(e.field,t);switch(e.fn){case"count":return`${!0===e.args?`COUNT(DISTINCT(${n}))`:`COUNT(${n})`}${t===u.SqlProvider.POSTGRES?"::int":""}`;case"sum":return`SUM(${n})`;case"avg":return`AVG(${n})`;case"min":return`MIN(${n})`;case"max":return`MAX(${n})`;case"join":return t===u.SqlProvider.POSTGRES?`string_agg(${n}, '${e.args}')`:`GROUP_CONCAT(${n} SEPARATOR '${e.args}')`;case"is":return n;default:throw s.ErrorBuilder.systemError(`Not supported agg function: ${e.fn}`)}};class Joiner{constructor(e){this.adapter=e,this.joinInfo=[],this.columnId=0}join(e,t,n,i){return this.joinInfo.push({rightModel:e,leftField:t,rightField:n,joinMode:i||"inner"}),this}where(e){return this.queryCondition=e,this}groupBy(e){return this.groupByFields=e,this}having(e){return this.havingCondition=e,this}getExecuteCondition(){const e=[],t=this.convertHavingCondition(this.havingCondition||{},e);return{conditions:{where:this.adapter.getQueryObjectFromQueryConditions(this.queryCondition,!0),transaction:this.adapter.transaction,include:this.joinInfo.map((e=>{const t=(0,s.getTableName)(e.rightModel);return{attributes:[],model:this.adapter.modelConnections[t].connection,duplicating:!1,required:"inner"===e.joinMode,on:{[`$${e.leftField}$`]:{[convertOp("_eq")]:a.Sequelize.col(e.rightField)}}}})),group:this.groupByFields,attributes:this.adapter.sqlProvider===u.SqlProvider.POSTGRES?[]:e.map((e=>[a.Sequelize.literal(e.sequelizeColumn),e.columnId])),having:t,raw:!0},collector:e}}countWithCondition(e){var t;return r(this,void 0,void 0,(function*(){e.offset=0,e.limit=this.adapter.sqlProvider===u.SqlProvider.POSTGRES?1:0,e.attributes=[...this.adapter.sqlProvider===u.SqlProvider.MYSQL&&e.attributes||[],[this.adapter.sqlProvider===u.SqlProvider.POSTGRES?a.Sequelize.literal("(COUNT(*) OVER ())::int"):a.Sequelize.literal("COUNT(*)"),"count"]];const n=this.adapter.sqlProvider===u.SqlProvider.POSTGRES?yield this.adapter.getCurrentConnection().findAll(e):yield this.adapter.getCurrentConnection().count(e);return(null===(t=n[0])||void 0===t?void 0:t.count)||0}))}count(){return r(this,void 0,void 0,(function*(){const{conditions:e}=this.getExecuteCondition();return this.countWithCondition(e)}))}rows(e,t){return r(this,void 0,void 0,(function*(){const{conditions:n,collector:i}=this.getExecuteCondition();n.attributes=[...n.attributes||[],...Object.keys(e).map((t=>[a.Sequelize.literal(getAggregatorColumn(e[t],this.adapter.sqlProvider)),t]))],n.limit=null==t?void 0:t.limit,n.offset=(null==t?void 0:t.limit)&&t.limit*((t.page||1)-1);const o=yield this.adapter.getCurrentConnection().findAll(n);return{total:yield this.countWithCondition(Object.assign(Object.assign({},n),{attributes:i.map((e=>[a.Sequelize.literal(e.sequelizeColumn),e.columnId]))})),records:o}}))}convertHavingOperation(e,t){const n=getAggregatorColumn(t[0],this.adapter.sqlProvider);return{columnId:"col__"+this.columnId++,sequelizeColumn:n,sequelizeOps:{[convertOp(e)]:t[1]}}}convertHavingCondition(e,t){if(!e)return{};const n=Object.keys(e);if(!n.length)return{};const i=n.map((n=>{if(p.includes(n))return{[convertOp(n)]:e[n].map((e=>this.convertHavingCondition(e,t)))};{const i=this.convertHavingOperation(n,e[n]);return t.push(i),this.adapter.sqlProvider===u.SqlProvider.POSTGRES?a.Sequelize.where(a.Sequelize.literal(i.sequelizeColumn),i.sequelizeOps):{[i.columnId]:i.sequelizeOps}}}));return i.length>1?{[convertOp("_and")]:i}:i[0]}}class ModelAdapter extends l.AbstractQuery{constructor(e){super(e.model),this.dbConnection=e.dbConnection,this.modelConnections=e.modelConnections,this.transaction=e.transaction,this.sqlProvider=e.sqlProvider,this.logger=null==e?void 0:e.logger}getCurrentConnection(){const e=(0,s.getObjectMetadata)(this.model).id;return this.modelConnections[e].connection}resolveNestedIncludes(e){return e&&e.map((e=>({model:this.modelConnections[e.modelId].connection,where:this.getQueryObjectFromQueryConditions(e.queries)})))}join(e,t,n,i){const o=new Joiner(this);return o.join(e,t,n,i),o}count(e,t,n){return r(this,void 0,void 0,(function*(){const i={where:this.getQueryObjectFromQueryConditions(e),transaction:this.transaction,include:this.resolveNestedIncludes(n)};return(null==t?void 0:t.distinct)&&Object.assign(i,{distinct:!0,col:t.distinct}),yield this.getCurrentConnection().count(i)}))}getById(e,t){return this.getOne({_eq:{id:e}},t)}getByIds(e,t){return this.getRecords({_in:{id:e}},t)}getOne(e,t){return r(this,void 0,void 0,(function*(){const n=yield this.getMany(e,{limit:1});return n.records.length?this.convertToLogicObjects(n.records,null==t?void 0:t.projection)[0]:void 0}))}getRecords(e,t,n){return r(this,void 0,void 0,(function*(){return(yield this.getMany(e,t,n)).records}))}getMany(e,t,n){return r(this,void 0,void 0,(function*(){let i={where:this.getQueryObjectFromQueryConditions(e),transaction:this.transaction,include:this.resolveNestedIncludes(n)};if((null==t?void 0:t.order)&&Object.assign(i,{order:t.order}),(null==t?void 0:t.projection)&&Object.assign(i,{attributes:t.projection}),(null==t?void 0:t.limit)&&(i=Object.assign(i,{limit:t.limit}),t.page&&(i=Object.assign(i,{offset:t.limit*(t.page-1)}))),1!==(null==t?void 0:t.limit)||t.page){if(null==t?void 0:t.limit){const{count:e,rows:n}=yield this.getCurrentConnection().findAndCountAll(i);return{total:e,records:this.convertToLogicObjects(n,null==t?void 0:t.projection)}}{const e=yield this.getCurrentConnection().findAll(i);return{total:0,records:this.convertToLogicObjects(e,null==t?void 0:t.projection)}}}{const e=yield this.getCurrentConnection().findOne(i);return{total:0,records:e?this.convertToLogicObjects([e],t.projection):[]}}}))}createOne(e){return r(this,void 0,void 0,(function*(){return(yield this.createMany([e]))[0]}))}createMany(e){return r(this,void 0,void 0,(function*(){let t=yield this.getCurrentConnection().bulkCreate(this.convertToDataObjects(e),{transaction:this.transaction});return this.convertToLogicObjects(t)}))}updateOne(e){return r(this,void 0,void 0,(function*(){return yield this.getCurrentConnection().update(this.convertToDataObjects([e],!0)[0],{where:this.getQueryObjectFromQueryConditions({_eq:{id:e.id}}),transaction:this.transaction}),e}))}updateMany(e,t,n){return r(this,void 0,void 0,(function*(){if(n){const n=yield this.getRecords(e,{projection:["id"]});if(!n.length)return[];const i=n.map((e=>e.id));return yield this.getCurrentConnection().update(this.convertToDataObjects([t],!0)[0],{where:this.getQueryObjectFromQueryConditions({_in:{id:i}}),transaction:this.transaction}),i}return yield this.getCurrentConnection().update(this.convertToDataObjects([t],!0)[0],{where:this.getQueryObjectFromQueryConditions(e),transaction:this.transaction}),[]}))}deleteOne(e){return r(this,void 0,void 0,(function*(){return yield this.deleteMany({_eq:{id:e.id}}),e}))}deleteMany(e,t){return r(this,void 0,void 0,(function*(){if(t){const t=yield this.getMany(e);if(!t.records.length)return[];const n=t.records.map((e=>e.id));return yield this.getCurrentConnection().destroy({where:this.getQueryObjectFromQueryConditions({_in:{id:n}}),transaction:this.transaction}),t.records}return yield this.getCurrentConnection().destroy({where:this.getQueryObjectFromQueryConditions(e),transaction:this.transaction}),[]}))}rawQuery(...e){return r(this,void 0,void 0,(function*(){const t=e[0],n=e[1]||{};if("string"!=typeof t)throw s.ErrorBuilder.error(s.Errors.QUERY_ERROR,"First argument of raw sql expected to be string");return this.dbConnection.query(t,Object.assign({transaction:this.transaction,raw:!0},n))}))}mapToSequelizeOperator(e,t,n,i,o){const r=o?a.Sequelize.literal(safetifyColumn(n,e)):a.Sequelize.col(n);switch(t){case"_sub":switch(this.sqlProvider){case u.SqlProvider.MYSQL:return a.Sequelize.where(r,{[a.Op.like]:a.Sequelize.literal(`${this.dbConnection.escape(`%${i}%`)} COLLATE utf8mb4_0900_as_cs`)});default:return a.Sequelize.where(r,{[a.Op.like]:`%${i}%`})}case"_isub":switch(this.sqlProvider){case u.SqlProvider.POSTGRES:return a.Sequelize.where(r,{[a.Op.iLike]:`%${i}%`});case u.SqlProvider.MYSQL:return a.Sequelize.where(r,{[a.Op.like]:a.Sequelize.literal(`${this.dbConnection.escape(`%${i}%`)} COLLATE utf8mb4_0900_as_ci`)})}case"_usub":switch(this.sqlProvider){case u.SqlProvider.POSTGRES:return a.Sequelize.where(a.Sequelize.fn("unaccent",r),{[a.Op.like]:a.Sequelize.literal(`unaccent(${this.dbConnection.escape(`%${i}%`)})`)});case u.SqlProvider.MYSQL:return a.Sequelize.where(a.Sequelize.fn("unaccent",r),{[a.Op.like]:a.Sequelize.literal(`unaccent(${this.dbConnection.escape(`%${i}%`)}) COLLATE utf8mb4_0900_as_cs`)})}case"_iusub":switch(this.sqlProvider){case u.SqlProvider.POSTGRES:return a.Sequelize.where(a.Sequelize.fn("unaccent",r),{[a.Op.iLike]:a.Sequelize.literal(`unaccent(${this.dbConnection.escape(`%${i}%`)})`)});case u.SqlProvider.MYSQL:return a.Sequelize.where(r,{[a.Op.like]:a.Sequelize.literal(`${this.dbConnection.escape(`%${i}%`)} COLLATE utf8mb4_0900_ai_ci`)})}case"_in":const e=i||[],n=e.filter((e=>null!==e));return n.length<e.length?a.Sequelize.or(a.Sequelize.where(r,{[a.Op.eq]:null}),...n.length?[a.Sequelize.where(r,{[a.Op.in]:n})]:[]):a.Sequelize.where(r,{[a.Op.in]:e});default:return a.Sequelize.where(r,{[convertOp(t)]:i})}}getQueryObjectFromQueryConditions(e,t){if(!e)return{};const n=Object.keys(e);if(!n.length)return{};const i=n.map((n=>p.includes(n)?{[convertOp(n)]:e[n].map((e=>this.getQueryObjectFromQueryConditions(e)))}:{[convertOp("_and")]:Object.keys(e[n]).map((i=>this.mapToSequelizeOperator(this.sqlProvider,n,i,e[n][i],t)))}));return i.length>1?{[convertOp("_and")]:i}:i[0]}}class TransactionAdapter{constructor(e){this.modelAdapters={},this.transaction=e.transaction,this.dbConnection=e.dbConnection,this.logger=e.logger,this.modelConnections=e.modelConnections,this.sqlProvider=e.sqlProvider,this.transactionState=d.TransactionState.EXECUTING}use(e){const t=getModelId(e);let n=this.modelAdapters[t];return n||(this.modelAdapters,n=new ModelAdapter({model:e,dbConnection:this.dbConnection,modelConnections:this.modelConnections,logger:this.logger,transaction:this.transaction,sqlProvider:this.sqlProvider}),this.modelAdapters[t]=n),n}commit(){return r(this,void 0,void 0,(function*(){return this.transactionState=d.TransactionState.COMMITTED,this.transaction.commit()}))}rollback(){return r(this,void 0,void 0,(function*(){return this.transactionState=d.TransactionState.ROLLED_BACK,this.transaction.rollback()}))}getState(){return this.transactionState}}let f=class DefaultSqlDatabaseAdapter extends c.AbstractDatabaseAdapter{constructor(e,t,n){super(),this.logger=n,this.injector=(0,s.getServiceProvider)().getInjector(),this.modelAdapters={},this.sqlProvider=e,this.dbConnection=new a.Sequelize(`${e}://${t}`,{dialect:this.sqlProvider,logging:e=>this.logger.debug(e),define:{timestamps:!1}})}createTransaction(){return r(this,void 0,void 0,(function*(){let e=yield this.dbConnection.transaction();return new TransactionAdapter({transaction:e,dbConnection:this.dbConnection,logger:this.logger,modelConnections:this.modelConnections,sqlProvider:this.sqlProvider})}))}init(){const e=Object.create(null,{init:{get:()=>super.init}});var t,n,i,o;return r(this,void 0,void 0,(function*(){yield e.init.call(this),yield this.injector.initInstances(),null===(t=this.logger)||void 0===t||t.debug("Connecting to database"),yield this.dbConnection.authenticate(),null===(n=this.logger)||void 0===n||n.debug("Generating in-memory schema");for(const e of this.modelMetadata){const t=this.generateSchemaObject(e);this.modelConnections[e.id].connection=t}for(const e of this.modelMetadata){const t=this.modelConnections[e.id].connection,n=e.fields.filter((e=>e.fk));for(const o of n){const n=null===(i=o.fk)||void 0===i?void 0:i.dtoId;if(!n)throw s.ErrorBuilder.systemError(`FK model id not resolved for ${e.id}:${o.name}`);const r=this.modelConnections[n].connection;t.belongsTo(r,{foreignKey:o.name}),r.hasMany(t,{foreignKey:o.name})}}null===(o=this.logger)||void 0===o||o.debug("Database adapter init succeeded")}))}exit(){var e;return null===(e=this.logger)||void 0===e||e.debug("Closing connection to database"),this.dbConnection.close(),0}use(e){const t=getModelId(e);let n=this.modelAdapters[t];return n||(n=new ModelAdapter({model:e,dbConnection:this.dbConnection,modelConnections:this.modelConnections,logger:this.logger,sqlProvider:this.sqlProvider}),this.modelAdapters[t]=n),n}generateSchemaObject(e){let t={};const n=(0,h.getDirectFields)(e);for(const e of n){switch(t[e.name]={},e.dataType){case s.DataType.NUMBER:e.floating?t[e.name].type=a.DataTypes.FLOAT:e.isBigInt?t[e.name].type=a.DataTypes.BIGINT:t[e.name].type=a.DataTypes.INTEGER;break;case s.DataType.STRING:e.textLength?t[e.name].type=a.DataTypes.STRING(e.textLength):t[e.name].type=a.DataTypes.STRING;break;case s.DataType.BOOLEAN:t[e.name].type=a.DataTypes.BOOLEAN;break;case s.DataType.ARRAY:case s.DataType.OBJECT:t[e.name].type=a.DataTypes.TEXT}e.pk&&(t[e.name].primaryKey=!0,e.pk.isAutoIncrement&&(t[e.name].autoIncrement=!0)),void 0!==e.defaultValue&&(t[e.name].defaultValue=e.defaultValue),t[e.name].allowNull=!e.isRequired}return this.dbConnection.define(e.id,t,{tableName:e.id,freezeTableName:!0,name:{singular:e.id,plural:e.id}})}};f=i([(0,s.Initable)(),(0,s.Injectable)(),o("design:paramtypes",[String,String,s.AbstractLogger])],f),t.DefaultSqlDatabaseAdapter=f},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractQuery=void 0;const i=n(0);t.AbstractQuery=class AbstractQuery{constructor(e){const t=(0,i.getObjectMetadata)(e);this.model=(0,i.getModelById)(t.id)||e,this.metadata=(0,i.getObjectMetadata)(this.model)}convertToLogicObjects(e,t){return e.map((e=>{let n=new this.model;return this.metadata.fields.filter((e=>!t||t.includes(e.name))).forEach((t=>{const i=e[t.name];void 0!==i&&(t.isBigInt?n[t.name]=Number(i):t.vectorProps?n[t.name]=JSON.parse(i):n[t.name]=i)})),n}))}convertToDataObjects(e,t){const n=Date.now();return e.map((e=>{let i=new this.model;for(const o of this.metadata.fields){let r=e[o.name];o.vectorProps?r=JSON.stringify(r):(o.modificationTimestamp||o.creationTimestamp&&!t)&&(r=n),i[o.name]=r}return i}))}}},function(e,t,n){"use strict";var i,o=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},r=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},s=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSqlDatabaseMigrator=void 0;const d=a(n(34)),c=a(n(33)),l=n(77),u=n(0),h=n(18),p=n(17),f=n(3),g=n(36),uniqueGroupComparator=(e,t)=>!e.groupName&&!t.groupName&&e.fieldNames[0]===t.fieldNames[0]||!!e.groupName&&e.groupName===t.groupName;let y=i=class DefaultSqlDatabaseMigrator extends g.AbstractDatabaseMigrator{constructor(e,t,n,i){super(),this.cliPath=e,this.sqlProvider=t,this.connectionString=n,this.logger=i,this.injector=(0,u.getServiceProvider)().getInjector(),this.cliPath=e,this.databaseURL=`${t}://${n}`,this.modelMetadata=((0,u.getGlobalStore)().models||[]).map((e=>(0,u.getObjectMetadata)(e)))}init(){return s(this,void 0,void 0,(function*(){yield this.injector.initInstances()}))}exit(){}getUniqueConstraintGroups(e){const t=[],n=(0,f.getDirectFields)(e).filter((e=>!!e.unique));for(const e of n)if(e.unique.groupName){let n=t.find((t=>t.groupName===e.unique.groupName));n||(n={groupName:e.unique.groupName,fieldNames:[]},t.push(n)),n.fieldNames.push(e.name)}else t.push({fieldNames:[e.name]});return t}generateFieldPropertiesQuery(e){let t="{";if(e.pk&&(t+="primaryKey:true,",e.pk.isAutoIncrement&&(t+="autoIncrement:true,")),void 0!==e.defaultValue&&(t+=`defaultValue:${JSON.stringify(e.defaultValue)},`),t+=`allowNull:${e.isRequired?"false":"true"},`,void 0!==e.dataType)switch(e.dataType){case u.DataType.STRING:e.textLength?t+=`type:Sequelize.STRING(${e.textLength}),`:t+="type:Sequelize.TEXT,";break;case u.DataType.NUMBER:e.floating?t+="type:Sequelize.FLOAT,":e.isBigInt?t+="type:Sequelize.BIGINT,":t+="type:Sequelize.INTEGER,";break;case u.DataType.BOOLEAN:t+="type:Sequelize.BOOLEAN,";break;case u.DataType.ARRAY:case u.DataType.OBJECT:t+="type:Sequelize.TEXT,"}return t+="}",t}getUniqueConstraintUpDown(e,t){const n=`${e}_${t.groupName||t.fieldNames[0]}_un`;return[`queryInterface.addConstraint("${e}",{fields:${JSON.stringify(t.fieldNames)},type:"unique",name:"${n}","transaction":t})`,`queryInterface.removeConstraint("${e}","${n}",{"transaction":t})`]}getSqlCascadeAction(e){switch(e){case"delete":return"CASCADE";case"restrict":return"RESTRICT";case"nullify":return"SET NULL";default:return"RESTRICT"}}getForeignKeyConstraintUpDown(e,t,n){var i,o,r;if(!e)throw u.ErrorBuilder.systemError(`Refer table ${null===(i=n.fk)||void 0===i?void 0:i.dtoId} not found at ${t}:${n.name}`);const s=`${t}_${n.name}_fk`;return[`queryInterface.addConstraint("${t}",{fields:["${n.name}"],type:"foreign key",name:"${s}",references:{table:"${e.id}",field:"id"},onDelete:'${this.getSqlCascadeAction(null===(o=n.fk)||void 0===o?void 0:o.cascade)}',onUpdate:'${this.getSqlCascadeAction(null===(r=n.fk)||void 0===r?void 0:r.cascade)}',"transaction":t})`,`queryInterface.removeConstraint("${t}","${s}",{"transaction":t})`]}getAddColumnUpDown(e,t){return[`queryInterface.addColumn('${e}','${t.name}',${this.generateFieldPropertiesQuery(t)},{"transaction":t})`,`queryInterface.removeColumn('${e}','${t.name}',{"transaction":t})`]}generateCreateTableQuery(e){let t={upTableAdd:[],downTableRemove:[],upConstraintAdd:[],downConstraintRemove:[],upTableRemove:[],downTableAdd:[],upConstraintRemove:[],downConstraintAdd:[]},n="",i="";n+="{\n";for(const t of(0,f.getDirectFields)(e)){let e=this.generateFieldPropertiesQuery(t);n+=`${t.name}:${e},\n`}n+="}\n",i+='{charset:"utf8",transaction:t}',t.upTableAdd.push(`queryInterface.createTable("${e.id}",${n},{charset:"utf8",transaction:t})`),t.downTableRemove.push(`queryInterface.dropTable("${e.id}",{"transaction":t})`);const o=this.getUniqueConstraintGroups(e);for(const n of o){const[i,o]=this.getUniqueConstraintUpDown(e.id,n);t.upConstraintAdd.push(i),t.downConstraintRemove.push(o)}for(const n of(0,f.getDirectFields)(e))if(n.fk){let i=this.modelMetadata.find((e=>{var t;return e.id===(null===(t=n.fk)||void 0===t?void 0:t.dtoId)}));const[o,r]=this.getForeignKeyConstraintUpDown(i,e.id,n);t.upConstraintAdd.push(o),t.downConstraintRemove.push(r)}return t}isBooleanDiff(e,t){return!!e&&!t||!!t&&!e}runProcess(e){return s(this,void 0,void 0,(function*(){return new Promise(((t,n)=>{(0,l.exec)(e,{env:process.env},(e=>(e&&n(e),t())))}))}))}rollback(e){return s(this,void 0,void 0,(function*(){let t=d.default.join(e,"scripts");if(!c.default.existsSync)throw u.ErrorBuilder.systemError("Migration directory not found");this.logger.debug("Rolling back last migration"),yield this.runProcess(`${this.cliPath} --url=${this.databaseURL} --migrations-path=${t} db:migrate:undo`),this.logger.debug("Rollback completed")}))}migrate(e){var t,n,o,r,a,l,g,y;return s(this,void 0,void 0,(function*(){let v=d.default.join(e,"metadata.json"),m=d.default.join(e,"scripts");c.default.existsSync(m)||(this.logger.debug("Migration directory not exists, creating empty folder"),c.default.mkdirSync(m,{recursive:!0})),c.default.existsSync(v)||(this.logger.debug("Migration metadata does not exist, creating one"),c.default.writeFileSync(v,JSON.stringify([]))),this.logger.debug("Parsing migration metadata file");let b=JSON.parse(String(c.default.readFileSync(v)));this.logger.debug("Calculating differences...");const C=this.modelMetadata.filter((e=>!b.find((t=>e.id===t.id)))),M=this.modelMetadata.filter((e=>b.find((t=>t.id===e.id)))).map((e=>e.id));let S=[];S.push(...C.map((e=>this.generateCreateTableQuery(e))));for(const e of M){const i=b.find((t=>t.id===e)),s=this.modelMetadata.find((t=>t.id===e));i.id!==s.id&&S.push({upTableAdd:[`queryInterface.query("ALTER TABLE ${i.id} RENAME TO ${s.id}",{"transaction":t})`],downTableRemove:[`queryInterface.query("ALTER TABLE ${s.id} RENAME TO ${i.id}",{"transaction":t})`],upConstraintAdd:[],downConstraintRemove:[],upTableRemove:[],downTableAdd:[],upConstraintRemove:[],downConstraintAdd:[]});let d={upTableAdd:[],downTableRemove:[],upConstraintAdd:[],downConstraintRemove:[],upTableRemove:[],downTableAdd:[],upConstraintRemove:[],downConstraintAdd:[]};const c=(0,f.getDirectFields)(i).filter((e=>!(0,f.getDirectFields)(s).find((t=>e.name===t.name))));for(const e of c){const[t,n]=this.getAddColumnUpDown(s.id,e);if(d.upTableRemove.push(n),d.downTableAdd.push(t),e.fk){let t=this.modelMetadata.find((t=>{var n;return t.id===(null===(n=e.fk)||void 0===n?void 0:n.dtoId)}));const[n,i]=this.getForeignKeyConstraintUpDown(t,s.id,e);d.upConstraintRemove.push(i),d.downConstraintAdd.push(n)}}const u=(0,f.getDirectFields)(s).filter((e=>!(0,f.getDirectFields)(i).find((t=>e.name===t.name))));for(const e of u){const[t,n]=this.getAddColumnUpDown(s.id,e);if(d.upTableAdd.push(t),d.downTableRemove.push(n),e.fk){let t=this.modelMetadata.find((t=>{var n;return t.id===(null===(n=e.fk)||void 0===n?void 0:n.dtoId)}));const[n,i]=this.getForeignKeyConstraintUpDown(t,s.id,e);d.upConstraintAdd.push(n),d.downConstraintRemove.push(i)}}const h=(0,f.getDirectFields)(s).filter((e=>(0,f.getDirectFields)(i).find((t=>e.name===t.name)))).map((e=>e.name));for(const e of h){const c=(0,f.getFieldByName)(i,e),u=(0,f.getFieldByName)(s,e);if((this.isBooleanDiff(c.floating,u.floating)||this.isBooleanDiff(c.isBigInt,u.isBigInt)||this.isBooleanDiff(c.isRequired,u.isRequired)||this.isBooleanDiff(null===(t=c.pk)||void 0===t?void 0:t.isAutoIncrement,null===(n=u.pk)||void 0===n?void 0:n.isAutoIncrement)||c.dataType!==u.dataType||c.textLength!==u.textLength||c.defaultValue!==u.defaultValue)&&(d.upTableAdd.push(`queryInterface.changeColumn("${s.id}","${u.name}",${this.generateFieldPropertiesQuery(u)},{"transaction":t})`),d.downTableRemove.push(`queryInterface.changeColumn("${s.id}","${c.name}",${this.generateFieldPropertiesQuery(c)},{"transaction":t})`)),(null===(o=c.fk)||void 0===o?void 0:o.dtoId)!==(null===(r=u.fk)||void 0===r?void 0:r.dtoId)||(null===(a=c.fk)||void 0===a?void 0:a.cascade)!==(null===(l=u.fk)||void 0===l?void 0:l.cascade)){if(null===(g=c.fk)||void 0===g?void 0:g.dtoId){const e=this.modelMetadata.find((e=>{var t;return e.id===(null===(t=c.fk)||void 0===t?void 0:t.dtoId)})),[t,n]=this.getForeignKeyConstraintUpDown(e,s.id,c);d.upTableAdd.push(n),d.downTableRemove.push(t)}if(null===(y=u.fk)||void 0===y?void 0:y.dtoId){const e=this.modelMetadata.find((e=>{var t;return e.id===(null===(t=u.fk)||void 0===t?void 0:t.dtoId)})),[t,n]=this.getForeignKeyConstraintUpDown(e,s.id,u);d.upTableAdd.push(t),d.downTableRemove.push(n)}}}const p=this.getUniqueConstraintGroups(i),v=this.getUniqueConstraintGroups(s),m=p.filter((e=>!!v.find((t=>uniqueGroupComparator(e,t))))),C=p.filter((e=>!m.find((t=>uniqueGroupComparator(e,t)))));for(const e of C){const[t,n]=this.getUniqueConstraintUpDown(s.id,e);d.upConstraintRemove.push(n),d.downConstraintAdd.push(t)}const M=v.filter((e=>!m.find((t=>uniqueGroupComparator(e,t)))));for(const e of M){const[t,n]=this.getUniqueConstraintUpDown(s.id,e);d.upConstraintAdd.push(t),d.downConstraintRemove.push(n)}for(const e of m){const t=p.find((t=>uniqueGroupComparator(t,e))),n=v.find((t=>uniqueGroupComparator(t,e)));if(t.fieldNames.length!==n.fieldNames.length||t.fieldNames.some((e=>!n.fieldNames.includes(e)))){const[e,i]=this.getUniqueConstraintUpDown(s.id,t),[o,r]=this.getUniqueConstraintUpDown(s.id,n);d.upConstraintRemove.push(i),d.upConstraintAdd.push(o),d.downConstraintRemove.push(r),d.downConstraintAdd.push(e)}}(d.upTableAdd.length||d.downTableRemove.length||d.upConstraintAdd.length||d.downConstraintRemove.length||d.upConstraintRemove.length||d.downConstraintAdd.length||d.upTableRemove.length||d.downTableAdd.length)&&S.push(d)}if(S.length){let e=`${Date.now()}-auto-migration.js`;const getTransactionalScript=e=>`const t = await queryInterface.sequelize.transaction({autoCommit: false}); \n try {\n ${e.reduce(((e,t)=>e+`await ${t};`),"")}\n await t.commit();\n } catch(err){\n await t.rollback(); \n throw(err);\n }`,migrationFunction=(e,t)=>s(this,void 0,void 0,(function*(){if(!e.up.length&&!e.down.length)return;let n=d.default.join(m,t),o=i.MIGRATION_TEMPLATE,r=new RegExp(i.COMMENT_BLOCK_REGEX_PATTERN),s=getTransactionalScript(e.up),a=getTransactionalScript(e.down);o=o.replace(r,s),o=o.replace(r,a),this.logger.debug("Writing to file",n),c.default.writeFileSync(n,o)}));throw yield migrationFunction({up:[...S.reduce(((e,t)=>e.concat(t.upConstraintRemove)),[]),...S.reduce(((e,t)=>e.concat(t.upTableRemove)),[]),...S.reduce(((e,t)=>e.concat(t.upTableAdd)),[]),...S.reduce(((e,t)=>e.concat(t.upConstraintAdd)),[])],down:[...S.reduce(((e,t)=>e.concat(t.downConstraintRemove)),[]).reverse(),...S.reduce(((e,t)=>e.concat(t.downTableRemove)),[]).reverse(),...S.reduce(((e,t)=>e.concat(t.downTableAdd)),[]).reverse(),...S.reduce(((e,t)=>e.concat(t.downConstraintAdd)),[]).reverse()]},e),this.logger.debug("Updating metadata file"),c.default.writeFileSync(v,JSON.stringify(this.modelMetadata.map((e=>this.getLeanModelMetadata(e))))),u.ErrorBuilder.systemError(`Migration review needed: ${e}`)}this.logger.debug("No difference, running migration"),this.logger.debug("Create database if not exist");try{yield this.runProcess(`${this.cliPath} --url=${this.databaseURL} db:create`)}catch(e){if(String(e).indexOf("already exists")<0)throw e}if(this.logger.debug("Running migration"),this.sqlProvider===p.SqlProvider.POSTGRES){this.logger.debug("Creating unaccent extension for postgres");const e=new h.Sequelize(this.databaseURL);yield e.query("CREATE EXTENSION IF NOT EXISTS unaccent;")}else if(this.sqlProvider===p.SqlProvider.MYSQL){this.logger.debug("Creating unaccent function for mysql");const e=new h.Sequelize(this.databaseURL,{dialectOptions:{multipleStatements:!0}}),t="ĂÂÀÁẢÃẠẰẮẲẴẶẦẤẨẪẬÔƠÒÓỎÕỌỒỐỔỖỘỜỚỞỠỢÈÉẺẼẸÊỀẾỂỄỆÙÚỦŨỤƯỪỨỬỮỰÌÍỈĨỊỲÝỶỸỴ",n="AAAAAAAAAAAAAAAAAOOOOOOOOOOOOOOOOOEEEEEEEEEEEUUUUUUUUUUUIIIIIYYYYY",i=`SET GLOBAL log_bin_trust_function_creators = 1; \nDROP FUNCTION IF EXISTS unaccent; \nCREATE FUNCTION unaccent( textvalue TEXT ) RETURNS TEXT \nBEGIN \nSET @textvalue = textvalue; \nSET @withaccents = 'ŠšŽžÄÅÆÇËÎÏÑÖØÛÜŸÞäåæçëîïñõöøûüÿþƒ${t}${t.toLowerCase()}'; \nSET @withoutaccents = 'SsZzAAACEIINOOUUYBaaaceiinooouuybf${n}${n.toLowerCase()}'; \nSET @count = LENGTH(@withaccents); \nWHILE @count > 0 DO \nSET @textvalue = REPLACE(@textvalue, SUBSTRING(@withaccents, @count, 1), SUBSTRING(@withoutaccents, @count, 1)); \nSET @count = @count - 1; \nEND WHILE; \nRETURN @textvalue; \nEND; \n`;yield e.query(i,{type:h.QueryTypes.RAW})}yield this.runProcess(`${this.cliPath} --url=${this.databaseURL} --migrations-path=${m} db:migrate`),this.logger.debug("Migration finished")}))}remove(e,t){return Object.keys(e).filter((e=>!t.includes(e))).reduce(((t,n)=>Object.assign(t,{[n]:e[n]})),{})}getLeanModelMetadata(e){return{id:e.id,fields:(0,f.getDirectFields)(e).map((e=>Object.assign({},this.remove(e,["vectorProps","stateMachineTransition","serverValue","searchable","regex","rangeProps","modificationTimestamp","mimeProps","isTimestamp","isSymbol","isLabel","injecteeSuperClass","hasMany","elementDto","creationTimestamp"]))))}}};y.COMMENT_BLOCK_REGEX_PATTERN="/\\*(\\*(?!/)|[^*])*\\*\\/",y.MIGRATION_TEMPLATE="'use strict';\n module.exports = {\n up: async (queryInterface, Sequelize) => {\n /**\n */\n },\n \n down: async (queryInterface, Sequelize) => {\n /**\n */\n }\n };",y=i=o([(0,u.Injectable)(),r("design:paramtypes",[String,String,String,u.AbstractLogger])],y),t.DefaultSqlDatabaseMigrator=y},function(e,t){e.exports=require("child_process")}])}));
|