@clairejs/server 3.8.6 → 3.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,5 +1,14 @@
1
1
  ## Change Log
2
2
 
3
+ #### 3.9.0
4
+
5
+ - fix AbstractHttpMiddleware to accept response as second param and return boolean as result
6
+
7
+ #### 3.8.8
8
+
9
+ - update core package, reduce db calls in ModelRepository
10
+ - allow nested update HasMany / HasOne field in ModelRepository
11
+
3
12
  #### 3.8.6
4
13
 
5
14
  - fix auto fill of post/put default value (no more auto fill, because of access condition check)
@@ -1,12 +1,9 @@
1
1
  /// <reference types="node" />
2
- declare type Dict = {
3
- [key: string]: string;
4
- };
5
2
  export declare class HttpResponse<T> {
6
3
  value?: T;
7
- code: number;
8
- headers: Dict;
9
- cookies: Dict;
4
+ code?: number;
5
+ headers: Record<string, string>;
6
+ cookies: Record<string, string>;
10
7
  }
11
8
  export declare class ResponseBuilder<T> {
12
9
  response: HttpResponse<T>;
@@ -22,4 +19,3 @@ export declare class ResponseBuilder<T> {
22
19
  static notFound(data?: any): HttpResponse<unknown>;
23
20
  static accessDenied(data?: any): HttpResponse<unknown>;
24
21
  }
25
- export {};
@@ -1,5 +1,10 @@
1
1
  import { HttpRequest } from "../common/HttpRequest";
2
2
  import { HttpResponse } from "../common/HttpResponse";
3
3
  export declare abstract class AbstractHttpMiddleware {
4
- abstract intercept(request: HttpRequest): Promise<HttpResponse<any> | undefined>;
4
+ /**
5
+ * Return true to proceed to next middleware and controller, return false to immediately break and returning current response
6
+ * @param request the http request
7
+ * @param response the http response
8
+ */
9
+ abstract intercept(request: HttpRequest, response: HttpResponse<any>): Promise<boolean>;
5
10
  }
@@ -11,6 +11,6 @@ export declare abstract class AbstractHttpRequestHandler {
11
11
  constructor(mountPoint: string, logger: AbstractLogger);
12
12
  protected resolverMountPoint(controllerMetadata: ControllerMetadata, mappingUrls: string[]): string;
13
13
  getMountedEndpointInfo(): Promise<MountedEndpointInfo[]>;
14
- abstract getMiddleware(): AbstractHttpMiddleware[];
14
+ abstract getMiddleware(): Promise<AbstractHttpMiddleware[]>;
15
15
  abstract handle(httpData: HttpData): Promise<HttpResponse<any>>;
16
16
  }
@@ -10,10 +10,12 @@ import { AbstractHttpMiddleware } from "./AbstractHttpMiddleware";
10
10
  export declare class DefaultHttpRequestHandler extends AbstractHttpRequestHandler {
11
11
  readonly logger: AbstractLogger;
12
12
  readonly authorizationProvider: AbstractHttpAuthorizationProvider<IPrincipal>;
13
+ private _middleware;
13
14
  constructor(logger: AbstractLogger, authorizationProvider: AbstractHttpAuthorizationProvider<IPrincipal>);
14
15
  protected accessControl(endpoint: MountedEndpointInfo, req: HttpRequest): Promise<void>;
15
16
  protected handleRequest(endpoint: MountedEndpointInfo, req: HttpRequest): Promise<HttpResponse<any>>;
16
17
  exit(): void;
18
+ private getResponse;
17
19
  handle(httpData: HttpData): Promise<HttpResponse<any>>;
18
- getMiddleware(): AbstractHttpMiddleware[];
20
+ getMiddleware(): Promise<AbstractHttpMiddleware[]>;
19
21
  }
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,(()=>(()=>{"use strict";var e={9025:(e,t)=>{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={}))},4638:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractPrincipalResolver=void 0;t.AbstractPrincipalResolver=class AbstractPrincipalResolver{}},1820:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},137:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ExitCode=void 0,t.ExitCode={SIGTERM_INTERUPTION:-1,SIGINT_INTERUPTION:-2,UNCAUGHT_EXCEPTION:-3,UNHANDLED_REJECTION:-4}},4435:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},4972:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getEndpointId=void 0;t.getEndpointId=e=>`${e.httpMethod}:${e.mount}`},1870:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},859:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractHttpAuthorizationProvider=void 0;t.AbstractHttpAuthorizationProvider=class AbstractHttpAuthorizationProvider{}},2085:function(e,t,n){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(2318),r=n(859),s=n(4972);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)))),l=(i.policyPermissions||[]).filter((e=>!!d.find((t=>t.policyId===e.policyId)))),c=(i.policyPermissionConditions||[]).filter((e=>!!l.find((t=>t.id===e.policyPermissionId)))),u=l.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=c.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},531:function(e,t,n){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(2085);class RedisRbacAuthProvider extends o.AbstractRbacAuthProvider{constructor(e,t,n,i,o,r,s,a=3e4){super(i,o,s),this.serviceIdResolver=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={},this.serviceId=""}getRbacCache(){return i(this,void 0,void 0,(function*(){if(this.lastRbacFetchTimestamp+this.redisDataRetentionDurationMs<Date.now()){this.serviceId||(this.serviceId=yield this.serviceIdResolver());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},7825:function(e,t,n){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(2318),a=n(2085),d=n(4638);let l=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)}))}))}};l=i([(0,s.Initable)(),o("design:paramtypes",[String,String,Function,d.AbstractPrincipalResolver,s.AbstractLogger,Function])],l),t.SocketRbacAuthProvider=l},9837:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},1532:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HttpRequest=void 0;const i=n(2318);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,!1))}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}}},8903:(e,t)=>{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},6004:function(e,t,n){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(2318),r=n(7756);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}))):[]}}},225:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractHttpMiddleware=void 0;t.AbstractHttpMiddleware=class AbstractHttpMiddleware{}},767:function(e,t,n){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(2318),r=n(4972),s=n(6004);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 l=[];for(const o of i){const i=l.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}`):l.push(o)}this.mountedEndpointInfo=l}return this.mountedEndpointInfo}))}}},7282:function(e,t,n){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(2318),d=n(7756),l=n(1071),c=n(1532),u=n(2417),h=n(6004),p=n(859),f=n(8903),y=n(3198),g=n(4192);class CrudHttpController extends h.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&&!e.multiLocaleColumn));"create_response"===t&&(o=o.filter((e=>e.pk||e.serverValue||e.mimeProps))),"create_body"!==t&&"update_body"!==t||(o=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.multiLocaleColumn)),s=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&&!e.isMultiLocale)}))),...s.map((n=>{var i,o,r,s;const d=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:(null===(o=n.hasMany)||void 0===o?void 0:o.single)?a.DataType.OBJECT:a.DataType.ARRAY,isRequired:!(null===(r=n.hasMany)||void 0===r?void 0:r.single)&&"create_response"===t,vectorProps:(null===(s=n.hasMany)||void 0===s?void 0:s.single)?void 0:{elementDataType:a.DataType.OBJECT,minLength:0},elementDto:Object.assign(Object.assign({},d),{fields:("create_body"===t||"update_body"===t?d.fields.filter((e=>{var t;return e.name!==(null===(t=n.hasMany)||void 0===t?void 0:t.column)})):d.fields).map((e=>"update_body"===t?Object.assign(Object.assign({},e),{isRequired:!1,allowNull:!0}):e))})}})),...r.map((e=>({description:"Translation for "+e.multiLocaleColumn,name:e.name,isRequired:!1,dataType:a.DataType.OBJECT})))),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);break;case a.DataType.BOOLEAN:t.dataType=a.DataType.BOOLEAN,t.allowNull=e.allowNull}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(p.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,g.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,g.DtoFieldValidation)(this.model,(e=>[e.getQuery().fields])),(0,l.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,l.FilterModelFieldAccessCondition)(this.model,(e=>{const t=e.getBody().update;return t?Object.keys((0,a.leanData)(t)):[]})),(0,g.DtoFieldValidation)(this.model,(e=>[e.getQuery().fields]),"dto_field_validation_query"),(0,g.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,g.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:"locale",description:"Language code for localization",isRequired:!1};n.dataType=a.DataType.STRING,t.fields.push(n);const i={name:"search",description:"Filter records for their @Searchable denoted fields."};i.dataType=a.DataType.STRING,t.fields.push(i),t.fields.push(CrudHttpController.projectionFieldDto(e));const o={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."};o.dataType=a.DataType.ARRAY,o.vectorProps={elementDataType:a.DataType.OBJECT,minLength:1};const r={id:"",fields:[]};r.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}))),o.elementDto=r,t.fields.push(o);const s={name:"limit",description:"Limit the number of returning result."};s.dataType=a.DataType.NUMBER,s.rangeProps={min:1},t.fields.push(s);const d={name:"page",description:"Page the returning result, default to 1 if ommited. Has no effect if limit is not set."};return d.dataType=a.DataType.NUMBER,d.rangeProps={min:1},t.fields.push(d),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 f.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 f.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 f.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 f.ResponseBuilder.json({modified:n.modified.map((e=>e.id)).map((e=>({id:e})))}).get()}))}}i([(0,d.Transactional)(d.PropagationMode.INHERIT_OR_CREATE),(0,u.ApiDescription)("Create records of this table."),(0,u.AccessCondition)([]),r(0,(0,u.Raw)()),o("design:type",Function),o("design:paramtypes",[c.HttpRequest]),o("design:returntype",Promise)],CrudHttpController.prototype,"createMany",null),i([(0,u.AccessCondition)([]),(0,u.ApiDescription)("Get records of this table."),r(0,(0,u.Raw)()),o("design:type",Function),o("design:paramtypes",[c.HttpRequest]),o("design:returntype",Promise)],CrudHttpController.prototype,"getMany",null),i([(0,d.Transactional)(d.PropagationMode.INHERIT_OR_CREATE),(0,u.ApiDescription)("Find and update records which match search condition."),(0,u.AccessCondition)([]),r(0,(0,u.Raw)()),o("design:type",Function),o("design:paramtypes",[c.HttpRequest]),o("design:returntype",Promise)],CrudHttpController.prototype,"updateMany",null),i([(0,d.Transactional)(d.PropagationMode.INHERIT_OR_CREATE),(0,u.ApiDescription)("Find and remove records which match search condition."),(0,u.AccessCondition)([]),r(0,(0,u.Raw)()),o("design:type",Function),o("design:paramtypes",[c.HttpRequest]),o("design:returntype",Promise)],CrudHttpController.prototype,"deleteMany",null),t.CrudHttpController=CrudHttpController},5879:function(e,t,n){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(2318),d=s(n(9215)),l=n(99),c=s(n(9103)),u=n(8903),h=n(1532),p=n(859),f=n(767),y=n(6721);let g=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(y.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*(){let t;try{const n=e.method,i=(0,d.default)({url:e.fullPath});let o={};const r=(yield this.getMountedEndpointInfo()).find((e=>{const t=e.endpointMetadata.httpMethod===n&&(0,l.match)(e.endpointMetadata.url,{decode:decodeURIComponent})(i.pathname||"/");return!!t&&(o=t,!0)}));if(!r)throw this.logger.debug(e),a.ErrorBuilder.error(y.Errors.NOT_FOUND,"Handler not found");const s=new h.HttpRequest({method:n,headers:e.headers,pathName:i.pathname||"",hash:i.hash||"",query:c.default.parse(decodeURIComponent(i.search||"")),params:o.params,body:e.body},r.endpointMetadata);for(const e of this.getMiddleware())if(t=yield e.intercept(s),t)break;if(t||(t=yield this.handleRequest(r,s)),!(t&&t instanceof u.HttpResponse))throw a.ErrorBuilder.systemError(`Invalid response value returned ${r.endpoint.httpMethod}:${r.endpoint.mount}, required instance of ${u.HttpResponse.name}, found ${t?null==t?void 0:t.constructor.name:t}`)}catch(e){this.logger.error(e),t=u.ResponseBuilder.json({name:e.name,message:e.message}).status([y.Errors.ACCESS_DENIED,y.Errors.AUTHENTICATION_ERROR,y.Errors.SESSION_EXPIRED].includes(e.name)?401:[y.Errors.SYSTEM_ERROR,y.Errors.CANNOT_LOCK].includes(e.name)?500:400).get()}return t}))}getMiddleware(){return[]}};g=i([(0,a.Injectable)(),o("design:paramtypes",[a.AbstractLogger,p.AbstractHttpAuthorizationProvider])],g),t.DefaultHttpRequestHandler=g},2417:(e,t,n)=>{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(2318);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}},6507:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractFileUploadHandler=void 0;t.AbstractFileUploadHandler=class AbstractFileUploadHandler{}},4839:function(e,t,n){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(2318),a=n(8709),d=n(6507);let l=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)}))}};l=i([(0,s.Injectable)(),o("design:paramtypes",[a.AbstractFileService])],l),t.FileUploadHandler=l},5232:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},5048:function(e,t,n){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(2318);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}}},9073:function(e,t,n){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(2318),r=n(5048),s=n(3355);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 l=Object.assign(Object.assign({},r.update),{id:t.fields.id[0]});yield this.beforeCreating(e,[l]),yield this.getMapValue(l,(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(l),((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 c=["id"];return t.returning&&(c=[...c,...Object.keys(r.update).filter((e=>void 0!==r.update[e]))]),{modified:l.id?this.project([l],c):[]}}))}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},8023:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},3355:function(e,t,n){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(2318),r=n(7756),s=n(6507),a=n(5048),d=n(9627),l=n(2552),c=n(5481);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 n;return e.name!==(null===(n=t.hasMany)||void 0===n?void 0:n.column)}))}));return{modelId:t.hasMany.relationDto.id,targetField:t.hasMany.column,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)){const t=e[s.name];if(void 0!==t)if(s.pk||s.fk||s.isSymbol)i.push({_in:{[s.name]:t}});else if(s.enum)i.push({_in:{[s.name]:t}});else switch(s.dataType){case o.DataType.STRING:if(s.searchable){const e={[(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]:t}};i.push(e)}else i.push({_eq:{[s.name]:t}});break;case o.DataType.NUMBER:const e=new o.RangeQueryDto;Object.assign(e,t),e.min&&(e.minExclusive?i.push({_gt:{[s.name]:e.min}}):i.push({_gte:{[s.name]:e.min}})),e.max&&(e.maxExclusive?i.push({_lt:{[s.name]:e.max}}):i.push({_lte:{[s.name]:e.max}}));break;case o.DataType.BOOLEAN:i.push({_eq:{[s.name]:t}})}}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}){var s;return i(this,void 0,void 0,(function*(){const i=t.records;if(!i.length)return{records:[]};const a=(0,r.getDirectFields)(this.modelMetadata),u=a.filter((e=>!!e.multiLocaleColumn)),h=(0,d.getSystemLocale)();if(h)for(const e of i)for(const t of u)e[t.name]&&(e[t.multiLocaleColumn]=e[t.name][h]);const p=this.modelMetadata.fields.filter((e=>!!e.hasMany)),f=i.map(((e,t)=>u.filter((t=>!!e[t.name])).map((e=>({recordIndex:t,field:e.name,entryObject:{}}))))).flatMap((e=>e)),y=yield n.use(c.LocaleEntry).createMany(f.map((e=>e.entryObject))),g=i.map((e=>u.filter((t=>!!e[t.name])).map((t=>e[t.name])))).flatMap((e=>e)).map(((e,t)=>Object.keys(e).map((n=>({localeCode:n,entryId:y[t].id,translation:e[n]}))))).flatMap((e=>e));yield n.use(l.LocaleTranslation).createMany(g),t.records=i.map(((e,t)=>a.reduce(((n,i)=>{let o=e[i.name];if(i.multiLocaleColumn){const e=f.findIndex((e=>e.recordIndex===t&&e.field===i.name));e>=0&&(o=y[e].id)}return Object.assign(n,void 0!==o?{[i.name]:o}:{})}),{}))),yield this.beforeCreating(e,t.records);let v=t.records.length?yield n.use(this.model).createMany(t.records):[];yield this.uriHandling(v,n),yield this.beforeReturning(v);const m=this.modelMetadata.fields.filter((e=>!e.multiLocaleColumn&&(e.pk||e.serverValue||e.mimeProps))).map((e=>e.name));v=this.project(v,m);for(const r of p){const a=v.flatMap(((e,t)=>{var n;const o=i[t][r.name];return o?((null===(n=r.hasMany)||void 0===n?void 0:n.single)?[o]:o).map((t=>Object.assign(Object.assign({},t),{[r.hasMany.column]:e.id}))):[]}));if(a.length){const i=new ModelRepository((0,o.getModelById)(r.hasMany.relationDto.id));t.records=a;const d=yield i.createMany({principal:e,body:t,tx:n});for(let e=0;e<d.records.length;e++)a[e]=Object.assign(Object.assign({},a[e]),d.records[e]);for(let e=0;e<v.length;e++){const t=[];for(let n=0;n<a.length;n++)a[n][r.hasMany.column]===v[e].id&&t.push(d.records[e]);v[e]=Object.assign(Object.assign({},v[e]),{[r.name]:(null===(s=r.hasMany)||void 0===s?void 0:s.single)?t[0]:t})}}}return{records:v}}))}updateMany({principal:e,ops:t,queries:n,body:s,tx:a}){var u,h;return i(this,void 0,void 0,(function*(){const i=t||[],p=this.modelMetadata.fields.filter((e=>!!e.hasMany)),f=(0,r.getDirectFields)(this.modelMetadata).filter((e=>!e.multiLocaleColumn&&void 0!==s.update[e.name])),y=f.reduce(((e,t)=>Object.assign(e,{[t.name]:s.update[t.name]})),{}),g=Object.keys(s.update),v=this.modelMetadata.fields.filter((e=>g.includes(e.name)&&e.multiLocaleColumn)),m=(0,d.getSystemLocale)();if(m)for(const e of v)if(s.update[e.name]){const t=s.update[e.name][m];t&&(y[e.multiLocaleColumn]=t)}if(null==n?void 0:n.fields){const e=this.getRequestQueryConditionFromQuery(n.fields,this.modelMetadata);e.length&&i.push(...e)}const b=i.length?{_and:[...i]}:{},M=this.getNestedQueries(n);let C=[];if(M.length){const e=yield a.use(this.model).getMany(b,{projection:["id"]},M);C=e.records.map((e=>e.id)),C.length&&f.length&&(yield a.use(this.model).updateMany({_in:{id:C}},y,!1))}else if(f.length)C=yield a.use(this.model).updateMany(b,y,!0);else{const e=yield a.use(this.model).getMany(b,{projection:["id"]});C=e.records.map((e=>e.id))}if(v.length){const e=yield a.use(this.model).getRecords({_in:{id:C}},{projection:["id",...v.map((e=>e.name))]}),t=e.map((e=>v.filter((t=>!e[t.name])).map((t=>({recordId:e.id,field:t.name}))))).flatMap((e=>e)),n=t.length?yield a.use(c.LocaleEntry).createMany(t.map((()=>({})))):[],i=[];n.forEach(((n,o)=>{const r=t[o],s=e.find((e=>e.id===r.recordId));if(s){s[r.field]=n.id;let e=i.find((e=>e.id===s.id));e||(e={id:s.id},i.push(e)),e[r.field]=n.id}})),yield Promise.all(i.map((e=>a.use(this.model).updateOne(e))));const o=[];for(const t of v){const n=s.update[t.name],i=Object.keys(n||{});i.length&&o.push(...e.map((e=>i.map((i=>({entryId:e[t.name],langCode:i,translation:n[i]}))))).flatMap((e=>e)))}o.length&&(yield a.use(l.LocaleTranslation).deleteMany({_or:o.map((e=>({_eq:{entryId:e.entryId,localeCode:e.langCode}})))}),yield a.use(l.LocaleTranslation).createMany(o.map((e=>({entryId:e.entryId,localeCode:e.langCode,translation:e.translation})))))}const R=C.map((e=>Object.assign(Object.assign({},y),{id:e})));yield this.uriHandling(R,a),yield this.beforeReturning(R);for(const t of p){const n=s.update[t.name];if(void 0===n||!C.length)continue;if(C.length>1)throw o.ErrorBuilder.systemError(`Multiple records found while updating @HasMany field: ${t.name}`);const i=R.find((e=>e.id===C[0])),r=(0,o.getModelById)(t.hasMany.relationDto.id),d=a.use(r),l=(yield d.getRecords({_eq:{[t.hasMany.column]:i.id}},{limit:(null===(u=t.hasMany)||void 0===u?void 0:u.single)?1:void 0})).map((e=>e.id)),c=n.map((e=>e.id)).filter((e=>!!e)),p=l.filter((e=>!c.includes(e))),f=n.filter((e=>!e.id)).map((e=>Object.assign(Object.assign({},e),{[t.hasMany.column]:i.id}))),y=n.filter((e=>!!e.id));yield d.deleteMany({_in:{id:p}});const g=new ModelRepository(r),v=yield g.createMany({principal:e,body:{records:f},tx:a}),m=f.map(((e,t)=>Object.assign(Object.assign({},e),v.records[t]))).concat(y);i[t.name]=(null===(h=t.hasMany)||void 0===h?void 0:h.single)?m[0]:m}let S=["id"];return(null==n?void 0:n.returning)&&(S=[...S,...Object.keys(s.update).filter((e=>void 0!==s.update[e]))]),{modified:this.project(R,S)}}))}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=this.modelMetadata.fields.filter((t=>t.isMultiLocale&&(!(null==e?void 0:e.projection)||e.projection.includes(t.name)))),a=this.modelMetadata.fields.filter((e=>s.find((t=>t.name===e.multiLocaleColumn)))),c=(null==e?void 0:e.projection)&&[...e.projection.filter((e=>!this.modelMetadata.fields.find((t=>t.name===e&&!!t.hasMany)))),...a.map((e=>e.name))],u=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:c,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)),h=u.records.map((e=>e.id)),p=u.records.map((e=>a.map((t=>e[t.name])))).flatMap((e=>e)),f=(0,d.getSystemLocale)(),y=(null==e?void 0:e.locale)?e.locale.toLowerCase()!==f?yield n.use(l.LocaleTranslation).getRecords({_in:{entryId:p},_eq:{localeCode:e.locale}},{projection:["entryId","localeCode","translation"]}):[]:yield n.use(l.LocaleTranslation).getRecords({_in:{entryId:p}},{projection:["entryId","localeCode","translation"]});if(y.length)if(null==e?void 0:e.locale)for(const t of u.records)for(const n of a){const i=y.find((i=>i.localeCode===e.locale&&i.entryId===t[n.name]));t[n.multiLocaleColumn]=null==i?void 0:i.translation}else for(const e of u.records)for(const t of a){const n=y.filter((n=>n.entryId===e[t.name]));e[t.name]=n.reduce(((e,t)=>Object.assign(e,{[t.localeCode]:t.translation})),{})}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),s=h.length?yield r.getMany({queries:{fields:{[t.hasMany.column]:h},limit:t.hasMany.single?1:0},queryProvider:n}):{records:[]};for(const e of u.records){const n=s.records.filter((n=>n[t.hasMany.column]===e.id));e[t.name]=t.hasMany.single?n[0]:n}}return yield this.beforeReturning(u.records),{total:u.total,records:this.project(u.records,(null==e?void 0:e.projection)&&[...e.projection,...c||[]].reduce(o.uniqueReducer,[]))}}))}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=[];const a=this.modelMetadata.fields.filter((e=>e.multiLocaleColumn));if(r.length||a.length){const e=yield n.use(this.model).getRecords(o,{projection:["id",...a.map((e=>e.name))]},r);yield n.use(this.model).deleteMany({_in:{id:e.map((e=>e.id))}});const t=e.map((e=>a.map((t=>e[t.name])))).flatMap((e=>e)).filter((e=>!!e));yield n.use(c.LocaleEntry).deleteMany({_in:{id:t}}),s=e}else s=yield n.use(this.model).deleteMany(o,null==e?void 0:e.returning);return{modified:s}}))}}t.ModelRepository=ModelRepository},2255:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractAccessCondition=void 0;t.AbstractAccessCondition=class AbstractAccessCondition{}},4192:function(e,t,n){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(2318),s=n(2255);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}},1071:function(e,t,n){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(2318),s=n(2255);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}},3198:function(e,t,n){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(2318),s=n(2255);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},341:function(e,t,n){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}),o(n(9025),t),o(n(4638),t),o(n(1820),t),o(n(1870),t),o(n(4972),t),o(n(8903),t),o(n(2417),t),o(n(1532),t),o(n(5879),t),o(n(6004),t),o(n(7282),t),o(n(4435),t),o(n(767),t),o(n(225),t),o(n(2255),t),o(n(1071),t),o(n(3198),t),o(n(4192),t),o(n(859),t),o(n(2085),t),o(n(531),t),o(n(7825),t),o(n(9837),t),o(n(3355),t),o(n(9073),t),o(n(8023),t),o(n(5048),t),o(n(5530),t),o(n(2841),t),o(n(7152),t),o(n(8577),t),o(n(2665),t),o(n(9990),t),o(n(6507),t),o(n(4839),t),o(n(5232),t),o(n(5572),t),o(n(10),t),o(n(5481),t),o(n(2552),t),o(n(889),t),o(n(5537),t),o(n(226),t),o(n(8836),t),o(n(9627),t),o(n(6721),t),o(n(204),t),o(n(7577),t),o(n(8709),t),o(n(1556),t),o(n(2363),t),o(n(4683),t),o(n(9527),t),o(n(3376),t),o(n(5033),t),o(n(523),t)},4683:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractJobController=void 0;const i=n(2318);t.AbstractJobController=class AbstractJobController{getAllJobs(){const e=(0,i.getObjectMetadata)(this.constructor);return(null==e?void 0:e.jobs)||[]}}},523:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractJobRepository=void 0;t.AbstractJobRepository=class AbstractJobRepository{}},9527:function(e,t,n){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.AbstractJobScheduler=void 0;const o=n(2318),r=n(4683);t.AbstractJobScheduler=class AbstractJobScheduler{constructor(e){this.logger=e,this._jobs=null}getAvailableJobInfo(){return i(this,void 0,void 0,(function*(){if(null===this._jobs){const e=(0,o.getServiceProvider)().getInjector(),t=e.resolveMultiple(r.AbstractJobController);yield e.initInstances(),this._jobs=t.flatMap((e=>e.getAllJobs().map((t=>Object.assign(Object.assign({},t),{handlerFn:e[t.handlerName].bind(e)})))))}return this._jobs}))}scheduleJobAt(e){return this.scheduleJob(e)}executeJob(e){return i(this,void 0,void 0,(function*(){const t=(yield this.getAvailableJobInfo()).find((t=>t.jobName===e.jobName));t&&(yield t.handlerFn(e.params)),t&&!e.at||(yield this.removeJob(e.jobId),this.logger.info(t?`Remove one-time job ${e.jobName} at timestamp ${e.at}`:`Remove not found job: ${e.jobName}`))}))}}},3376:function(e,t,n){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.AwsJobScheduler=void 0;const a=n(2318),d=s(n(9336)),l=s(n(1495)),c=n(9527),u=n(2363),gcdBetween=(e,t)=>{const n=e>t?e:t,i=e>t?t:e;if(n<=0||i<=0)return 1;if(n%i==0)return i;{const e=Math.trunc(n/i);return gcdBetween(i,n-i*e)}},gcdOf=(e,t)=>t.length?gcdOf(gcdBetween(e,t[0]),t.slice(1)):e,getWaitExpression=e=>`Wait ${e} seconds`;let h=class AwsJobScheduler extends c.AbstractJobScheduler{constructor(e,t,n,i,o,r,s="default",a="claire-aws-job-",c="one-minute-step-function-trigger"){super(e),this.logger=e,this.redisServerUrl=t,this.uniqueIdKey=n,this.apiLambdaFunctionArn=i,this.stepFunctionName=o,this.iamRoleArn=r,this.eventBusName=s,this.jobNamePrefix=a,this.oneMinuteRule=c,this.eventbridge=new d.default.EventBridge,this.stepfunctions=new d.default.StepFunctions({apiVersion:"2016-11-23"}),this.redisClient=new l.default(this.redisServerUrl)}init(){return r(this,void 0,void 0,(function*(){}))}exit(){this.redisClient.quit()}handleInterval(e){return r(this,void 0,void 0,(function*(){this.logger.debug("Handle interval",e,typeof e);const t=(yield this.getAvailableJobInfo()).filter((t=>t.interval&&e%t.interval==0));yield Promise.all(t.map((e=>this.executeJob(Object.assign(Object.assign({},e),{jobId:e.jobName})))))}))}handleCron(e){return r(this,void 0,void 0,(function*(){this.logger.debug("Handle cron",e),yield this.executeJob(e)}))}generateCronFromTimestamp(e){const t=new Date(e);return[t.getUTCMinutes(),t.getUTCHours(),t.getUTCDate(),t.getUTCMonth(),"?",t.getUTCFullYear()].join(" ")}isActiveScheduler(){return!1}getAllScheduledJobs(){return r(this,void 0,void 0,(function*(){const e=yield this.getAvailableJobInfo(),t=yield this.eventbridge.listRules({EventBusName:this.eventBusName,NamePrefix:this.jobNamePrefix}).promise();return(yield Promise.all((t.Rules||[]).map((e=>r(this,void 0,void 0,(function*(){var t;const n=e.Name,i=null===(t=(yield this.eventbridge.listTargetsByRule({EventBusName:this.eventBusName,Rule:n}).promise()).Targets)||void 0===t?void 0:t.find((e=>e.Id===n));if(!i||!i.Input)return;return JSON.parse(i.Input).requestContext.cronScheduler.data})))))).filter((e=>!!e)).concat(e.filter((e=>e.interval)).map((e=>Object.assign(Object.assign({},e),{jobId:e.jobName}))))}))}scheduleJob(e){return r(this,void 0,void 0,(function*(){if(this.logger.debug("Scheduling job: ",e),e.cron||e.at){const t=yield this.redisClient.incr(this.uniqueIdKey),n=`${this.jobNamePrefix}${t}`,i=`${e.cron} *`||this.generateCronFromTimestamp(e.at);return this.logger.debug("Cron expression",i),yield this.eventbridge.putRule({Name:n,Description:`${e.jobName} - ${e.cron||e.at}`,EventBusName:this.eventBusName,ScheduleExpression:`cron(${i})`,State:"ENABLED"}).promise(),yield this.eventbridge.putTargets({Rule:n,Targets:[{Arn:this.apiLambdaFunctionArn,Id:n,Input:JSON.stringify({requestContext:{cronScheduler:{data:Object.assign(Object.assign({},e),{jobId:n})}}})}]}).promise(),n}if(e.interval)return e.jobName;throw a.ErrorBuilder.systemError(`Job does not have time config: ${e.jobName}`)}))}syncJobs(){return r(this,void 0,void 0,(function*(){this.logger.debug("Checking interval scheduler"),yield this.checkIntervalScheduler();const e=yield this.getAllScheduledJobs(),t=yield this.getAvailableJobInfo(),n=e.filter((e=>!t.find((t=>t.jobName===e.jobName))));for(const e of n)this.logger.info(`Removing stale job: ${e.jobName} of id: ${e.jobId}`),yield this.removeJob(e.jobId);n.length&&this.logger.info(`Cleaned up: ${n.length} stale jobs`),this.logger.debug("Remove scheduled cron jobs");const i=e.filter((e=>e.cron));yield Promise.all(i.map((e=>this.removeJob(e.jobId))));const o=t.filter((e=>e.cron||e.interval));this.logger.debug("Scheduling cron & interval jobs");for(const e of o)yield this.scheduleJob({jobName:e.jobName,cron:e.cron,interval:e.interval})}))}removeJob(e){return r(this,void 0,void 0,(function*(){yield this.eventbridge.removeTargets({EventBusName:this.eventBusName,Rule:e,Ids:[e]}).promise(),yield this.eventbridge.deleteRule({EventBusName:this.eventBusName,Name:e}).promise()}))}checkIntervalScheduler(){var e,t;return r(this,void 0,void 0,(function*(){const n=(yield this.getAvailableJobInfo()).filter((e=>e.interval)),i=n.map((e=>e.interval)),[o,r]=((e,t)=>{let n=u.JobInterval.EVERY_30S;t.length&&(n=gcdOf(t[0],t.slice(1)),n<u.JobInterval.EVERY_5S&&(n=u.JobInterval.EVERY_5S));const i=Math.trunc(60/n),o=[];for(let e=0;e<i;e++)o.push(e*n);return[n,`\n {\n "StartAt": "Create items",\n "States": {\n "Create items": {\n "Type": "Pass",\n "Next": "Loop",\n "Result": ${JSON.stringify(o)}\n },\n "Loop": {\n "Type": "Map",\n "End": true,\n "Iterator": {\n "StartAt": "${getWaitExpression(n)}",\n "States": {\n "${getWaitExpression(n)}": {\n "Type": "Wait",\n "Seconds": ${n},\n "Next": "Convert time to request object"\n },\n "Convert time to request object": {\n "Type": "Pass",\n "Next": "Lambda Invoke",\n "Result": {\n "requestContext": {\n "intervalScheduler": {\n "time": "$"\n }\n }\n }\n },\n "Lambda Invoke": {\n "Type": "Task",\n "Resource": "arn:aws:states:::lambda:invoke",\n "Parameters": {\n "Payload.$": "$",\n "FunctionName": "${e}:$LATEST"\n },\n "End": true,\n "OutputPath": "$.Payload"\n }\n }\n },\n "MaxConcurrency": 1\n }\n },\n "Comment": "One minute loop to trigger lambda function"\n }\n `]})(this.apiLambdaFunctionArn,i);this.logger.debug("Listing all state machines");const s=yield this.stepfunctions.listStateMachines({}).promise();let a=null===(e=s.stateMachines.find((e=>e.name.includes(this.stepFunctionName))))||void 0===e?void 0:e.stateMachineArn,d=a;if(a){(yield this.stepfunctions.describeStateMachine({stateMachineArn:a}).promise()).definition.includes(getWaitExpression(o))||(this.logger.debug("Step function definition changed, create new state machine"),d="")}const l=`${this.stepFunctionName}-${o}`;if(!d){this.logger.debug(`Create new step function with interval ${o} seconds`);d=(yield this.stepfunctions.createStateMachine({definition:r,name:l,roleArn:this.iamRoleArn,type:"EXPRESS"}).promise()).stateMachineArn}this.logger.debug("Step function ARNs old / new",a,d),this.logger.debug("Getting one minute rule");const c=yield this.eventbridge.listRules({EventBusName:this.eventBusName,NamePrefix:this.oneMinuteRule}).promise(),h=null===(t=c.Rules)||void 0===t?void 0:t.find((e=>e.Name==this.oneMinuteRule));h||(this.logger.debug("Create new one minute rule"),yield this.eventbridge.putRule({EventBusName:this.eventBusName,Name:this.oneMinuteRule,Description:"One minute trigger function for step function",ScheduleExpression:"rate(1 minute)",State:"ENABLED"}).promise()),this.logger.debug("Adding step function state machine as target"),d!==a&&(a&&(this.logger.debug("Removing old target",a),yield this.eventbridge.removeTargets({EventBusName:this.eventBusName,Rule:this.oneMinuteRule,Ids:[this.stepFunctionName]}).promise(),this.logger.debug("Removing old state machine function"),yield this.stepfunctions.deleteStateMachine({stateMachineArn:a}).promise()),this.logger.debug("Adding new target",d),yield this.eventbridge.putTargets({Rule:this.oneMinuteRule,Targets:[{Arn:d,Id:this.stepFunctionName,RoleArn:this.iamRoleArn}]}).promise()),!n.length&&(null==h?void 0:h.State)?(this.logger.info("No interval job found, disable one minute rule"),yield this.eventbridge.disableRule({EventBusName:this.eventBusName,Name:this.oneMinuteRule}).promise()):(this.logger.info("Interval job found, enable one minute rule"),yield this.eventbridge.enableRule({EventBusName:this.eventBusName,Name:this.oneMinuteRule}).promise())}))}};h=i([(0,a.Initable)(),o("design:paramtypes",[a.AbstractLogger,String,String,String,String,String,Object,Object,Object])],h),t.AwsJobScheduler=h},5033:function(e,t,n){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.LocalJobScheduler=void 0;const a=n(2318),d=s(n(1495)),l=s(n(9896)),c=s(n(7344)),u=n(9527),h=n(523),p=n(9512);var f;!function(e){e.SCHEDULE_JOB="SCHEDULE_JOB",e.REMOVE_JOB="REMOVE_JOB",e.SYNC_JOB="SYNC_JOB",e.NOTIFY="NOTIFY"}(f||(f={}));let y=class LocalJobScheduler extends u.AbstractJobScheduler{constructor(e,t,n,i,o,r,s,a=30){super(e),this.logger=e,this.jobRepo=t,this.redisServerUrl=n,this.lockMutexKey=i,this.holdMutexKey=o,this.uniqueIdKey=r,this.multiClientChannel=s,this.keyRetentionDurationSecond=a,this.intervals=[],this.isActive=!1,this.notifyResolver={},this.jobHolder={},this.redisClient=new d.default(this.redisServerUrl),this.subscribeClient=this.redisClient.duplicate()}sendJob(e,t,n){this.subscribeClient.publish(this.multiClientChannel,JSON.stringify({type:e,messageId:t,data:n}))}processMessage(e,t,n){return r(this,void 0,void 0,(function*(){switch(e){case f.SYNC_JOB:yield this.syncJobs(),this.sendJob(f.NOTIFY,t);break;case f.NOTIFY:const i=this.notifyResolver[t];if(!i)return;i(n);break;case f.SCHEDULE_JOB:if(!this.isActive)return;const o=n,r=yield this.scheduleJobAt(o);this.sendJob(f.NOTIFY,t,r);break;case f.REMOVE_JOB:if(!this.isActive)return;const s=n;yield this.removeJob(s),this.sendJob(f.NOTIFY,t);break;default:this.logger.error(`Not recognize message type ${e}`)}}))}extendMutexKey(){return r(this,void 0,void 0,(function*(){this.redisClient&&(yield this.redisClient.setex(this.holdMutexKey,this.keyRetentionDurationSecond,1),this.logger.debug("Scheduler extends mutex key"))}))}init(){return r(this,void 0,void 0,(function*(){this.logger.debug("LocalJobScheduler init"),this.logger.debug("Listening on multi client channel"),this.redisClient.on("message",((e,t)=>{if(e===this.multiClientChannel){const e=JSON.parse(t);this.processMessage(e.type,e.messageId,e.data).catch((t=>this.logger.error(`Fail to process message, ${e}`,t)))}})),yield this.subscribeClient.subscribe(this.multiClientChannel),this.logger.debug("Try to claim active scheduler");const e=new l.default([this.redisClient]);try{const t=yield e.acquire([this.lockMutexKey],this.keyRetentionDurationSecond);this.isActive=!0,yield this.extendMutexKey(),yield t.release(),this.logger.debug("Being active scheduler"),this.mutexHoldInterval=setInterval((()=>{this.extendMutexKey()}),Math.trunc(1e3*this.keyRetentionDurationSecond/2)+1)}catch(e){this.logger.info("Failed to lock mutex key, ignore",e)}}))}exit(){this.mutexHoldInterval&&(0,p.clearInterval)(this.mutexHoldInterval),this.redisClient.quit(),this.subscribeClient.quit();for(const e of this.intervals)(0,p.clearInterval)(e);this.logger.debug("LocalJobScheduler exit")}isActiveScheduler(){return this.isActive}getAllScheduledJobs(){return r(this,void 0,void 0,(function*(){return Object.values(this.jobHolder).filter((e=>!!(null==e?void 0:e.jobInfo))).map((e=>null==e?void 0:e.jobInfo))}))}syncJobs(){return r(this,void 0,void 0,(function*(){if(!this.isActive){const e=yield this.redisClient.incr(this.uniqueIdKey);return new Promise((t=>{this.notifyResolver[e]=t,this.sendJob(f.SYNC_JOB,e)}))}{const e=yield this.getAvailableJobInfo();for(const t of e)(t.cron||t.interval)&&(yield this.scheduleJob(t));const t=yield this.jobRepo.getJobs();for(const e of t)yield this.scheduleJob(e)}}))}scheduleJob(e){return r(this,void 0,void 0,(function*(){if(this.isActive){if(e.at){const t=yield this.jobRepo.saveJob({jobName:e.jobName,params:e.params,at:e.at}),n=Object.assign(Object.assign({},e),{jobId:t}),i=c.default.scheduleJob(new Date(e.at),(()=>{this.executeJob(n).catch((e=>this.logger.error(`Error execute job ${n.jobName} with id: ${n.jobId}`,e)))}));return this.jobHolder[t]={jobCanceler:()=>i.cancel(),jobInfo:Object.assign(Object.assign({},e),{jobId:t})},t}if(e.interval){const t=e.jobName,n=Object.assign(Object.assign({},e),{jobId:t}),i=setInterval((()=>{this.executeJob(n).catch((e=>this.logger.error(`Error execute job ${n.jobName} with id: ${n.jobId}`,e)))}),e.interval);return this.jobHolder[t]={jobCanceler:()=>(0,p.clearInterval)(i),jobInfo:Object.assign(Object.assign({},e),{jobId:t})},t}if(e.cron){const t=e.jobName,n=Object.assign(Object.assign({},e),{jobId:t}),i=c.default.scheduleJob(e.cron,(()=>{this.executeJob(n).catch((e=>this.logger.error(`Error execute job ${n.jobName} with id: ${n.jobId}`,e)))}));return this.jobHolder[t]={jobCanceler:()=>i.cancel(),jobInfo:Object.assign(Object.assign({},e),{jobId:t})},t}throw a.ErrorBuilder.systemError(`Job does not have time config: ${e.jobName}`)}{const t=yield this.redisClient.incr(this.uniqueIdKey);return new Promise((n=>{this.notifyResolver[t]=n,this.sendJob(f.SCHEDULE_JOB,t,e)}))}}))}removeJob(e){return r(this,void 0,void 0,(function*(){if(this.isActive){const t=this.jobHolder[e];return t&&(t.jobCanceler(),this.jobHolder[e]=void 0),void(yield this.jobRepo.removeJobById(e))}{const t=yield this.redisClient.incr(this.uniqueIdKey);return new Promise((n=>{this.notifyResolver[t]=n,this.sendJob(f.REMOVE_JOB,t,e)}))}}))}};y=i([(0,a.Initable)(),o("design:paramtypes",[a.AbstractLogger,h.AbstractJobRepository,String,String,String,String,String,Number])],y),t.LocalJobScheduler=y},1556:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CustomJob=t.CronJob=t.IntervalJob=void 0;const i=n(2318);t.IntervalJob=(e,t)=>(n,o)=>{const r=(0,i.initObjectMetadata)(n);r.jobs||(r.jobs=[]),r.jobs.push({jobName:e,interval:t,handlerName:o})};t.CronJob=(e,t)=>(n,o)=>{const r=(0,i.initObjectMetadata)(n);if(r.jobs||(r.jobs=[]),5!==t.split(" ").length)throw i.ErrorBuilder.systemError("Invalid cron expression, expect minute / hour / day / month / day-of-week");r.jobs.push({jobName:e,cron:t,handlerName:o})};t.CustomJob=e=>(t,n)=>{const o=(0,i.initObjectMetadata)(t);o.jobs||(o.jobs=[]),o.jobs.push({jobName:e,handlerName:n})}},2363:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.JobInterval=t.CRON_REQUEST_METHOD=t.INTERVAL_REQUEST_METHOD=void 0,t.INTERVAL_REQUEST_METHOD="interval",t.CRON_REQUEST_METHOD="cron",function(e){e[e.EVERY_5S=5]="EVERY_5S",e[e.EVERY_10S=10]="EVERY_10S",e[e.EVERY_15S=15]="EVERY_15S",e[e.EVERY_20S=20]="EVERY_20S",e[e.EVERY_30S=30]="EVERY_30S"}(t.JobInterval||(t.JobInterval={}))},5572:function(e,t,n){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(7147)),l=a(n(1017)),c=n(2318);let u=i=class FileLogMedium{constructor(e){const t=e.separated?i.levels.map((t=>l.default.join(e.destination,t+".log"))):[e.destination];this.destination=t.map((e=>(d.default.existsSync(l.default.dirname(e))||d.default.mkdirSync(l.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(c.LogLevel),u=i=o([(0,c.Initable)(),r("design:paramtypes",[Object])],u),t.FileLogMedium=u},7577:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractCacheService=void 0;t.AbstractCacheService=class AbstractCacheService{}},8709:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractFileService=void 0;t.AbstractFileService=class AbstractFileService{}},204:function(e,t,n){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(7756);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)}))}}},6862:function(e,t,n){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.AbstractServerSocket=void 0;const o=n(2318);t.AbstractServerSocket=class AbstractServerSocket{constructor(e){this.socketInfo=e}getId(){return this.socketInfo.id}getAuthInfo(){return this.socketInfo.authInfo}send(e,t){return i(this,void 0,void 0,(function*(){t?this.socketInfo.channels.find((e=>e.name===t&&e.serverToClientAllowed))&&(yield this.sendRaw({type:o.MessageType.PLAIN,data:{message:e,channel:t}})):yield this.sendRaw({type:o.MessageType.PLAIN,data:{message:e}})}))}sendRaw(e){return i(this,void 0,void 0,(function*(){yield this.physicSend(e)}))}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}}},5530:function(e,t,n){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())}))},r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractServerSocketManager=void 0;const s=n(2318),a=r(n(1495)),d=n(9990),l=n(2665),c=n(2255),u=n(1532),h="x-socket-action",p="read",f="write";let y=class SocketReadCondition extends c.AbstractAccessCondition{resolveConditionValue(e){return o(this,void 0,void 0,(function*(){return e.getHeaders()["x-socket-action"]===p}))}validate(e){return o(this,void 0,void 0,(function*(){return!!e}))}getConditionMetadata(){return{name:"socket_read",description:"Can receive message from channel",valueType:s.AccessConditionValueType.BOOLEAN}}};y=i([(0,s.Register)()],y);let g=class SocketWriteCondition extends c.AbstractAccessCondition{resolveConditionValue(e){return o(this,void 0,void 0,(function*(){return e.getHeaders()["x-socket-action"]===f}))}validate(e){return o(this,void 0,void 0,(function*(){return!!e}))}getConditionMetadata(){return{name:"socket_write",description:"Can send message to channel",valueType:s.AccessConditionValueType.BOOLEAN}}};g=i([(0,s.Register)()],g);t.AbstractServerSocketManager=class AbstractServerSocketManager{constructor(e,t,n,i,o){this.requireAuthentication=e,this.logger=t,this.redisServerUrl=n,this.authProvider=i,this.authResolver=o,this._connectionHandler=null,this.redisClient=new a.default(this.redisServerUrl)}getUniqueChannelPrefix(){return"CHANNEL:"}getSocketInfoHashKey(){return"__SOCKET_INFO__"}getConnectionHandler(){return o(this,void 0,void 0,(function*(){if(null===this._connectionHandler){const e=(0,s.getServiceProvider)().getInjector();this._connectionHandler=e.resolveOptional(d.AbstractSocketConnectionHandler),yield e.initInstances()}return this._connectionHandler}))}formatBroadcastData(e,t){return{type:s.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 this.redisClient.smembers(this.getUniqueChannelName(e)))||[]}))}addSocketToChannel(e,t){return o(this,void 0,void 0,(function*(){const n=yield this.getById(e);return n&&(n.addChannels(t),yield Promise.all(t.map((t=>this.redisClient.sadd(this.getUniqueChannelName(t.name),e)))),yield n.saveSocketInfo()),n}))}removeSocketFromChannel(e,t,n=!0){return o(this,void 0,void 0,(function*(){if(!t.length)return;const i=yield this.getById(e);i&&(i.removeChannels(t),yield Promise.all(t.map((t=>this.redisClient.srem(this.getUniqueChannelName(t),e)))),n&&(yield i.saveSocketInfo()))}))}removeSocket(e,t=!0){return o(this,void 0,void 0,(function*(){const t=yield this.getById(e);t&&(this.logger.debug("Remove from all channels"),yield this.removeSocketFromChannel(e,t.getChannelsInfo().map((e=>e.name)),!1)),this.logger.debug("Remove from redis"),yield this.redisClient.hdel(this.getSocketInfoHashKey(),e)}))}handle(e){var t;return o(this,void 0,void 0,(function*(){this.logger.debug("Handle socket data",e);const n=yield this.getConnectionHandler();switch(e.method){case s.SocketMethod.CONNECT:{this.logger.debug("Socket connection attempt",e);const n=this.authResolver(null===(t=e.data)||void 0===t?void 0:t.queries),i=yield this.authProvider.getPrincipalResolver().resolvePrincipal(n);if(!i&&this.requireAuthentication)throw s.ErrorBuilder.error(s.Errors.AUTHENTICATION_ERROR);yield this.addSocket({id:e.socketId,authInfo:i,channels:[],createdAt:Date.now()},e.data);break}case s.SocketMethod.DISCONNECT:{this.logger.debug("Socket disconnect",e);const t=yield this.getById(e.socketId);if(t){const e=yield this.getMountedEndpointInfo();this.logger.debug("Notify channels");for(const n of t.getChannelsInfo()){const i=e.find((e=>e.endpointMetadata.url===n.name));i&&i.endpoint.controller.onChannelLeave(t)}this.logger.debug("Calling disconnection handler"),null==n||n.onSocketDisconnect(t),this.logger.debug("Removing socket"),yield this.removeSocket(t.getId(),!1)}break}case s.SocketMethod.MESSAGE:{this.logger.debug("Socket message",e);const t=e.data;let i=yield this.getById(e.socketId);if(i)switch(t.type){case s.MessageType.READY:yield i.sendRaw({type:s.MessageType.READY,data:""}),yield null==n?void 0:n.onSocketConnect(i);break;case s.MessageType.PING_PONG:yield i.sendRaw({type:s.MessageType.PING_PONG,data:t.data});break;case s.MessageType.CHANNEL_JOIN:{const e=t.data,n=[],o=[];for(const t of e){let e=!1,r=!1;const a=(yield this.getMountedEndpointInfo()).find((e=>e.endpointMetadata.url===t));if(a){try{const e=new u.HttpRequest({method:s.SocketMethod.MESSAGE,pathName:t,headers:{[h]:p}},a.endpointMetadata);yield this.authProvider.authorize(i.getAuthInfo(),e,a),r=!0}catch(e){this.logger.debug("Error in read authorize",e)}try{const n=new u.HttpRequest({method:s.SocketMethod.MESSAGE,pathName:t,headers:{[h]:f}},a.endpointMetadata);yield this.authProvider.authorize(i.getAuthInfo(),n,a),e=!0}catch(e){this.logger.debug("Error in write authorize",e)}(e||r)&&(this.logger.debug("Adding channel info",t,e,r),n.push({name:t,clientToServerAllowed:e,serverToClientAllowed:r}),o.push(a))}}i=yield this.addSocketToChannel(i.getId(),n),i?yield Promise.all([i.sendRaw({type:s.MessageType.CHANNEL_JOIN,data:n.map((e=>e.name))}),...o.map((e=>e.endpoint.controller.onChannelJoin(i)))]):this.logger.debug("Socket not found after addSocketToChannel")}break;case s.MessageType.CHANNEL_LEAVE:{const e=t.data,n=yield this.getMountedEndpointInfo();Promise.all(e.map((e=>()=>{const t=n.find((t=>t.endpointMetadata.url===e));if(t)return t.endpoint.controller.onChannelLeave(i)}))),yield this.removeSocketFromChannel(i.getId(),e)}break;case s.MessageType.PLAIN:{const e=t.data.channel,o=t.data.message;if(e){if(i.getChannelsInfo().find((t=>t.name===e&&t.clientToServerAllowed))){const t=(yield this.getMountedEndpointInfo()).find((t=>t.endpointMetadata.url===e));if(t){!1!==(yield t.endpoint.controller.onMessage(i,o))&&(this.logger.debug("broadcasting to channel",e,o),this.broadcastToChannel(e,o))}}}else yield null==n?void 0:n.onMessage(i,o)}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,s.getServiceProvider)().getInjector(),t=e.resolveMultiple(l.AbstractSocketController);yield e.initInstances(),this.mountedEndpointInfo=t.map((e=>({endpoint:{httpMethod:s.SocketMethod.MESSAGE,mount:e.channel,controller:e,handlerFunctionName:e.onMessage.name},endpointMetadata:{httpMethod:s.SocketMethod.MESSAGE,description:"Send / Receive message to / from channel",dataType:s.DataType.OBJECT,url:e.channel,name:e.channel,accessConditions:[y,g]}})))}return this.mountedEndpointInfo}))}}},9990:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractSocketConnectionHandler=void 0;t.AbstractSocketConnectionHandler=class AbstractSocketConnectionHandler{}},2665:function(e,t){var n=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.AbstractSocketController=void 0;t.AbstractSocketController=class AbstractSocketController{constructor(e){this.channel=e}onChannelJoin(e){return n(this,void 0,void 0,(function*(){}))}onChannelLeave(e){return n(this,void 0,void 0,(function*(){}))}onMessage(e,t){return n(this,void 0,void 0,(function*(){}))}}},7152:function(e,t,n){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(2318),d=s(n(9336)),l=n(767),c=n(5530),u=n(6862),h=n(859);class ApiGatewaySocket extends u.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*(){yield this.redisClient.hset(this.socketNamespace,this.socketInfo.id,JSON.stringify(this.socketInfo))}))}physicSend(e){return r(this,void 0,void 0,(function*(){this.logger.debug("aws socket physic send",e),yield this.socketManager.physicSend(this.getId(),e)}))}disconnect(e){return r(this,void 0,void 0,(function*(){e&&(yield this.physicSend(e)),yield this.socketManager.removeSocket(this.getId())}))}serialize(){return JSON.stringify(this.socketInfo)}}let p=class AwsSocketManager extends c.AbstractServerSocketManager{constructor(e,t,n,i,o,r,s,a){super(e,a,i,r,s),this.authenticationRequired=e,this.region=t,this.socketDomainUrl=n,this.redisServerUrl=i,this.httpRequestHandler=o,this.authorizationProvider=r,this.authResolver=s,this.logger=a,this.apiGatewayManagement=new d.default.ApiGatewayManagementApi({region:t,apiVersion:"2018-11-29",endpoint:n})}init(){return r(this,void 0,void 0,(function*(){this.logger.info("AwsSocketManager init")}))}exit(){this.redisClient.disconnect(),this.logger.info("AwsSocketManager exit")}removeSocketFromRedis(e){return r(this,void 0,void 0,(function*(){yield this.redisClient.hdel(this.getSocketInfoHashKey(),e)}))}physicSend(e,t){return r(this,void 0,void 0,(function*(){try{this.logger.debug(`Socket ${e} sending`,t),yield this.apiGatewayManagement.postToConnection({ConnectionId:e,Data:JSON.stringify(t)}).promise()}catch(t){throw this.logger.debug(`Socket ${e} post error`,t),410===t.statusCode&&(this.logger.debug(`Disconnect & remove stale socket ${e}`),yield this.removeSocket(e,!1),this.logger.debug(`Socket removed ${e}`)),t}}))}configure(e){this.logger.debug("Aws socket manager configure")}getSocketsByChannel(e){return r(this,void 0,void 0,(function*(){const t=yield this.getSocketIdsOfChannel(e);if(!t.length)return[];return(yield this.redisClient.hmget(this.getSocketInfoHashKey(),...t)).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);if(n.length){const i=this.formatBroadcastData(e,t);n.map((e=>this.physicSend(e,i).catch((t=>this.logger.error(`Cannot send to socket ${e}`,t)))))}}))}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 yield t.saveSocketInfo(),t}))}removeSocket(e,t=!0){const n=Object.create(null,{removeSocket:{get:()=>super.removeSocket}});return r(this,void 0,void 0,(function*(){this.logger.debug(`Aws socket manager remove socket: ${e}, ${t}`),yield n.removeSocket.call(this,e,t),this.logger.debug("Super remove ok"),t&&this.apiGatewayManagement.deleteConnection({ConnectionId:e}).promise().catch((e=>this.logger.error("Cannot physic remove aws socket",e)))}))}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 this.redisClient.hget(this.getSocketInfoHashKey(),e);if(t)return this.logger.debug("Serialized aws socket",t),this.getSocketBySerialized(t);this.logger.error("Cannot find socket with id: "+e)}))}};p=i([(0,a.Initable)(),o("design:paramtypes",[Boolean,String,String,String,l.AbstractHttpRequestHandler,h.AbstractHttpAuthorizationProvider,Function,a.AbstractLogger])],p),t.AwsSocketManager=p},8577:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},2841:function(e,t,n){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(2318),d=s(n(5352)),l=s(n(9215)),c=s(n(9103)),u=n(5530),h=n(6862),p=n(859);var f;!function(e){e.SEND="SEND",e.CLOSE="CLOSE",e.SAVE="SAVE"}(f||(f={}));class RedisSocket extends h.AbstractServerSocket{constructor(e,t,n){super(n),this.socketChannelName=e,this.redisClient=t,this.socketInfo=n}physicSend(e){return r(this,void 0,void 0,(function*(){yield this.redisClient.publish(this.socketChannelName,JSON.stringify({type:f.SEND,data:e}))}))}disconnect(e){return r(this,void 0,void 0,(function*(){yield this.redisClient.publish(this.socketChannelName,JSON.stringify({type:f.CLOSE,data:e}))}))}saveSocketInfo(){return r(this,void 0,void 0,(function*(){yield this.redisClient.publish(this.socketChannelName,JSON.stringify({type:f.SAVE,data:this.socketInfo}))}))}}class ExpressSocket extends h.AbstractServerSocket{constructor(e,t,n,i,o){super(i),this.socketManager=e,this.logger=t,this.socket=n,this.socketInfo=i,this.infoSaver=o}saveSocketInfo(){return r(this,void 0,void 0,(function*(){yield this.infoSaver(this.socketInfo)}))}physicSend(e){return r(this,void 0,void 0,(function*(){this.socket.send(JSON.stringify(e))}))}disconnect(e){return r(this,void 0,void 0,(function*(){this.socket.close(1e3,e&&JSON.stringify(e)),yield this.socketManager.removeSocket(this.getId())}))}}let y=class LocalSocketManager extends u.AbstractServerSocketManager{constructor(e,t,n,i,o){super(e,n,t,i,o),this.authenticationRequired=e,this.redisServerUrl=t,this.logger=n,this.authProvider=i,this.authResolver=o,this.allSockets=[],this.subscribedChannels=[],this.subClient=this.redisClient.duplicate(),this.channelSubClient=this.redisClient.duplicate(),this.sendClient=this.redisClient.duplicate()}init(){return r(this,void 0,void 0,(function*(){this.logger.info("LocalSocketManager init"),this.channelSubClient.on("message",((e,t)=>{this.logger.debug("channelSubClient: ",t,e),this.channelMessageListenner(t,e)})),this.subClient.on("message",((e,t)=>{this.logger.debug("subClient: ",t,e),this.socketMessageListener(t,e)}))}))}exit(){this.sendClient.disconnect(),this.subClient.disconnect(),this.channelSubClient.disconnect(),this.redisClient.disconnect(),this.logger.info("LocalSocketManager exit")}channelMessageListenner(e,t){this.logger.debug("Receiving message from channel",t,e);const n=JSON.parse(e);n.type===a.MessageType.PLAIN&&this.allSockets.forEach((e=>{e.send(n.data.message,n.data.channel)}))}socketMessageListener(e,t){this.logger.debug("Receiving message from remote socket channel",t,e);const n=t.substring(this.getSocketChannelKeyPrefix().length),i=this.allSockets.find((e=>e.getId()===n));if(i){const t=JSON.parse(e);switch(t.type){case f.SEND:i.physicSend(t.data);break;case f.SAVE:i.socketInfo.channels=t.data,i.saveSocketInfo();break;case f.CLOSE:i.disconnect(t.data);break;default:this.logger.debug("Invalid remote command",t)}}}getUniqueDataChannelName(e){return`CHANNEL_DATA:${e}`}getSocketChannelKeyPrefix(){return"SOCKET_CHANNEL:"}getSocketChannelKey(e){return`${this.getSocketChannelKeyPrefix()}${e}`}broadcastToChannel(e,t){return r(this,void 0,void 0,(function*(){const n=this.formatBroadcastData(e,t);yield this.redisClient.publish(this.getUniqueDataChannelName(e),JSON.stringify(n))}))}addSocketToChannel(e,t){const n=Object.create(null,{addSocketToChannel:{get:()=>super.addSocketToChannel}});return r(this,void 0,void 0,(function*(){const i=yield n.addSocketToChannel.call(this,e,t),o=t.map((e=>e.name)).filter((e=>!this.subscribedChannels.includes(e)));return o.length&&(yield Promise.all(o.map((e=>this.channelSubClient.subscribe(this.getUniqueDataChannelName(e))))),this.subscribedChannels.push(...o)),i}))}removeSocketFromChannel(e,t,n=!0){const i=Object.create(null,{removeSocketFromChannel:{get:()=>super.removeSocketFromChannel}});return r(this,void 0,void 0,(function*(){yield i.removeSocketFromChannel.call(this,e,t,n),yield Promise.all(t.map((e=>this.channelSubClient.unsubscribe(this.getUniqueChannelName(e))))),this.subscribedChannels=this.subscribedChannels.filter((e=>!t.includes(e)))}))}addSocket(e,{socket:t}){return r(this,void 0,void 0,(function*(){const n=new ExpressSocket(this,this.logger,t,e,(e=>r(this,void 0,void 0,(function*(){yield this.redisClient.hset(this.getSocketInfoHashKey(),e.id,JSON.stringify(e))})))),i=this.getSocketChannelKey(e.id);return yield this.subClient.subscribe(i),this.allSockets.push(n),n}))}removeSocket(e,t=!0){const n=Object.create(null,{removeSocket:{get:()=>super.removeSocket}});return r(this,void 0,void 0,(function*(){yield n.removeSocket.call(this,e,t);const i=this.getSocketChannelKey(e);yield this.subClient.unsubscribe(i),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).then((e=>t(e?JSON.parse(e):void 0))).catch((e=>{this.logger.error(e),t(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"];let i=!1,o=[];const r=(0,l.default)({url:t.url}),s=c.default.parse(decodeURIComponent(r.search||""));this.handle({method:a.SocketMethod.CONNECT,socketId:n,data:{queries:s,socket:e}}).then((()=>{i=!0;for(const e of o)this.handle(e).catch((e=>{this.logger.error(e)}))})).catch((t=>{o=[],e.close(1e3,`${t.name}:${t.message}`)})),e.onmessage=e=>{const t={method:a.SocketMethod.MESSAGE,socketId:n,data:e.data&&JSON.parse(e.data)};i?this.handle(t).catch((e=>{this.logger.error(e)})):o.push(t)},e.onclose=()=>{this.handle({method:a.SocketMethod.DISCONNECT,socketId:n}).catch((e=>{this.logger.error(e)}))}}))}};y=i([(0,a.Initable)(),o("design:paramtypes",[Boolean,String,a.AbstractLogger,p.AbstractHttpAuthorizationProvider,Function])],y),t.LocalSocketManager=y},5537:function(e,t,n){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(2318),r=n(137),s=n(4972);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},226:function(e,t,n){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(2318),s=o(n(6860)),a=o(n(3685)),d=o(n(3582)),l=o(n(6674)),c=n(5530),u=n(767);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(c.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)(),c=a.default.createServer(o);return null===(t=this.socketManager)||void 0===t||t.configure(c),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,l.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()};if(n.method===r.SocketMethod.CONNECT){const t=e.body.data.querystring,i=t.substring(1,t.length-1).split(",").map((e=>e.trim().split("="))).reduce(((e,t)=>Object.assign(e,{[t[0]]:t[1]})),{});n.data={queries:i}}yield this.socketManager.handle(n).then((()=>{t.status(200).send()})).catch((e=>{this.logger.debug("Handle error",e),t.status(400).json({name:e.name,message:e.message})}))}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=c.listen(e,t).on("error",n)}))}))}}},8836:function(e,t,n){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(2318),r=n(767),s=n(3376),a=n(2363),d=n(5530),l=n(6721),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.serverFactory=e,this.requestMapper=t,this.requestMapper=t,this.handler=this.handler.bind(this),this.injector=(0,o.getServiceProvider)().getInjector(),this.logger=this.injector.resolve(o.AbstractLogger),this.socketManager=this.injector.resolveOptional(d.AbstractServerSocketManager),this.httpRequestHandler=this.injector.resolveOptional(r.AbstractHttpRequestHandler),this.jobScheduler=this.injector.resolveOptional(s.AwsJobScheduler)}bootServer(){var e;return i(this,void 0,void 0,(function*(){return this._server||(this._server=yield this.serverFactory(),yield this.injector.initInstances(),null===(e=this.socketManager)||void 0===e||e.configure(),yield this._server.init()),this._server}))}handler(e){var t,n;return i(this,void 0,void 0,(function*(){yield this.bootServer();const i=this.requestMapper(e);if(!i)return toApiGatewayFormat(400,"Cannot resolve event");if(i.method===o.HttpMethod.OPTIONS)return toApiGatewayFormat(200);if(i.method===a.INTERVAL_REQUEST_METHOD)return yield null===(t=this.jobScheduler)||void 0===t?void 0:t.handleInterval(i.body),toApiGatewayFormat(200);if(i.method===a.CRON_REQUEST_METHOD)return yield null===(n=this.jobScheduler)||void 0===n?void 0:n.handleCron(i.body),toApiGatewayFormat(200);try{if(Object.values(o.HttpMethod).includes(i.method)){if(!this.httpRequestHandler)throw o.ErrorBuilder.error(l.Errors.SYSTEM_ERROR,"Http request handler not found");const e={fullPath:i.rawPath,method:i.method,headers:i.headers,body:i.body},t=yield this.httpRequestHandler.handle(e);return toApiGatewayFormat(t.code,t.value)}if(!Object.values(o.SocketMethod).includes(i.method))throw o.ErrorBuilder.error(l.Errors.HTTP_REQUEST_ERROR,"Not allow request method: "+i.method);{if(!this.socketManager)throw o.ErrorBuilder.error(l.Errors.SYSTEM_ERROR,"Socket manager not found");const e={socketId:i.rawPath,method:i.method,data:i.body};yield this.socketManager.handle(e)}return toApiGatewayFormat(200)}catch(e){return toApiGatewayFormat(400,{name:e.name,message:e.message})}}))}}},9627:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getSystemLocale=t.setSystemLocale=void 0;const i=n(2318);t.setSystemLocale=e=>{(0,i.getGlobalStore)().systemLocale=e};t.getSystemLocale=()=>{var e;return(null===(e=(0,i.getGlobalStore)().systemLocale)||void 0===e?void 0:e.toLowerCase())||""}},6721:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Errors=void 0;const i=n(2318);t.Errors=Object.assign(Object.assign({},i.Errors),{TFA_REQUIRED:"TFA_REQUIRED"})},889:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.lambdaRequestMapper=void 0;const i=n(2318),o=n(2363);t.lambdaRequestMapper=e=>{if(e.requestContext.eventType){const t=e.requestContext.eventType.toLowerCase(),n=e.body&&JSON.parse(e.body);return{method:t,rawPath:e.requestContext.connectionId,body:t===i.SocketMethod.CONNECT?{queries:e.queryStringParameters}:n}}return e.requestContext.intervalScheduler?{method:o.INTERVAL_REQUEST_METHOD,rawPath:"",body:e.requestContext.intervalScheduler.time}:e.requestContext.cronScheduler?{method:o.CRON_REQUEST_METHOD,rawPath:"",body:e.requestContext.cronScheduler.data}:{method:e.requestContext.http.method.toLowerCase(),rawPath:`${e.rawPath}?${e.rawQueryString}`,body:e.body&&JSON.parse(e.body),headers:e.headers}}},5481:function(e,t,n){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};Object.defineProperty(t,"__esModule",{value:!0}),t.LocaleEntry=void 0;const o=n(2318);let r=class LocaleEntry extends o.AbstractModel{};r=i([(0,o.Model)()],r),t.LocaleEntry=r},2552:function(e,t,n){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)};Object.defineProperty(t,"__esModule",{value:!0}),t.LocaleTranslation=void 0;const r=n(2318),s=n(5481),a="translation_unique";let d=class LocaleTranslation extends r.AbstractModel{};i([(0,r.Column)(Object.assign(Object.assign({description:"Id of the locale",isRequired:!0},(0,r.FK)({model:s.LocaleEntry,cascade:"delete"})),{unique:{groupName:a}})),o("design:type",Number)],d.prototype,"entryId",void 0),i([(0,r.Column)({description:"Code of locale",isRequired:!0,unique:{groupName:a},textLength:3}),o("design:type",String)],d.prototype,"localeCode",void 0),i([(0,r.Column)({description:"Translation of locale",isRequired:!0}),o("design:type",String)],d.prototype,"translation",void 0),d=i([(0,r.Model)()],d),t.LocaleTranslation=d},10:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.LocaleOf=void 0;const i=n(2318),o=n(5481);t.LocaleOf=e=>(t,n)=>{const r=(0,i.initFieldMetadata)(t,n);r.multiLocaleColumn=e,r.fk=(0,i.FK)({model:o.LocaleEntry,cascade:"nullify"}).fk,r.dataType=i.DataType.NUMBER;(0,i.initFieldMetadata)(t,e).isMultiLocale=!0}},2318:e=>{e.exports=require("@clairejs/core")},7756:e=>{e.exports=require("@clairejs/orm")},9336:e=>{e.exports=require("aws-sdk")},3582:e=>{e.exports=require("cors")},6860:e=>{e.exports=require("express")},6674:e=>{e.exports=require("express-fileupload")},1495:e=>{e.exports=require("ioredis")},7344:e=>{e.exports=require("node-schedule")},9215:e=>{e.exports=require("parseurl")},99:e=>{e.exports=require("path-to-regexp")},9103:e=>{e.exports=require("query-string")},9896:e=>{e.exports=require("redlock")},5352:e=>{e.exports=require("ws")},7147:e=>{e.exports=require("fs")},3685:e=>{e.exports=require("http")},1017:e=>{e.exports=require("path")},9512:e=>{e.exports=require("timers")}},t={};var n=function __webpack_require__(n){var i=t[n];if(void 0!==i)return i.exports;var o=t[n]={exports:{}};return e[n].call(o.exports,o,o.exports,__webpack_require__),o.exports}(341);return n})()));
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 i=t();for(var n in i)("object"==typeof exports?exports:e)[n]=i[n]}}(global,(()=>(()=>{"use strict";var e={9025:(e,t)=>{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={}))},4638:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractPrincipalResolver=void 0;t.AbstractPrincipalResolver=class AbstractPrincipalResolver{}},1820:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},137:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ExitCode=void 0,t.ExitCode={SIGTERM_INTERUPTION:-1,SIGINT_INTERUPTION:-2,UNCAUGHT_EXCEPTION:-3,UNHANDLED_REJECTION:-4}},4435:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},4972:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getEndpointId=void 0;t.getEndpointId=e=>`${e.httpMethod}:${e.mount}`},1870:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},859:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractHttpAuthorizationProvider=void 0;t.AbstractHttpAuthorizationProvider=class AbstractHttpAuthorizationProvider{}},2085:function(e,t,i){var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(o,r){function fulfilled(e){try{step(n.next(e))}catch(e){r(e)}}function rejected(e){try{step(n.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((n=n.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractRbacAuthProvider=void 0;const o=i(2318),r=i(859),s=i(4972);class AbstractRbacAuthProvider extends r.AbstractHttpAuthorizationProvider{constructor(e,t,i){super(),this.authDataResolver=e,this.principalResolver=t,this.logger=i}getPrincipalResolver(){return this.principalResolver}resolvePrincipal(e){return this.principalResolver.resolvePrincipal(this.authDataResolver(e))}authorize(e,t,i){return n(this,void 0,void 0,(function*(){if(i.endpointMetadata.openAccess)return;const n=yield this.getRbacCache();if(!n)throw o.ErrorBuilder.error(o.Errors.SYSTEM_ERROR,"Cannot read rbac cache");let r=[];if(e){const t=yield this.getRolesOfPrincipal(e);r=(n.roles||[]).filter((e=>!!t.find((t=>t===e.roleId))))}else r=(n.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=(n.rolePolicies||[]).filter((e=>!!r.find((t=>t.roleId===e.roleId)))),d=(n.policies||[]).filter((e=>!!a.find((t=>t.policyId===e.policyId)))),l=(n.policyPermissions||[]).filter((e=>!!d.find((t=>t.policyId===e.policyId)))),c=(n.policyPermissionConditions||[]).filter((e=>!!l.find((t=>t.id===e.policyPermissionId)))),u=l.filter((e=>e.permission===(0,s.getEndpointId)(i.endpoint)));if(!u.length)throw o.ErrorBuilder.error(o.Errors.ACCESS_DENIED,`Not permitted: ${(0,s.getEndpointId)(i.endpoint)}`);let h=!1;for(const e of u){const n=c.filter((t=>t.policyPermissionId===e.id));if(n.length){let e=!0;const r=(0,o.getServiceProvider)().getInjector(),s=(i.endpointMetadata.accessConditions||[]).map((e=>r.resolve(e)));yield r.initInstances();for(const i of n){const n=s.find((e=>e.getConditionMetadata().name===i.conditionName));if(!n)continue;const o=yield n.resolveConditionValue(t),r=JSON.parse(i.conditionValue);if(e=yield n.validate(o,r),!e){this.logger.debug("Condition check failed: condition, requested, permitted",i.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},531:function(e,t,i){var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(o,r){function fulfilled(e){try{step(n.next(e))}catch(e){r(e)}}function rejected(e){try{step(n.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((n=n.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.RedisRbacAuthProvider=void 0;const o=i(2085);class RedisRbacAuthProvider extends o.AbstractRbacAuthProvider{constructor(e,t,i,n,o,r,s,a=3e4){super(n,o,s),this.serviceIdResolver=e,this.rbacChannel=t,this.principalChannel=i,this.authDataResolver=n,this.principalResolver=o,this.cacheService=r,this.logger=s,this.redisDataRetentionDurationMs=a,this.lastRbacFetchTimestamp=0,this.principalCache={},this.serviceId=""}getRbacCache(){return n(this,void 0,void 0,(function*(){if(this.lastRbacFetchTimestamp+this.redisDataRetentionDurationMs<Date.now()){this.serviceId||(this.serviceId=yield this.serviceIdResolver());const e=yield this.cacheService.hget(this.rbacChannel,this.serviceId);this.rbacCache=e,this.lastRbacFetchTimestamp=Date.now()}return this.rbacCache}))}getRolesOfPrincipal(e){return n(this,void 0,void 0,(function*(){const t=String(e.id);let i=this.principalCache[t];if(!i||i.lastFetchTimestamp+this.redisDataRetentionDurationMs<Date.now()){const e=yield this.cacheService.hget(this.principalChannel,t),n=e?"string"==typeof e?JSON.parse(e):e:[];i={lastFetchTimestamp:Date.now(),roles:n},this.principalCache[t]=i}return i.roles}))}}t.RedisRbacAuthProvider=RedisRbacAuthProvider},7825:function(e,t,i){var n=this&&this.__decorate||function(e,t,i,n){var o,r=arguments.length,s=r<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,n);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,i,s):o(t,i))||s);return r>3&&s&&Object.defineProperty(t,i,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,i,n){return new(i||(i=Promise))((function(o,r){function fulfilled(e){try{step(n.next(e))}catch(e){r(e)}}function rejected(e){try{step(n.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((n=n.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.SocketRbacAuthProvider=void 0;const s=i(2318),a=i(2085),d=i(4638);let l=class SocketRbacAuthProvider extends a.AbstractRbacAuthProvider{constructor(e,t,i,n,o,r){super(i,n,o),this.rbacCacheChannel=e,this.principalCacheChannel=t,this.authDataResolver=i,this.principalResolver=n,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:i}=e,n=this.idResolvers.find((e=>e.principalId===t));if(n){for(const e of n.resolvers)e(i);n.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 i;let n=this.idResolvers.find((t=>t.principalId===e.id));n||(n={principalId:e.id,resolvers:[]},this.idResolvers.push(n)),n.resolvers.length||null===(i=this.socket)||void 0===i||i.send(e.id,this.principalCacheChannel),n.resolvers.push(t)}))}))}};l=n([(0,s.Initable)(),o("design:paramtypes",[String,String,Function,d.AbstractPrincipalResolver,s.AbstractLogger,Function])],l),t.SocketRbacAuthProvider=l},9837:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},1532:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HttpRequest=void 0;const n=i(2318);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,n.validateData)(this.params,null==t?void 0:t.paramsValidationDto)),this.query=e.query||{},(null==t?void 0:t.queriesValidationDto)&&(this.query=(0,n.validateData)(this.jsonParsing(this.query,t.queriesValidationDto),t.queriesValidationDto)),this.body=e.body||{},t&&(t.httpMethod===n.HttpMethod.POST||t.httpMethod===n.HttpMethod.PUT)&&(null==t?void 0:t.bodyValidationDto)&&(this.body=(0,n.validateData)(this.body||{},t.bodyValidationDto,!1))}jsonParsing(e,t){const i=Object.assign({},e);for(const o of t.fields)try{(void 0!==e[o.name]||o.isRequired)&&(i[o.name]=JSON.parse(e[o.name]))}catch(e){throw n.ErrorBuilder.error(n.Errors.VALIDATION_ERROR,`JSON parsing failed for field ${o.name}`)}return i}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}}},8903:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ResponseBuilder=t.HttpResponse=void 0;class HttpResponse{constructor(){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},6004:function(e,t,i){var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(o,r){function fulfilled(e){try{step(n.next(e))}catch(e){r(e)}}function rejected(e){try{step(n.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((n=n.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractHttpController=void 0;const o=i(2318),r=i(7756);t.AbstractHttpController=class AbstractHttpController{constructor(e){this.databaseAdapter=e}createTransaction(){return n(this,void 0,void 0,(function*(){return this.databaseAdapter.createTransaction()}))}getCurrentTransaction(){return n(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}))):[]}}},225:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractHttpMiddleware=void 0;t.AbstractHttpMiddleware=class AbstractHttpMiddleware{}},767:function(e,t,i){var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(o,r){function fulfilled(e){try{step(n.next(e))}catch(e){r(e)}}function rejected(e){try{step(n.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((n=n.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractHttpRequestHandler=void 0;const o=i(2318),r=i(4972),s=i(6004);t.AbstractHttpRequestHandler=class AbstractHttpRequestHandler{constructor(e,t){this.mountPoint=e,this.logger=t}resolverMountPoint(e,t){if(!e)return"";const i=[];return i.push(...t),i.reduce(((e,t)=>`${e}/${t}`),"").replace(/(\/)\/+/g,"$1")}getMountedEndpointInfo(){var e,t,i;return n(this,void 0,void 0,(function*(){if(!this.mountedEndpointInfo){const n=[],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),i=e.getEndpointMetadata();for(const r of i){const i={mount:r.httpMethod===o.SocketMethod.MESSAGE?r.url:this.resolverMountPoint(t,[this.mountPoint||"/",r.url]),httpMethod:r.httpMethod,controller:e,handlerFunctionName:r.name};n.push({endpointMetadata:r,endpoint:i})}}const l=[];for(const o of n){const n=l.find((e=>e.endpoint.mount===o.endpoint.mount&&e.endpoint.httpMethod===o.endpoint.httpMethod));n?null===(e=this.logger)||void 0===e||e.warn(`Implicit overriding endpoint: ${(0,r.getEndpointId)(n.endpoint)} of ${null===(t=n.endpoint.controller)||void 0===t?void 0:t.constructor.name}:${n.endpoint.handlerFunctionName}`,`Ignore ${(0,r.getEndpointId)(o.endpoint)} of ${null===(i=o.endpoint.controller)||void 0===i?void 0:i.constructor.name}:${o.endpoint.handlerFunctionName}`):l.push(o)}this.mountedEndpointInfo=l}return this.mountedEndpointInfo}))}}},7282:function(e,t,i){var n=this&&this.__decorate||function(e,t,i,n){var o,r=arguments.length,s=r<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,n);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,i,s):o(t,i))||s);return r>3&&s&&Object.defineProperty(t,i,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(i,n){t(i,n,e)}},s=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(o,r){function fulfilled(e){try{step(n.next(e))}catch(e){r(e)}}function rejected(e){try{step(n.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((n=n.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.CrudHttpController=void 0;const a=i(2318),d=i(7756),l=i(1071),c=i(1532),u=i(2417),h=i(6004),p=i(859),f=i(8903),y=i(3198),g=i(4192);class CrudHttpController extends h.AbstractHttpController{constructor(e,t,i){super(i),this.model=e,this.crudRepository=t,this.databaseAdapter=i,this.modelMetadata=(0,a.getObjectMetadata)(e)}getMountedUrl(){return`/${this.model.name.toLowerCase()}`}static queryFieldDto(e){const t={id:"",fields:CrudHttpController.getRequestQueryFieldFromModel(e)},i={name:"fields",description:"Filter records by value of their fields."};return i.dataType=a.DataType.OBJECT,i.elementDto=t,i}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,i){const n={id:"",fields:[]};let o=e.fields.filter((e=>!e.hasMany&&!e.multiLocaleColumn));"create_response"===t&&(o=o.filter((e=>e.pk||e.serverValue||e.mimeProps))),"create_body"!==t&&"update_body"!==t||(o=o.filter((e=>{var t;return!e.serverValue&&!(null===(t=e.pk)||void 0===t?void 0:t.isAutoIncrement)||!!i&&!i.fields.find((t=>{var i;return(null===(i=t.hasMany)||void 0===i?void 0:i.column)===e.name}))})));const r=e.fields.filter((e=>e.multiLocaleColumn)),s=e.fields.filter((e=>!!e.hasMany));return n.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&&!i)&&(e.isRequired&&!e.isMultiLocale)}))),...s.map((i=>{var n,o,r,s;const d=CrudHttpController.getBodyDtoRecordClass(i.hasMany.relationDto,t,e);return{description:`All records of "${null===(n=i.hasMany)||void 0===n?void 0:n.relationDto.id}" table in this relationship.`,name:i.name,dataType:(null===(o=i.hasMany)||void 0===o?void 0:o.single)?a.DataType.OBJECT:a.DataType.ARRAY,isRequired:!(null===(r=i.hasMany)||void 0===r?void 0:r.single)&&"create_response"===t,vectorProps:(null===(s=i.hasMany)||void 0===s?void 0:s.single)?void 0:{elementDataType:a.DataType.OBJECT,minLength:0},elementDto:Object.assign(Object.assign({},d),{fields:("create_body"===t||"update_body"===t?d.fields.filter((e=>{var t;return e.name!==(null===(t=i.hasMany)||void 0===t?void 0:t.column)})):d.fields).map((e=>"update_body"===t?Object.assign(Object.assign({},e),{isRequired:!1,allowNull:!0}):e))})}})),...r.map((e=>({description:"Translation for "+e.multiLocaleColumn,name:e.name,isRequired:!1,dataType:a.DataType.OBJECT})))),n}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 i={id:"",fields:CrudHttpController.getRequestQueryFieldFromModel(e.hasMany.relationDto).filter((t=>{var i;return t.name!==(null===(i=e.hasMany)||void 0===i?void 0:i.column)})),relaxed:!0};t.dataType=a.DataType.OBJECT,t.elementDto=i}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);break;case a.DataType.BOOLEAN:t.dataType=a.DataType.BOOLEAN,t.allowNull=e.allowNull}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(p.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,g.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,g.DtoFieldValidation)(this.model,(e=>[e.getQuery().fields])),(0,l.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,l.FilterModelFieldAccessCondition)(this.model,(e=>{const t=e.getBody().update;return t?Object.keys((0,a.leanData)(t)):[]})),(0,g.DtoFieldValidation)(this.model,(e=>[e.getQuery().fields]),"dto_field_validation_query"),(0,g.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,g.DtoFieldValidation)(this.model,(e=>[e.getQuery().fields]))],e}static getCreateManyBodyValidator(e){const t={id:"",fields:[]},i={name:"records",description:"Array of records to be created."};return i.dataType=a.DataType.ARRAY,i.isRequired=!0,i.vectorProps={elementDataType:a.DataType.OBJECT,minLength:0},i.elementDto=CrudHttpController.getBodyDtoRecordClass(e,"create_body"),t.fields.push(i),t}static getCreateManyResponseValidator(e){const t={id:"",fields:[]},i={name:"records",description:"Array of records had just been created."};return i.dataType=a.DataType.ARRAY,i.isRequired=!0,i.vectorProps={elementDataType:a.DataType.OBJECT,minLength:0},i.elementDto=CrudHttpController.getBodyDtoRecordClass(e,"create_response"),t.fields.push(i),t}static getGetManyResponseValidator(e){const t={id:"",fields:[]},i={name:"total",description:"Number of records found, zero is returned if the request is not paged."};i.dataType=a.DataType.NUMBER,i.isRequired=!0,t.fields.push(i);const n={name:"records",description:"The found records. All records will be returned if the request is not paged."};return n.dataType=a.DataType.ARRAY,n.isRequired=!0,n.vectorProps={elementDataType:a.DataType.OBJECT,minLength:0},n.elementDto=CrudHttpController.getBodyDtoRecordClass(e,"get_response"),t.fields.push(n),t}static getGetManyQueryValidator(e){const t={id:"",fields:[CrudHttpController.queryFieldDto(e)]},i={name:"locale",description:"Language code for localization",isRequired:!1};i.dataType=a.DataType.STRING,t.fields.push(i);const 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 o={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."};o.dataType=a.DataType.ARRAY,o.vectorProps={elementDataType:a.DataType.OBJECT,minLength:1};const r={id:"",fields:[]};r.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}))),o.elementDto=r,t.fields.push(o);const s={name:"limit",description:"Limit the number of returning result."};s.dataType=a.DataType.NUMBER,s.rangeProps={min:1},t.fields.push(s);const d={name:"page",description:"Page the returning result, default to 1 if ommited. Has no effect if limit is not set."};return d.dataType=a.DataType.NUMBER,d.rangeProps={min:1},t.fields.push(d),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:[]},i={name:"update",isRequired:!0,description:"The update data to apply to found records."};return i.dataType=a.DataType.OBJECT,i.elementDto=CrudHttpController.getBodyDtoRecordClass(e,"update_body"),t.fields.push(i),t}static getUpdateManyResponseValidator(e){const t={id:"",fields:[]},i={name:"modified",description:"Array of affected records."};return i.dataType=a.DataType.ARRAY,i.vectorProps={minLength:0,elementDataType:a.DataType.OBJECT},i.elementDto=i.elementDto=CrudHttpController.getBodyDtoRecordClass(e,"get_response"),t.fields.push(i),t}getEndpointMetadata(){var e,t,i,n;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===(i=this.modelMetadata.ignoreCrud)||void 0===i?void 0:i.includes(a.HttpMethod.PUT))?o=o.filter((e=>e.name!==CrudHttpController.prototype.updateMany.name)):r.push(this.updateManyEndpoinMetadata()),(null===(n=this.modelMetadata.ignoreCrud)||void 0===n?void 0:n.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(),i=yield this.getAuthProvider(),n=i&&(yield i.resolvePrincipal(e)),o=yield this.crudRepository.createMany({principal:n,body:e.getBody(),tx:t});return f.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 f.ResponseBuilder.json(t).get()}))}updateMany(e){return s(this,void 0,void 0,(function*(){const t=yield this.getCurrentTransaction(),i=yield this.getAuthProvider(),n=i&&(yield i.resolvePrincipal(e)),o=yield this.crudRepository.updateMany({principal:n,queries:e.getQuery(),body:e.getBody(),tx:t});return f.ResponseBuilder.json(o).get()}))}deleteMany(e){return s(this,void 0,void 0,(function*(){const t=yield this.getCurrentTransaction(),i=yield this.crudRepository.deleteMany({queries:e.getQuery(),tx:t});return f.ResponseBuilder.json({modified:i.modified.map((e=>e.id)).map((e=>({id:e})))}).get()}))}}n([(0,d.Transactional)(d.PropagationMode.INHERIT_OR_CREATE),(0,u.ApiDescription)("Create records of this table."),(0,u.AccessCondition)([]),r(0,(0,u.Raw)()),o("design:type",Function),o("design:paramtypes",[c.HttpRequest]),o("design:returntype",Promise)],CrudHttpController.prototype,"createMany",null),n([(0,u.AccessCondition)([]),(0,u.ApiDescription)("Get records of this table."),r(0,(0,u.Raw)()),o("design:type",Function),o("design:paramtypes",[c.HttpRequest]),o("design:returntype",Promise)],CrudHttpController.prototype,"getMany",null),n([(0,d.Transactional)(d.PropagationMode.INHERIT_OR_CREATE),(0,u.ApiDescription)("Find and update records which match search condition."),(0,u.AccessCondition)([]),r(0,(0,u.Raw)()),o("design:type",Function),o("design:paramtypes",[c.HttpRequest]),o("design:returntype",Promise)],CrudHttpController.prototype,"updateMany",null),n([(0,d.Transactional)(d.PropagationMode.INHERIT_OR_CREATE),(0,u.ApiDescription)("Find and remove records which match search condition."),(0,u.AccessCondition)([]),r(0,(0,u.Raw)()),o("design:type",Function),o("design:paramtypes",[c.HttpRequest]),o("design:returntype",Promise)],CrudHttpController.prototype,"deleteMany",null),t.CrudHttpController=CrudHttpController},5879:function(e,t,i){var n=this&&this.__decorate||function(e,t,i,n){var o,r=arguments.length,s=r<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,n);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,i,s):o(t,i))||s);return r>3&&s&&Object.defineProperty(t,i,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,i,n){return new(i||(i=Promise))((function(o,r){function fulfilled(e){try{step(n.next(e))}catch(e){r(e)}}function rejected(e){try{step(n.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((n=n.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=i(2318),d=s(i(9215)),l=i(99),c=s(i(9103)),u=i(8903),h=i(1532),p=i(859),f=i(767),y=i(6721),g=i(225);let v=class DefaultHttpRequestHandler extends f.AbstractHttpRequestHandler{constructor(e,t){super("",e),this.logger=e,this.authorizationProvider=t,this._middleware=null}accessControl(e,t){return r(this,void 0,void 0,(function*(){if(e.endpointMetadata.httpMethod!==a.SocketMethod.MESSAGE){const i=yield this.authorizationProvider.resolvePrincipal(t);if(t.setAuthInfo(i),!e.endpointMetadata.openAccess&&(yield this.authorizationProvider.authorize(i,t,e),e.endpointMetadata.tfaRequired&&!(null==i?void 0:i.hasTfa)))throw a.ErrorBuilder.error(y.Errors.TFA_REQUIRED)}}))}handleRequest(e,t){return r(this,void 0,void 0,(function*(){yield this.accessControl(e,t);const i=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}})),n=yield e.endpoint.controller[e.endpointMetadata.name](...i);return e.endpointMetadata.responseValidationDto&&(n.value=(0,a.stripData)(n.value,e.endpointMetadata.responseValidationDto)),n}))}exit(){}getResponse(e){return r(this,void 0,void 0,(function*(){let t=new u.HttpResponse;const i=e.method,n=(0,d.default)({url:e.fullPath});let o={};const r=(yield this.getMountedEndpointInfo()).find((e=>{const t=e.endpointMetadata.httpMethod===i&&(0,l.match)(e.endpointMetadata.url,{decode:decodeURIComponent})(n.pathname||"/");return!!t&&(o=t,!0)}));if(!r)throw this.logger.debug(e),a.ErrorBuilder.error(y.Errors.NOT_FOUND,"Handler not found");const s=new h.HttpRequest({method:i,headers:e.headers,pathName:n.pathname||"",hash:n.hash||"",query:c.default.parse(decodeURIComponent(n.search||"")),params:o.params,body:e.body},r.endpointMetadata),p=yield this.getMiddleware();for(const e of p){if(!(yield e.intercept(s,t)))return t}const f=yield this.handleRequest(r,s);return f.code=f.code||t.code||200,f.value=f.value||t.value,f.headers=Object.assign(Object.assign({},t.headers),f.headers),f.cookies=Object.assign(Object.assign({},t.cookies),f.cookies),f}))}handle(e){return r(this,void 0,void 0,(function*(){try{const t=yield this.getResponse(e);if(!(t&&t instanceof u.HttpResponse))throw a.ErrorBuilder.systemError(`Invalid response value returned, required instance of ${u.HttpResponse.name}, found ${t?null==t?void 0:t.constructor.name:t}`);return t}catch(e){return this.logger.error(e),u.ResponseBuilder.json({name:e.name,message:e.message}).status([y.Errors.ACCESS_DENIED,y.Errors.AUTHENTICATION_ERROR,y.Errors.SESSION_EXPIRED].includes(e.name)?401:[y.Errors.SYSTEM_ERROR,y.Errors.CANNOT_LOCK].includes(e.name)?500:400).get()}}))}getMiddleware(){return r(this,void 0,void 0,(function*(){if(null===this._middleware){const e=(0,a.getServiceProvider)().getInjector();this._middleware=e.resolveMultiple(g.AbstractHttpMiddleware),yield e.initInstances()}return this._middleware}))}};v=n([(0,a.Injectable)(),o("design:paramtypes",[a.AbstractLogger,p.AbstractHttpAuthorizationProvider])],v),t.DefaultHttpRequestHandler=v},2417:(e,t,i)=>{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 n=i(2318);t.Controller=e=>t=>{(0,n.getServiceProvider)().register(t,"singleton");(0,n.initObjectMetadata)(t.prototype).permissionGroup=null==e?void 0:e.permissionGroup};t.ApiDescription=e=>(t,i)=>{(0,n.initFieldMetadata)(t,i).description=e};t.Endpoint=e=>(t,i)=>{const o=(0,n.initFieldMetadata)(t,i);o.httpMethod=e.method,o.url=e.url||"/"};t.Post=e=>(i,o,r)=>(0,t.Endpoint)({method:n.HttpMethod.POST,url:e})(i,o);t.Put=e=>(i,o,r)=>(0,t.Endpoint)({method:n.HttpMethod.PUT,url:e})(i,o);t.Del=e=>(i,o,r)=>(0,t.Endpoint)({method:n.HttpMethod.DEL,url:e})(i,o);t.Get=e=>(i,o,r)=>(0,t.Endpoint)({method:n.HttpMethod.GET,url:e})(i,o);t.ApiResponse=e=>(t,i,o)=>{const r=(0,n.initFieldMetadata)(t,i);e===String?r.responseValidationDto={id:"",primitiveType:n.DataType.STRING,fields:[]}:e===Number?r.responseValidationDto={id:"",primitiveType:n.DataType.NUMBER,fields:[]}:e===Boolean?r.responseValidationDto={id:"",primitiveType:n.DataType.BOOLEAN,fields:[]}:r.responseValidationDto=(0,n.getObjectMetadata)(e)};t.OpenAccess=()=>(e,t)=>{(0,n.initFieldMetadata)(e,t).openAccess=!0};t.TfaRequired=()=>(e,t)=>{(0,n.initFieldMetadata)(e,t).tfaRequired=!0};t.AccessCondition=e=>(t,i)=>{(0,n.initFieldMetadata)(t,i).accessConditions=e};const RequestDeco=e=>(t,i,o)=>{const r=(0,n.initFieldMetadata)(t,i),s=Reflect.getMetadata("design:paramtypes",t,i)||[];switch(e){case"body":r.bodyValidationDto=(0,n.getObjectMetadata)(s[o]);break;case"params":r.paramsValidationDto=(0,n.getObjectMetadata)(s[o]);break;case"queries":r.queriesValidationDto=(0,n.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,i)=>{(0,n.initFieldMetadata)(t,i).uriMapper=e};t.CurrentUser=e=>(t,i)=>{const o=(0,n.initFieldMetadata)(t,i);o.userResolver=e,o.serverValue=!0}},6507:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractFileUploadHandler=void 0;t.AbstractFileUploadHandler=class AbstractFileUploadHandler{}},4839:function(e,t,i){var n=this&&this.__decorate||function(e,t,i,n){var o,r=arguments.length,s=r<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,n);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,i,s):o(t,i))||s);return r>3&&s&&Object.defineProperty(t,i,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,i,n){return new(i||(i=Promise))((function(o,r){function fulfilled(e){try{step(n.next(e))}catch(e){r(e)}}function rejected(e){try{step(n.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((n=n.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.FileUploadHandler=void 0;const s=i(2318),a=i(8709),d=i(6507);let l=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)}))}};l=n([(0,s.Injectable)(),o("design:paramtypes",[a.AbstractFileService])],l),t.FileUploadHandler=l},5232:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},5048:function(e,t,i){var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(o,r){function fulfilled(e){try{step(n.next(e))}catch(e){r(e)}}function rejected(e){try{step(n.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((n=n.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractRepository=void 0;const o=i(2318);t.AbstractRepository=class AbstractRepository{constructor(e){this.model=e,this.modelMetadata=(0,o.getObjectMetadata)(this.model)}beforeCreating(e,t){return n(this,void 0,void 0,(function*(){for(const i of t)for(const t of this.modelMetadata.fields)t.userResolver&&e&&(i[t.name]=t.userResolver(e))}))}project(e,t){return t?e.map((e=>t.reduce(((t,i)=>Object.assign(t,{[i]:e[i]})),{}))):e}}},9073:function(e,t,i){var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(o,r){function fulfilled(e){try{step(n.next(e))}catch(e){r(e)}}function rejected(e){try{step(n.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((n=n.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.DtoRepository=t.MultipleMap=t.SingleMap=void 0;const o=i(2318),r=i(5048),s=i(3355);t.SingleMap=(e,t,i,n,o)=>({multiple:!1,modelClass:e,forwardOps:t,forwardMapping:e=>{const t=i(e[0]||{});return t&&[t]},rootMapping:e=>{const t=e&&e[0];return n(t)},nestedMapping:o});t.MultipleMap=(e,t,i,n,o)=>({multiple:!0,modelClass:e,forwardOps:t,forwardMapping:i,rootMapping:n,nestedMapping:o});class DtoRepository extends r.AbstractRepository{constructor(e,t){super(e),this.model=e,this.dissolver=t}getMapValue(e,t,i,r,s){return n(this,void 0,void 0,(function*(){for(const n of i){const i=yield t(n);let a=r?yield r(n,n.forwardMapping(i),i):n.forwardMapping(i);if(n.nestedMapping&&a)for(const i of a)yield this.getMapValue(e,t,n.nestedMapping(i),r,s);s&&(a=yield s(n,n.forwardMapping(i),i));const d=n.rootMapping(a);(0,o.deepMerge)(e,d)}}))}createMany({principal:e,body:t,tx:i}){return n(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=>n(this,void 0,void 0,(function*(){const t=new s.ModelRepository(e.modelClass);return(yield t.getMany({ops:e.forwardOps(),queryProvider:i})).records}))),this.dissolver(a),((t,r,a)=>n(this,void 0,void 0,(function*(){if(!r)return[];const n=new s.ModelRepository(t.modelClass),d=t.forwardOps();if(t.multiple){yield n.deleteMany({ops:d,tx:i});return(yield n.createMany({principal:e,body:{records:r},tx:i})).records}{const s=r[0];if(!s)return[];if(0===a.length){return(yield n.createMany({principal:e,body:{records:r},tx:i})).records}if(1===a.length){const t=yield n.updateMany({principal:e,ops:d,body:{update:s},tx:i});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:i,body:r,tx:a}){var d;return n(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 l=Object.assign(Object.assign({},r.update),{id:t.fields.id[0]});yield this.beforeCreating(e,[l]),yield this.getMapValue(l,(e=>n(this,void 0,void 0,(function*(){const t=new s.ModelRepository(e.modelClass);return(yield t.getMany({ops:e.forwardOps(i),queryProvider:a})).records}))),this.dissolver(l),((t,o,r)=>n(this,void 0,void 0,(function*(){if(!o)return[];const n=new s.ModelRepository(t.modelClass),d=t.forwardOps(i);if(t.multiple){yield n.deleteMany({ops:d,tx:a});return(yield n.createMany({principal:e,body:{records:o},tx:a})).records}{const t=o[0];return t?0==r.length?[]:(r.length>1?(yield n.deleteMany({ops:d,tx:a}),yield n.createMany({principal:e,body:{records:[t]},tx:a})):yield n.updateMany({principal:e,ops:d,body:{update:t},tx:a}),r.map((e=>Object.assign(Object.assign({},e),t)))):[]}}))));let c=["id"];return t.returning&&(c=[...c,...Object.keys(r.update).filter((e=>void 0!==r.update[e]))]),{modified:l.id?this.project([l],c):[]}}))}getMany({queries:e,ops:t,queryProvider:i}){var r;return n(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,(()=>n(this,void 0,void 0,(function*(){return[]}))),this.dissolver(a),(e=>n(this,void 0,void 0,(function*(){const n=new s.ModelRepository(e.modelClass);return(yield n.getMany({ops:e.forwardOps(t),queryProvider:i})).records})))),a.id?{records:this.project([a],e.projection),total:1}:{records:[],total:0}}))}deleteMany({queries:e,ops:t,tx:i}){var r;return n(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,(()=>n(this,void 0,void 0,(function*(){return[]}))),this.dissolver(a),void 0,(o=>n(this,void 0,void 0,(function*(){const n=new s.ModelRepository(o.modelClass),r=o.forwardOps(t);return(yield n.deleteMany({queries:{returning:null==e?void 0:e.returning},ops:r,tx:i})).modified})))),{modified:a.id?[a]:[]}}))}}t.DtoRepository=DtoRepository},8023:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},3355:function(e,t,i){var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(o,r){function fulfilled(e){try{step(n.next(e))}catch(e){r(e)}}function rejected(e){try{step(n.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((n=n.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.ModelRepository=void 0;const o=i(2318),r=i(7756),s=i(6507),a=i(5048),d=i(9627),l=i(2552),c=i(5481);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 i=t.hasMany.relationDto,n=this.getRequestQueryConditionFromQuery(null==e?void 0:e.fields[t.name],Object.assign(Object.assign({},i),{fields:i.fields.filter((e=>{var i;return e.name!==(null===(i=t.hasMany)||void 0===i?void 0:i.column)}))}));return{modelId:t.hasMany.relationDto.id,targetField:t.hasMany.column,queries:n.length?{_and:n}:{}}}))}getUploadHandler(){return n(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 i;const n=[];for(const s of(0,r.getDirectFields)(t)){const t=e[s.name];if(void 0!==t)if(s.pk||s.fk||s.isSymbol)n.push({_in:{[s.name]:t}});else if(s.enum)n.push({_in:{[s.name]:t}});else switch(s.dataType){case o.DataType.STRING:if(s.searchable){const e={[(null==s?void 0:s.searchable.caseSensitive)?(null==s?void 0:s.searchable.accentSensitive)?"_sub":"_usub":(null===(i=null==s?void 0:s.searchable)||void 0===i?void 0:i.accentSensitive)?"_isub":"_iusub"]:{[s.name]:t}};n.push(e)}else n.push({_eq:{[s.name]:t}});break;case o.DataType.NUMBER:const e=new o.RangeQueryDto;Object.assign(e,t),e.min&&(e.minExclusive?n.push({_gt:{[s.name]:e.min}}):n.push({_gte:{[s.name]:e.min}})),e.max&&(e.maxExclusive?n.push({_lt:{[s.name]:e.max}}):n.push({_lte:{[s.name]:e.max}}));break;case o.DataType.BOOLEAN:n.push({_eq:{[s.name]:t}})}}return n}uriHandling(e,t){return n(this,void 0,void 0,(function*(){const i=yield this.getUploadHandler();if(!i)return;const n=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 i.moveFile(e,s),r[o.name]=s,yield n.updateOne(r))}}))}beforeReturning(e){var t;return n(this,void 0,void 0,(function*(){const i=yield this.getUploadHandler();for(const n of e)for(const e of this.modelMetadata.fields)if(e.uriMapper&&i){if(!n[e.name])continue;n[e.name]=(null===(t=e.mimeProps)||void 0===t?void 0:t.public)?yield i.resolvePublicUrl(n[e.name]):yield i.resolvePrivateUrl(n[e.name])}}))}createMany({principal:e,body:t,tx:i}){var s;return n(this,void 0,void 0,(function*(){const n=t.records;if(!n.length)return{records:[]};const a=(0,r.getDirectFields)(this.modelMetadata),u=a.filter((e=>!!e.multiLocaleColumn)),h=(0,d.getSystemLocale)();if(h)for(const e of n)for(const t of u)e[t.name]&&(e[t.multiLocaleColumn]=e[t.name][h]);const p=this.modelMetadata.fields.filter((e=>!!e.hasMany)),f=n.map(((e,t)=>u.filter((t=>!!e[t.name])).map((e=>({recordIndex:t,field:e.name,entryObject:{}}))))).flatMap((e=>e)),y=yield i.use(c.LocaleEntry).createMany(f.map((e=>e.entryObject))),g=n.map((e=>u.filter((t=>!!e[t.name])).map((t=>e[t.name])))).flatMap((e=>e)).map(((e,t)=>Object.keys(e).map((i=>({localeCode:i,entryId:y[t].id,translation:e[i]}))))).flatMap((e=>e));yield i.use(l.LocaleTranslation).createMany(g),t.records=n.map(((e,t)=>a.reduce(((i,n)=>{let o=e[n.name];if(n.multiLocaleColumn){const e=f.findIndex((e=>e.recordIndex===t&&e.field===n.name));e>=0&&(o=y[e].id)}return Object.assign(i,void 0!==o?{[n.name]:o}:{})}),{}))),yield this.beforeCreating(e,t.records);let v=t.records.length?yield i.use(this.model).createMany(t.records):[];yield this.uriHandling(v,i),yield this.beforeReturning(v);const m=this.modelMetadata.fields.filter((e=>!e.multiLocaleColumn&&(e.pk||e.serverValue||e.mimeProps))).map((e=>e.name));v=this.project(v,m);for(const r of p){const a=v.flatMap(((e,t)=>{var i;const o=n[t][r.name];return o?((null===(i=r.hasMany)||void 0===i?void 0:i.single)?[o]:o).map((t=>Object.assign(Object.assign({},t),{[r.hasMany.column]:e.id}))):[]}));if(a.length){const n=new ModelRepository((0,o.getModelById)(r.hasMany.relationDto.id));t.records=a;const d=yield n.createMany({principal:e,body:t,tx:i});for(let e=0;e<d.records.length;e++)a[e]=Object.assign(Object.assign({},a[e]),d.records[e]);for(let e=0;e<v.length;e++){const t=[];for(let i=0;i<a.length;i++)a[i][r.hasMany.column]===v[e].id&&t.push(d.records[e]);v[e]=Object.assign(Object.assign({},v[e]),{[r.name]:(null===(s=r.hasMany)||void 0===s?void 0:s.single)?t[0]:t})}}}return{records:v}}))}updateMany({principal:e,ops:t,queries:i,body:s,tx:a}){var u,h;return n(this,void 0,void 0,(function*(){const n=t||[],p=this.modelMetadata.fields.filter((e=>!!e.hasMany)),f=(0,r.getDirectFields)(this.modelMetadata).filter((e=>!e.multiLocaleColumn&&void 0!==s.update[e.name])),y=f.reduce(((e,t)=>Object.assign(e,{[t.name]:s.update[t.name]})),{}),g=Object.keys(s.update),v=this.modelMetadata.fields.filter((e=>g.includes(e.name)&&e.multiLocaleColumn)),m=(0,d.getSystemLocale)();if(m)for(const e of v)if(s.update[e.name]){const t=s.update[e.name][m];t&&(y[e.multiLocaleColumn]=t)}if(null==i?void 0:i.fields){const e=this.getRequestQueryConditionFromQuery(i.fields,this.modelMetadata);e.length&&n.push(...e)}const b=n.length?{_and:[...n]}:{},M=this.getNestedQueries(i);let C=[];if(M.length){const e=yield a.use(this.model).getMany(b,{projection:["id"]},M);C=e.records.map((e=>e.id)),C.length&&f.length&&(yield a.use(this.model).updateMany({_in:{id:C}},y,!1))}else if(f.length)C=yield a.use(this.model).updateMany(b,y,!0);else{const e=yield a.use(this.model).getMany(b,{projection:["id"]});C=e.records.map((e=>e.id))}if(v.length){const e=yield a.use(this.model).getRecords({_in:{id:C}},{projection:["id",...v.map((e=>e.name))]}),t=e.map((e=>v.filter((t=>!e[t.name])).map((t=>({recordId:e.id,field:t.name}))))).flatMap((e=>e)),i=t.length?yield a.use(c.LocaleEntry).createMany(t.map((()=>({})))):[],n=[];i.forEach(((i,o)=>{const r=t[o],s=e.find((e=>e.id===r.recordId));if(s){s[r.field]=i.id;let e=n.find((e=>e.id===s.id));e||(e={id:s.id},n.push(e)),e[r.field]=i.id}})),yield Promise.all(n.map((e=>a.use(this.model).updateOne(e))));const o=[];for(const t of v){const i=s.update[t.name],n=Object.keys(i||{});n.length&&o.push(...e.map((e=>n.map((n=>({entryId:e[t.name],langCode:n,translation:i[n]}))))).flatMap((e=>e)))}o.length&&(yield a.use(l.LocaleTranslation).deleteMany({_or:o.map((e=>({_eq:{entryId:e.entryId,localeCode:e.langCode}})))}),yield a.use(l.LocaleTranslation).createMany(o.map((e=>({entryId:e.entryId,localeCode:e.langCode,translation:e.translation})))))}const R=C.map((e=>Object.assign(Object.assign({},y),{id:e})));yield this.uriHandling(R,a),yield this.beforeReturning(R);for(const t of p){const i=s.update[t.name];if(void 0===i||!C.length)continue;if(C.length>1)throw o.ErrorBuilder.systemError(`Multiple records found while updating @HasMany field: ${t.name}`);const n=R.find((e=>e.id===C[0])),r=(0,o.getModelById)(t.hasMany.relationDto.id),d=a.use(r),l=(yield d.getRecords({_eq:{[t.hasMany.column]:n.id}},{limit:(null===(u=t.hasMany)||void 0===u?void 0:u.single)?1:void 0})).map((e=>e.id)),c=i.map((e=>e.id)).filter((e=>!!e)),p=l.filter((e=>!c.includes(e))),f=i.filter((e=>!e.id)).map((e=>Object.assign(Object.assign({},e),{[t.hasMany.column]:n.id}))),y=i.filter((e=>!!e.id));p.length&&(yield d.deleteMany({_in:{id:p}}));const g=new ModelRepository(r),v=yield g.createMany({principal:e,body:{records:f},tx:a});yield Promise.all(y.filter((e=>Object.keys(e).length>1)).map((t=>g.updateMany({principal:e,ops:[{_eq:{id:t.id}}],tx:a,body:{update:(0,o.leanData)(Object.assign(Object.assign({},t),{id:void 0}))}}))));const m=f.map(((e,t)=>Object.assign(Object.assign({},e),v.records[t]))).concat(y);n[t.name]=(null===(h=t.hasMany)||void 0===h?void 0:h.single)?m[0]:m}let S=["id"];return(null==i?void 0:i.returning)&&(S=[...S,...Object.keys(s.update).filter((e=>void 0!==s.update[e]))]),{modified:this.project(R,S)}}))}getMany({queries:e,ops:t,queryProvider:i}){var r;return n(this,void 0,void 0,(function*(){const n=t||[];if((null==e?void 0:e.fields)&&n.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&&n.push({_or:t})}const s=this.modelMetadata.fields.filter((t=>t.isMultiLocale&&(!(null==e?void 0:e.projection)||e.projection.includes(t.name)))),a=this.modelMetadata.fields.filter((e=>s.find((t=>t.name===e.multiLocaleColumn)))),c=(null==e?void 0:e.projection)&&[...e.projection.filter((e=>!this.modelMetadata.fields.find((t=>t.name===e&&!!t.hasMany)))),...a.map((e=>e.name))],u=yield i.use(this.model).getMany(n.length?{_and:n}:{},{limit:null==e?void 0:e.limit,page:null==e?void 0:e.page,projection:c,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)),h=u.records.map((e=>e.id)),p=u.records.map((e=>a.map((t=>e[t.name])))).flatMap((e=>e)),f=(0,d.getSystemLocale)(),y=(null==e?void 0:e.locale)?e.locale.toLowerCase()!==f?yield i.use(l.LocaleTranslation).getRecords({_in:{entryId:p},_eq:{localeCode:e.locale}},{projection:["entryId","localeCode","translation"]}):[]:yield i.use(l.LocaleTranslation).getRecords({_in:{entryId:p}},{projection:["entryId","localeCode","translation"]});if(y.length)if(null==e?void 0:e.locale)for(const t of u.records)for(const i of a){const n=y.find((n=>n.localeCode===e.locale&&n.entryId===t[i.name]));t[i.multiLocaleColumn]=null==n?void 0:n.translation}else for(const e of u.records)for(const t of a){const i=y.filter((i=>i.entryId===e[t.name]));e[t.name]=i.reduce(((e,t)=>Object.assign(e,{[t.localeCode]:t.translation})),{})}for(const t of this.modelMetadata.fields){if(!t.hasMany||(null==e?void 0:e.projection)&&!e.projection.includes(t.name))continue;const n=(0,o.getModelById)(t.hasMany.relationDto.id),r=new ModelRepository(n),s=h.length?yield r.getMany({queries:{fields:{[t.hasMany.column]:h},limit:t.hasMany.single?1:0},queryProvider:i}):{records:[]};for(const e of u.records){const i=s.records.filter((i=>i[t.hasMany.column]===e.id));e[t.name]=t.hasMany.single?i[0]:i}}return yield this.beforeReturning(u.records),{total:u.total,records:this.project(u.records,(null==e?void 0:e.projection)&&[...e.projection,...c||[]].reduce(o.uniqueReducer,[]))}}))}deleteMany({queries:e,ops:t,tx:i}){return n(this,void 0,void 0,(function*(){let n=t||[];if(null==e?void 0:e.fields){const t=this.getRequestQueryConditionFromQuery(e.fields,this.modelMetadata);t.length&&n.push(...t)}const o=n.length?{_and:[...n,...t||[]]}:{},r=this.getNestedQueries(e);let s=[];const a=this.modelMetadata.fields.filter((e=>e.multiLocaleColumn));if(r.length||a.length){const e=yield i.use(this.model).getRecords(o,{projection:["id",...a.map((e=>e.name))]},r);yield i.use(this.model).deleteMany({_in:{id:e.map((e=>e.id))}});const t=e.map((e=>a.map((t=>e[t.name])))).flatMap((e=>e)).filter((e=>!!e));yield i.use(c.LocaleEntry).deleteMany({_in:{id:t}}),s=e}else s=yield i.use(this.model).deleteMany(o,null==e?void 0:e.returning);return{modified:s}}))}}t.ModelRepository=ModelRepository},2255:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractAccessCondition=void 0;t.AbstractAccessCondition=class AbstractAccessCondition{}},4192:function(e,t,i){var n=this&&this.__decorate||function(e,t,i,n){var o,r=arguments.length,s=r<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,n);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,i,s):o(t,i))||s);return r>3&&s&&Object.defineProperty(t,i,s),s},o=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(o,r){function fulfilled(e){try{step(n.next(e))}catch(e){r(e)}}function rejected(e){try{step(n.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((n=n.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.DtoFieldValidation=void 0;const r=i(2318),s=i(2255);t.DtoFieldValidation=(e,t,i)=>{let a=class _ extends s.AbstractAccessCondition{resolveConditionValue(e){return o(this,void 0,void 0,(function*(){return t(e)}))}getConditionMetadata(){return{name:i||"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 i of e)(0,r.validateData)(i,t);return!0}catch(e){return!1}}))}};return a=n([(0,r.Register)()],a),a}},1071:function(e,t,i){var n=this&&this.__decorate||function(e,t,i,n){var o,r=arguments.length,s=r<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,n);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,i,s):o(t,i))||s);return r>3&&s&&Object.defineProperty(t,i,s),s},o=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(o,r){function fulfilled(e){try{step(n.next(e))}catch(e){r(e)}}function rejected(e){try{step(n.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((n=n.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.FilterModelFieldAccessCondition=void 0;const r=i(2318),s=i(2255);t.FilterModelFieldAccessCondition=(e,t)=>{let i=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 i=n([(0,r.Register)()],i),i}},3198:function(e,t,i){var n=this&&this.__decorate||function(e,t,i,n){var o,r=arguments.length,s=r<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,n);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,i,s):o(t,i))||s);return r>3&&s&&Object.defineProperty(t,i,s),s},o=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(o,r){function fulfilled(e){try{step(n.next(e))}catch(e){r(e)}}function rejected(e){try{step(n.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((n=n.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.MaximumQueryLimit=void 0;const r=i(2318),s=i(2255);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=n([(0,r.Register)()],a),t.MaximumQueryLimit=a},341:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var o=Object.getOwnPropertyDescriptor(t,i);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,o)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),o=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||n(t,e,i)};Object.defineProperty(t,"__esModule",{value:!0}),o(i(9025),t),o(i(4638),t),o(i(1820),t),o(i(1870),t),o(i(4972),t),o(i(8903),t),o(i(2417),t),o(i(1532),t),o(i(5879),t),o(i(6004),t),o(i(7282),t),o(i(4435),t),o(i(767),t),o(i(225),t),o(i(2255),t),o(i(1071),t),o(i(3198),t),o(i(4192),t),o(i(859),t),o(i(2085),t),o(i(531),t),o(i(7825),t),o(i(9837),t),o(i(3355),t),o(i(9073),t),o(i(8023),t),o(i(5048),t),o(i(5530),t),o(i(2841),t),o(i(7152),t),o(i(8577),t),o(i(2665),t),o(i(9990),t),o(i(6507),t),o(i(4839),t),o(i(5232),t),o(i(5572),t),o(i(10),t),o(i(5481),t),o(i(2552),t),o(i(889),t),o(i(5537),t),o(i(226),t),o(i(8836),t),o(i(9627),t),o(i(6721),t),o(i(204),t),o(i(7577),t),o(i(8709),t),o(i(1556),t),o(i(2363),t),o(i(4683),t),o(i(9527),t),o(i(3376),t),o(i(5033),t),o(i(523),t)},4683:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractJobController=void 0;const n=i(2318);t.AbstractJobController=class AbstractJobController{getAllJobs(){const e=(0,n.getObjectMetadata)(this.constructor);return(null==e?void 0:e.jobs)||[]}}},523:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractJobRepository=void 0;t.AbstractJobRepository=class AbstractJobRepository{}},9527:function(e,t,i){var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(o,r){function fulfilled(e){try{step(n.next(e))}catch(e){r(e)}}function rejected(e){try{step(n.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((n=n.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractJobScheduler=void 0;const o=i(2318),r=i(4683);t.AbstractJobScheduler=class AbstractJobScheduler{constructor(e){this.logger=e,this._jobs=null}getAvailableJobInfo(){return n(this,void 0,void 0,(function*(){if(null===this._jobs){const e=(0,o.getServiceProvider)().getInjector(),t=e.resolveMultiple(r.AbstractJobController);yield e.initInstances(),this._jobs=t.flatMap((e=>e.getAllJobs().map((t=>Object.assign(Object.assign({},t),{handlerFn:e[t.handlerName].bind(e)})))))}return this._jobs}))}scheduleJobAt(e){return this.scheduleJob(e)}executeJob(e){return n(this,void 0,void 0,(function*(){const t=(yield this.getAvailableJobInfo()).find((t=>t.jobName===e.jobName));t&&(yield t.handlerFn(e.params)),t&&!e.at||(yield this.removeJob(e.jobId),this.logger.info(t?`Remove one-time job ${e.jobName} at timestamp ${e.at}`:`Remove not found job: ${e.jobName}`))}))}}},3376:function(e,t,i){var n=this&&this.__decorate||function(e,t,i,n){var o,r=arguments.length,s=r<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,n);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,i,s):o(t,i))||s);return r>3&&s&&Object.defineProperty(t,i,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,i,n){return new(i||(i=Promise))((function(o,r){function fulfilled(e){try{step(n.next(e))}catch(e){r(e)}}function rejected(e){try{step(n.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((n=n.apply(e,t||[])).next())}))},s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.AwsJobScheduler=void 0;const a=i(2318),d=s(i(9336)),l=s(i(1495)),c=i(9527),u=i(2363),gcdBetween=(e,t)=>{const i=e>t?e:t,n=e>t?t:e;if(i<=0||n<=0)return 1;if(i%n==0)return n;{const e=Math.trunc(i/n);return gcdBetween(n,i-n*e)}},gcdOf=(e,t)=>t.length?gcdOf(gcdBetween(e,t[0]),t.slice(1)):e,getWaitExpression=e=>`Wait ${e} seconds`;let h=class AwsJobScheduler extends c.AbstractJobScheduler{constructor(e,t,i,n,o,r,s="default",a="claire-aws-job-",c="one-minute-step-function-trigger"){super(e),this.logger=e,this.redisServerUrl=t,this.uniqueIdKey=i,this.apiLambdaFunctionArn=n,this.stepFunctionName=o,this.iamRoleArn=r,this.eventBusName=s,this.jobNamePrefix=a,this.oneMinuteRule=c,this.eventbridge=new d.default.EventBridge,this.stepfunctions=new d.default.StepFunctions({apiVersion:"2016-11-23"}),this.redisClient=new l.default(this.redisServerUrl)}init(){return r(this,void 0,void 0,(function*(){}))}exit(){this.redisClient.quit()}handleInterval(e){return r(this,void 0,void 0,(function*(){this.logger.debug("Handle interval",e,typeof e);const t=(yield this.getAvailableJobInfo()).filter((t=>t.interval&&e%t.interval==0));yield Promise.all(t.map((e=>this.executeJob(Object.assign(Object.assign({},e),{jobId:e.jobName})))))}))}handleCron(e){return r(this,void 0,void 0,(function*(){this.logger.debug("Handle cron",e),yield this.executeJob(e)}))}generateCronFromTimestamp(e){const t=new Date(e);return[t.getUTCMinutes(),t.getUTCHours(),t.getUTCDate(),t.getUTCMonth(),"?",t.getUTCFullYear()].join(" ")}isActiveScheduler(){return!1}getAllScheduledJobs(){return r(this,void 0,void 0,(function*(){const e=yield this.getAvailableJobInfo(),t=yield this.eventbridge.listRules({EventBusName:this.eventBusName,NamePrefix:this.jobNamePrefix}).promise();return(yield Promise.all((t.Rules||[]).map((e=>r(this,void 0,void 0,(function*(){var t;const i=e.Name,n=null===(t=(yield this.eventbridge.listTargetsByRule({EventBusName:this.eventBusName,Rule:i}).promise()).Targets)||void 0===t?void 0:t.find((e=>e.Id===i));if(!n||!n.Input)return;return JSON.parse(n.Input).requestContext.cronScheduler.data})))))).filter((e=>!!e)).concat(e.filter((e=>e.interval)).map((e=>Object.assign(Object.assign({},e),{jobId:e.jobName}))))}))}scheduleJob(e){return r(this,void 0,void 0,(function*(){if(this.logger.debug("Scheduling job: ",e),e.cron||e.at){const t=yield this.redisClient.incr(this.uniqueIdKey),i=`${this.jobNamePrefix}${t}`,n=`${e.cron} *`||this.generateCronFromTimestamp(e.at);return this.logger.debug("Cron expression",n),yield this.eventbridge.putRule({Name:i,Description:`${e.jobName} - ${e.cron||e.at}`,EventBusName:this.eventBusName,ScheduleExpression:`cron(${n})`,State:"ENABLED"}).promise(),yield this.eventbridge.putTargets({Rule:i,Targets:[{Arn:this.apiLambdaFunctionArn,Id:i,Input:JSON.stringify({requestContext:{cronScheduler:{data:Object.assign(Object.assign({},e),{jobId:i})}}})}]}).promise(),i}if(e.interval)return e.jobName;throw a.ErrorBuilder.systemError(`Job does not have time config: ${e.jobName}`)}))}syncJobs(){return r(this,void 0,void 0,(function*(){this.logger.debug("Checking interval scheduler"),yield this.checkIntervalScheduler();const e=yield this.getAllScheduledJobs(),t=yield this.getAvailableJobInfo(),i=e.filter((e=>!t.find((t=>t.jobName===e.jobName))));for(const e of i)this.logger.info(`Removing stale job: ${e.jobName} of id: ${e.jobId}`),yield this.removeJob(e.jobId);i.length&&this.logger.info(`Cleaned up: ${i.length} stale jobs`),this.logger.debug("Remove scheduled cron jobs");const n=e.filter((e=>e.cron));yield Promise.all(n.map((e=>this.removeJob(e.jobId))));const o=t.filter((e=>e.cron||e.interval));this.logger.debug("Scheduling cron & interval jobs");for(const e of o)yield this.scheduleJob({jobName:e.jobName,cron:e.cron,interval:e.interval})}))}removeJob(e){return r(this,void 0,void 0,(function*(){yield this.eventbridge.removeTargets({EventBusName:this.eventBusName,Rule:e,Ids:[e]}).promise(),yield this.eventbridge.deleteRule({EventBusName:this.eventBusName,Name:e}).promise()}))}checkIntervalScheduler(){var e,t;return r(this,void 0,void 0,(function*(){const i=(yield this.getAvailableJobInfo()).filter((e=>e.interval)),n=i.map((e=>e.interval)),[o,r]=((e,t)=>{let i=u.JobInterval.EVERY_30S;t.length&&(i=gcdOf(t[0],t.slice(1)),i<u.JobInterval.EVERY_5S&&(i=u.JobInterval.EVERY_5S));const n=Math.trunc(60/i),o=[];for(let e=0;e<n;e++)o.push(e*i);return[i,`\n {\n "StartAt": "Create items",\n "States": {\n "Create items": {\n "Type": "Pass",\n "Next": "Loop",\n "Result": ${JSON.stringify(o)}\n },\n "Loop": {\n "Type": "Map",\n "End": true,\n "Iterator": {\n "StartAt": "${getWaitExpression(i)}",\n "States": {\n "${getWaitExpression(i)}": {\n "Type": "Wait",\n "Seconds": ${i},\n "Next": "Convert time to request object"\n },\n "Convert time to request object": {\n "Type": "Pass",\n "Next": "Lambda Invoke",\n "Result": {\n "requestContext": {\n "intervalScheduler": {\n "time": "$"\n }\n }\n }\n },\n "Lambda Invoke": {\n "Type": "Task",\n "Resource": "arn:aws:states:::lambda:invoke",\n "Parameters": {\n "Payload.$": "$",\n "FunctionName": "${e}:$LATEST"\n },\n "End": true,\n "OutputPath": "$.Payload"\n }\n }\n },\n "MaxConcurrency": 1\n }\n },\n "Comment": "One minute loop to trigger lambda function"\n }\n `]})(this.apiLambdaFunctionArn,n);this.logger.debug("Listing all state machines");const s=yield this.stepfunctions.listStateMachines({}).promise();let a=null===(e=s.stateMachines.find((e=>e.name.includes(this.stepFunctionName))))||void 0===e?void 0:e.stateMachineArn,d=a;if(a){(yield this.stepfunctions.describeStateMachine({stateMachineArn:a}).promise()).definition.includes(getWaitExpression(o))||(this.logger.debug("Step function definition changed, create new state machine"),d="")}const l=`${this.stepFunctionName}-${o}`;if(!d){this.logger.debug(`Create new step function with interval ${o} seconds`);d=(yield this.stepfunctions.createStateMachine({definition:r,name:l,roleArn:this.iamRoleArn,type:"EXPRESS"}).promise()).stateMachineArn}this.logger.debug("Step function ARNs old / new",a,d),this.logger.debug("Getting one minute rule");const c=yield this.eventbridge.listRules({EventBusName:this.eventBusName,NamePrefix:this.oneMinuteRule}).promise(),h=null===(t=c.Rules)||void 0===t?void 0:t.find((e=>e.Name==this.oneMinuteRule));h||(this.logger.debug("Create new one minute rule"),yield this.eventbridge.putRule({EventBusName:this.eventBusName,Name:this.oneMinuteRule,Description:"One minute trigger function for step function",ScheduleExpression:"rate(1 minute)",State:"ENABLED"}).promise()),this.logger.debug("Adding step function state machine as target"),d!==a&&(a&&(this.logger.debug("Removing old target",a),yield this.eventbridge.removeTargets({EventBusName:this.eventBusName,Rule:this.oneMinuteRule,Ids:[this.stepFunctionName]}).promise(),this.logger.debug("Removing old state machine function"),yield this.stepfunctions.deleteStateMachine({stateMachineArn:a}).promise()),this.logger.debug("Adding new target",d),yield this.eventbridge.putTargets({Rule:this.oneMinuteRule,Targets:[{Arn:d,Id:this.stepFunctionName,RoleArn:this.iamRoleArn}]}).promise()),!i.length&&(null==h?void 0:h.State)?(this.logger.info("No interval job found, disable one minute rule"),yield this.eventbridge.disableRule({EventBusName:this.eventBusName,Name:this.oneMinuteRule}).promise()):(this.logger.info("Interval job found, enable one minute rule"),yield this.eventbridge.enableRule({EventBusName:this.eventBusName,Name:this.oneMinuteRule}).promise())}))}};h=n([(0,a.Initable)(),o("design:paramtypes",[a.AbstractLogger,String,String,String,String,String,Object,Object,Object])],h),t.AwsJobScheduler=h},5033:function(e,t,i){var n=this&&this.__decorate||function(e,t,i,n){var o,r=arguments.length,s=r<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,n);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,i,s):o(t,i))||s);return r>3&&s&&Object.defineProperty(t,i,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,i,n){return new(i||(i=Promise))((function(o,r){function fulfilled(e){try{step(n.next(e))}catch(e){r(e)}}function rejected(e){try{step(n.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((n=n.apply(e,t||[])).next())}))},s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.LocalJobScheduler=void 0;const a=i(2318),d=s(i(1495)),l=s(i(9896)),c=s(i(7344)),u=i(9527),h=i(523),p=i(9512);var f;!function(e){e.SCHEDULE_JOB="SCHEDULE_JOB",e.REMOVE_JOB="REMOVE_JOB",e.SYNC_JOB="SYNC_JOB",e.NOTIFY="NOTIFY"}(f||(f={}));let y=class LocalJobScheduler extends u.AbstractJobScheduler{constructor(e,t,i,n,o,r,s,a=30){super(e),this.logger=e,this.jobRepo=t,this.redisServerUrl=i,this.lockMutexKey=n,this.holdMutexKey=o,this.uniqueIdKey=r,this.multiClientChannel=s,this.keyRetentionDurationSecond=a,this.intervals=[],this.isActive=!1,this.notifyResolver={},this.jobHolder={},this.redisClient=new d.default(this.redisServerUrl),this.subscribeClient=this.redisClient.duplicate()}sendJob(e,t,i){this.subscribeClient.publish(this.multiClientChannel,JSON.stringify({type:e,messageId:t,data:i}))}processMessage(e,t,i){return r(this,void 0,void 0,(function*(){switch(e){case f.SYNC_JOB:yield this.syncJobs(),this.sendJob(f.NOTIFY,t);break;case f.NOTIFY:const n=this.notifyResolver[t];if(!n)return;n(i);break;case f.SCHEDULE_JOB:if(!this.isActive)return;const o=i,r=yield this.scheduleJobAt(o);this.sendJob(f.NOTIFY,t,r);break;case f.REMOVE_JOB:if(!this.isActive)return;const s=i;yield this.removeJob(s),this.sendJob(f.NOTIFY,t);break;default:this.logger.error(`Not recognize message type ${e}`)}}))}extendMutexKey(){return r(this,void 0,void 0,(function*(){this.redisClient&&(yield this.redisClient.setex(this.holdMutexKey,this.keyRetentionDurationSecond,1),this.logger.debug("Scheduler extends mutex key"))}))}init(){return r(this,void 0,void 0,(function*(){this.logger.debug("LocalJobScheduler init"),this.logger.debug("Listening on multi client channel"),this.redisClient.on("message",((e,t)=>{if(e===this.multiClientChannel){const e=JSON.parse(t);this.processMessage(e.type,e.messageId,e.data).catch((t=>this.logger.error(`Fail to process message, ${e}`,t)))}})),yield this.subscribeClient.subscribe(this.multiClientChannel),this.logger.debug("Try to claim active scheduler");const e=new l.default([this.redisClient]);try{const t=yield e.acquire([this.lockMutexKey],this.keyRetentionDurationSecond);this.isActive=!0,yield this.extendMutexKey(),yield t.release(),this.logger.debug("Being active scheduler"),this.mutexHoldInterval=setInterval((()=>{this.extendMutexKey()}),Math.trunc(1e3*this.keyRetentionDurationSecond/2)+1)}catch(e){this.logger.info("Failed to lock mutex key, ignore",e)}}))}exit(){this.mutexHoldInterval&&(0,p.clearInterval)(this.mutexHoldInterval),this.redisClient.quit(),this.subscribeClient.quit();for(const e of this.intervals)(0,p.clearInterval)(e);this.logger.debug("LocalJobScheduler exit")}isActiveScheduler(){return this.isActive}getAllScheduledJobs(){return r(this,void 0,void 0,(function*(){return Object.values(this.jobHolder).filter((e=>!!(null==e?void 0:e.jobInfo))).map((e=>null==e?void 0:e.jobInfo))}))}syncJobs(){return r(this,void 0,void 0,(function*(){if(!this.isActive){const e=yield this.redisClient.incr(this.uniqueIdKey);return new Promise((t=>{this.notifyResolver[e]=t,this.sendJob(f.SYNC_JOB,e)}))}{const e=yield this.getAvailableJobInfo();for(const t of e)(t.cron||t.interval)&&(yield this.scheduleJob(t));const t=yield this.jobRepo.getJobs();for(const e of t)yield this.scheduleJob(e)}}))}scheduleJob(e){return r(this,void 0,void 0,(function*(){if(this.isActive){if(e.at){const t=yield this.jobRepo.saveJob({jobName:e.jobName,params:e.params,at:e.at}),i=Object.assign(Object.assign({},e),{jobId:t}),n=c.default.scheduleJob(new Date(e.at),(()=>{this.executeJob(i).catch((e=>this.logger.error(`Error execute job ${i.jobName} with id: ${i.jobId}`,e)))}));return this.jobHolder[t]={jobCanceler:()=>n.cancel(),jobInfo:Object.assign(Object.assign({},e),{jobId:t})},t}if(e.interval){const t=e.jobName,i=Object.assign(Object.assign({},e),{jobId:t}),n=setInterval((()=>{this.executeJob(i).catch((e=>this.logger.error(`Error execute job ${i.jobName} with id: ${i.jobId}`,e)))}),e.interval);return this.jobHolder[t]={jobCanceler:()=>(0,p.clearInterval)(n),jobInfo:Object.assign(Object.assign({},e),{jobId:t})},t}if(e.cron){const t=e.jobName,i=Object.assign(Object.assign({},e),{jobId:t}),n=c.default.scheduleJob(e.cron,(()=>{this.executeJob(i).catch((e=>this.logger.error(`Error execute job ${i.jobName} with id: ${i.jobId}`,e)))}));return this.jobHolder[t]={jobCanceler:()=>n.cancel(),jobInfo:Object.assign(Object.assign({},e),{jobId:t})},t}throw a.ErrorBuilder.systemError(`Job does not have time config: ${e.jobName}`)}{const t=yield this.redisClient.incr(this.uniqueIdKey);return new Promise((i=>{this.notifyResolver[t]=i,this.sendJob(f.SCHEDULE_JOB,t,e)}))}}))}removeJob(e){return r(this,void 0,void 0,(function*(){if(this.isActive){const t=this.jobHolder[e];return t&&(t.jobCanceler(),this.jobHolder[e]=void 0),void(yield this.jobRepo.removeJobById(e))}{const t=yield this.redisClient.incr(this.uniqueIdKey);return new Promise((i=>{this.notifyResolver[t]=i,this.sendJob(f.REMOVE_JOB,t,e)}))}}))}};y=n([(0,a.Initable)(),o("design:paramtypes",[a.AbstractLogger,h.AbstractJobRepository,String,String,String,String,String,Number])],y),t.LocalJobScheduler=y},1556:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CustomJob=t.CronJob=t.IntervalJob=void 0;const n=i(2318);t.IntervalJob=(e,t)=>(i,o)=>{const r=(0,n.initObjectMetadata)(i);r.jobs||(r.jobs=[]),r.jobs.push({jobName:e,interval:t,handlerName:o})};t.CronJob=(e,t)=>(i,o)=>{const r=(0,n.initObjectMetadata)(i);if(r.jobs||(r.jobs=[]),5!==t.split(" ").length)throw n.ErrorBuilder.systemError("Invalid cron expression, expect minute / hour / day / month / day-of-week");r.jobs.push({jobName:e,cron:t,handlerName:o})};t.CustomJob=e=>(t,i)=>{const o=(0,n.initObjectMetadata)(t);o.jobs||(o.jobs=[]),o.jobs.push({jobName:e,handlerName:i})}},2363:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.JobInterval=t.CRON_REQUEST_METHOD=t.INTERVAL_REQUEST_METHOD=void 0,t.INTERVAL_REQUEST_METHOD="interval",t.CRON_REQUEST_METHOD="cron",function(e){e[e.EVERY_5S=5]="EVERY_5S",e[e.EVERY_10S=10]="EVERY_10S",e[e.EVERY_15S=15]="EVERY_15S",e[e.EVERY_20S=20]="EVERY_20S",e[e.EVERY_30S=30]="EVERY_30S"}(t.JobInterval||(t.JobInterval={}))},5572:function(e,t,i){var n,o=this&&this.__decorate||function(e,t,i,n){var o,r=arguments.length,s=r<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,n);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,i,s):o(t,i))||s);return r>3&&s&&Object.defineProperty(t,i,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,i,n){return new(i||(i=Promise))((function(o,r){function fulfilled(e){try{step(n.next(e))}catch(e){r(e)}}function rejected(e){try{step(n.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((n=n.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(i(7147)),l=a(i(1017)),c=i(2318);let u=n=class FileLogMedium{constructor(e){const t=e.separated?n.levels.map((t=>l.default.join(e.destination,t+".log"))):[e.destination];this.destination=t.map((e=>(d.default.existsSync(l.default.dirname(e))||d.default.mkdirSync(l.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 i=this.separated?this.destination[n.levels.indexOf(e)]:0;d.default.appendFileSync(i,t)}};u.levels=Object.values(c.LogLevel),u=n=o([(0,c.Initable)(),r("design:paramtypes",[Object])],u),t.FileLogMedium=u},7577:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractCacheService=void 0;t.AbstractCacheService=class AbstractCacheService{}},8709:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractFileService=void 0;t.AbstractFileService=class AbstractFileService{}},204:function(e,t,i){var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(o,r){function fulfilled(e){try{step(n.next(e))}catch(e){r(e)}}function rejected(e){try{step(n.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((n=n.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractService=void 0;const o=i(7756);t.AbstractService=class AbstractService{constructor(e){this.databaseAdapter=e}createTransaction(){return this.databaseAdapter.createTransaction()}getCurrentTransaction(){return n(this,void 0,void 0,(function*(){return(0,o.getTransactionFromContext)(this)}))}}},6862:function(e,t,i){var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(o,r){function fulfilled(e){try{step(n.next(e))}catch(e){r(e)}}function rejected(e){try{step(n.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((n=n.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractServerSocket=void 0;const o=i(2318);t.AbstractServerSocket=class AbstractServerSocket{constructor(e){this.socketInfo=e}getId(){return this.socketInfo.id}getAuthInfo(){return this.socketInfo.authInfo}send(e,t){return n(this,void 0,void 0,(function*(){t?this.socketInfo.channels.find((e=>e.name===t&&e.serverToClientAllowed))&&(yield this.sendRaw({type:o.MessageType.PLAIN,data:{message:e,channel:t}})):yield this.sendRaw({type:o.MessageType.PLAIN,data:{message:e}})}))}sendRaw(e){return n(this,void 0,void 0,(function*(){yield this.physicSend(e)}))}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}}},5530:function(e,t,i){var n=this&&this.__decorate||function(e,t,i,n){var o,r=arguments.length,s=r<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,n);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,i,s):o(t,i))||s);return r>3&&s&&Object.defineProperty(t,i,s),s},o=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(o,r){function fulfilled(e){try{step(n.next(e))}catch(e){r(e)}}function rejected(e){try{step(n.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((n=n.apply(e,t||[])).next())}))},r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractServerSocketManager=void 0;const s=i(2318),a=r(i(1495)),d=i(9990),l=i(2665),c=i(2255),u=i(1532),h="x-socket-action",p="read",f="write";let y=class SocketReadCondition extends c.AbstractAccessCondition{resolveConditionValue(e){return o(this,void 0,void 0,(function*(){return e.getHeaders()["x-socket-action"]===p}))}validate(e){return o(this,void 0,void 0,(function*(){return!!e}))}getConditionMetadata(){return{name:"socket_read",description:"Can receive message from channel",valueType:s.AccessConditionValueType.BOOLEAN}}};y=n([(0,s.Register)()],y);let g=class SocketWriteCondition extends c.AbstractAccessCondition{resolveConditionValue(e){return o(this,void 0,void 0,(function*(){return e.getHeaders()["x-socket-action"]===f}))}validate(e){return o(this,void 0,void 0,(function*(){return!!e}))}getConditionMetadata(){return{name:"socket_write",description:"Can send message to channel",valueType:s.AccessConditionValueType.BOOLEAN}}};g=n([(0,s.Register)()],g);t.AbstractServerSocketManager=class AbstractServerSocketManager{constructor(e,t,i,n,o){this.requireAuthentication=e,this.logger=t,this.redisServerUrl=i,this.authProvider=n,this.authResolver=o,this._connectionHandler=null,this.redisClient=new a.default(this.redisServerUrl)}getUniqueChannelPrefix(){return"CHANNEL:"}getSocketInfoHashKey(){return"__SOCKET_INFO__"}getConnectionHandler(){return o(this,void 0,void 0,(function*(){if(null===this._connectionHandler){const e=(0,s.getServiceProvider)().getInjector();this._connectionHandler=e.resolveOptional(d.AbstractSocketConnectionHandler),yield e.initInstances()}return this._connectionHandler}))}formatBroadcastData(e,t){return{type:s.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 this.redisClient.smembers(this.getUniqueChannelName(e)))||[]}))}addSocketToChannel(e,t){return o(this,void 0,void 0,(function*(){const i=yield this.getById(e);return i&&(i.addChannels(t),yield Promise.all(t.map((t=>this.redisClient.sadd(this.getUniqueChannelName(t.name),e)))),yield i.saveSocketInfo()),i}))}removeSocketFromChannel(e,t,i=!0){return o(this,void 0,void 0,(function*(){if(!t.length)return;const n=yield this.getById(e);n&&(n.removeChannels(t),yield Promise.all(t.map((t=>this.redisClient.srem(this.getUniqueChannelName(t),e)))),i&&(yield n.saveSocketInfo()))}))}removeSocket(e,t=!0){return o(this,void 0,void 0,(function*(){const t=yield this.getById(e);t&&(this.logger.debug("Remove from all channels"),yield this.removeSocketFromChannel(e,t.getChannelsInfo().map((e=>e.name)),!1)),this.logger.debug("Remove from redis"),yield this.redisClient.hdel(this.getSocketInfoHashKey(),e)}))}handle(e){var t;return o(this,void 0,void 0,(function*(){this.logger.debug("Handle socket data",e);const i=yield this.getConnectionHandler();switch(e.method){case s.SocketMethod.CONNECT:{this.logger.debug("Socket connection attempt",e);const i=this.authResolver(null===(t=e.data)||void 0===t?void 0:t.queries),n=yield this.authProvider.getPrincipalResolver().resolvePrincipal(i);if(!n&&this.requireAuthentication)throw s.ErrorBuilder.error(s.Errors.AUTHENTICATION_ERROR);yield this.addSocket({id:e.socketId,authInfo:n,channels:[],createdAt:Date.now()},e.data);break}case s.SocketMethod.DISCONNECT:{this.logger.debug("Socket disconnect",e);const t=yield this.getById(e.socketId);if(t){const e=yield this.getMountedEndpointInfo();this.logger.debug("Notify channels");for(const i of t.getChannelsInfo()){const n=e.find((e=>e.endpointMetadata.url===i.name));n&&n.endpoint.controller.onChannelLeave(t)}this.logger.debug("Calling disconnection handler"),null==i||i.onSocketDisconnect(t),this.logger.debug("Removing socket"),yield this.removeSocket(t.getId(),!1)}break}case s.SocketMethod.MESSAGE:{this.logger.debug("Socket message",e);const t=e.data;let n=yield this.getById(e.socketId);if(n)switch(t.type){case s.MessageType.READY:yield n.sendRaw({type:s.MessageType.READY,data:""}),yield null==i?void 0:i.onSocketConnect(n);break;case s.MessageType.PING_PONG:yield n.sendRaw({type:s.MessageType.PING_PONG,data:t.data});break;case s.MessageType.CHANNEL_JOIN:{const e=t.data,i=[],o=[];for(const t of e){let e=!1,r=!1;const a=(yield this.getMountedEndpointInfo()).find((e=>e.endpointMetadata.url===t));if(a){try{const e=new u.HttpRequest({method:s.SocketMethod.MESSAGE,pathName:t,headers:{[h]:p}},a.endpointMetadata);yield this.authProvider.authorize(n.getAuthInfo(),e,a),r=!0}catch(e){this.logger.debug("Error in read authorize",e)}try{const i=new u.HttpRequest({method:s.SocketMethod.MESSAGE,pathName:t,headers:{[h]:f}},a.endpointMetadata);yield this.authProvider.authorize(n.getAuthInfo(),i,a),e=!0}catch(e){this.logger.debug("Error in write authorize",e)}(e||r)&&(this.logger.debug("Adding channel info",t,e,r),i.push({name:t,clientToServerAllowed:e,serverToClientAllowed:r}),o.push(a))}}n=yield this.addSocketToChannel(n.getId(),i),n?yield Promise.all([n.sendRaw({type:s.MessageType.CHANNEL_JOIN,data:i.map((e=>e.name))}),...o.map((e=>e.endpoint.controller.onChannelJoin(n)))]):this.logger.debug("Socket not found after addSocketToChannel")}break;case s.MessageType.CHANNEL_LEAVE:{const e=t.data,i=yield this.getMountedEndpointInfo();Promise.all(e.map((e=>()=>{const t=i.find((t=>t.endpointMetadata.url===e));if(t)return t.endpoint.controller.onChannelLeave(n)}))),yield this.removeSocketFromChannel(n.getId(),e)}break;case s.MessageType.PLAIN:{const e=t.data.channel,o=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!==(yield t.endpoint.controller.onMessage(n,o))&&(this.logger.debug("broadcasting to channel",e,o),this.broadcastToChannel(e,o))}}}else yield null==i?void 0:i.onMessage(n,o)}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,s.getServiceProvider)().getInjector(),t=e.resolveMultiple(l.AbstractSocketController);yield e.initInstances(),this.mountedEndpointInfo=t.map((e=>({endpoint:{httpMethod:s.SocketMethod.MESSAGE,mount:e.channel,controller:e,handlerFunctionName:e.onMessage.name},endpointMetadata:{httpMethod:s.SocketMethod.MESSAGE,description:"Send / Receive message to / from channel",dataType:s.DataType.OBJECT,url:e.channel,name:e.channel,accessConditions:[y,g]}})))}return this.mountedEndpointInfo}))}}},9990:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractSocketConnectionHandler=void 0;t.AbstractSocketConnectionHandler=class AbstractSocketConnectionHandler{}},2665:function(e,t){var i=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(o,r){function fulfilled(e){try{step(n.next(e))}catch(e){r(e)}}function rejected(e){try{step(n.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((n=n.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractSocketController=void 0;t.AbstractSocketController=class AbstractSocketController{constructor(e){this.channel=e}onChannelJoin(e){return i(this,void 0,void 0,(function*(){}))}onChannelLeave(e){return i(this,void 0,void 0,(function*(){}))}onMessage(e,t){return i(this,void 0,void 0,(function*(){}))}}},7152:function(e,t,i){var n=this&&this.__decorate||function(e,t,i,n){var o,r=arguments.length,s=r<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,n);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,i,s):o(t,i))||s);return r>3&&s&&Object.defineProperty(t,i,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,i,n){return new(i||(i=Promise))((function(o,r){function fulfilled(e){try{step(n.next(e))}catch(e){r(e)}}function rejected(e){try{step(n.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((n=n.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=i(2318),d=s(i(9336)),l=i(767),c=i(5530),u=i(6862),h=i(859);class ApiGatewaySocket extends u.AbstractServerSocket{constructor(e,t,i,n,o,r){super(i),this.socketManager=e,this.logger=t,this.socketInfo=i,this.apiGateway=n,this.socketNamespace=o,this.redisClient=r}saveSocketInfo(){return r(this,void 0,void 0,(function*(){yield this.redisClient.hset(this.socketNamespace,this.socketInfo.id,JSON.stringify(this.socketInfo))}))}physicSend(e){return r(this,void 0,void 0,(function*(){this.logger.debug("aws socket physic send",e),yield this.socketManager.physicSend(this.getId(),e)}))}disconnect(e){return r(this,void 0,void 0,(function*(){e&&(yield this.physicSend(e)),yield this.socketManager.removeSocket(this.getId())}))}serialize(){return JSON.stringify(this.socketInfo)}}let p=class AwsSocketManager extends c.AbstractServerSocketManager{constructor(e,t,i,n,o,r,s,a){super(e,a,n,r,s),this.authenticationRequired=e,this.region=t,this.socketDomainUrl=i,this.redisServerUrl=n,this.httpRequestHandler=o,this.authorizationProvider=r,this.authResolver=s,this.logger=a,this.apiGatewayManagement=new d.default.ApiGatewayManagementApi({region:t,apiVersion:"2018-11-29",endpoint:i})}init(){return r(this,void 0,void 0,(function*(){this.logger.info("AwsSocketManager init")}))}exit(){this.redisClient.disconnect(),this.logger.info("AwsSocketManager exit")}removeSocketFromRedis(e){return r(this,void 0,void 0,(function*(){yield this.redisClient.hdel(this.getSocketInfoHashKey(),e)}))}physicSend(e,t){return r(this,void 0,void 0,(function*(){try{this.logger.debug(`Socket ${e} sending`,t),yield this.apiGatewayManagement.postToConnection({ConnectionId:e,Data:JSON.stringify(t)}).promise()}catch(t){throw this.logger.debug(`Socket ${e} post error`,t),410===t.statusCode&&(this.logger.debug(`Disconnect & remove stale socket ${e}`),yield this.removeSocket(e,!1),this.logger.debug(`Socket removed ${e}`)),t}}))}configure(e){this.logger.debug("Aws socket manager configure")}getSocketsByChannel(e){return r(this,void 0,void 0,(function*(){const t=yield this.getSocketIdsOfChannel(e);if(!t.length)return[];return(yield this.redisClient.hmget(this.getSocketInfoHashKey(),...t)).filter((e=>!!e)).map((e=>this.getSocketBySerialized(e)))}))}broadcastToChannel(e,t){return r(this,void 0,void 0,(function*(){const i=yield this.getSocketIdsOfChannel(e);if(i.length){const n=this.formatBroadcastData(e,t);i.map((e=>this.physicSend(e,n).catch((t=>this.logger.error(`Cannot send to socket ${e}`,t)))))}}))}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 yield t.saveSocketInfo(),t}))}removeSocket(e,t=!0){const i=Object.create(null,{removeSocket:{get:()=>super.removeSocket}});return r(this,void 0,void 0,(function*(){this.logger.debug(`Aws socket manager remove socket: ${e}, ${t}`),yield i.removeSocket.call(this,e,t),this.logger.debug("Super remove ok"),t&&this.apiGatewayManagement.deleteConnection({ConnectionId:e}).promise().catch((e=>this.logger.error("Cannot physic remove aws socket",e)))}))}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 this.redisClient.hget(this.getSocketInfoHashKey(),e);if(t)return this.logger.debug("Serialized aws socket",t),this.getSocketBySerialized(t);this.logger.error("Cannot find socket with id: "+e)}))}};p=n([(0,a.Initable)(),o("design:paramtypes",[Boolean,String,String,String,l.AbstractHttpRequestHandler,h.AbstractHttpAuthorizationProvider,Function,a.AbstractLogger])],p),t.AwsSocketManager=p},8577:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},2841:function(e,t,i){var n=this&&this.__decorate||function(e,t,i,n){var o,r=arguments.length,s=r<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,n);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,i,s):o(t,i))||s);return r>3&&s&&Object.defineProperty(t,i,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,i,n){return new(i||(i=Promise))((function(o,r){function fulfilled(e){try{step(n.next(e))}catch(e){r(e)}}function rejected(e){try{step(n.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((n=n.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=i(2318),d=s(i(5352)),l=s(i(9215)),c=s(i(9103)),u=i(5530),h=i(6862),p=i(859);var f;!function(e){e.SEND="SEND",e.CLOSE="CLOSE",e.SAVE="SAVE"}(f||(f={}));class RedisSocket extends h.AbstractServerSocket{constructor(e,t,i){super(i),this.socketChannelName=e,this.redisClient=t,this.socketInfo=i}physicSend(e){return r(this,void 0,void 0,(function*(){yield this.redisClient.publish(this.socketChannelName,JSON.stringify({type:f.SEND,data:e}))}))}disconnect(e){return r(this,void 0,void 0,(function*(){yield this.redisClient.publish(this.socketChannelName,JSON.stringify({type:f.CLOSE,data:e}))}))}saveSocketInfo(){return r(this,void 0,void 0,(function*(){yield this.redisClient.publish(this.socketChannelName,JSON.stringify({type:f.SAVE,data:this.socketInfo}))}))}}class ExpressSocket extends h.AbstractServerSocket{constructor(e,t,i,n,o){super(n),this.socketManager=e,this.logger=t,this.socket=i,this.socketInfo=n,this.infoSaver=o}saveSocketInfo(){return r(this,void 0,void 0,(function*(){yield this.infoSaver(this.socketInfo)}))}physicSend(e){return r(this,void 0,void 0,(function*(){this.socket.send(JSON.stringify(e))}))}disconnect(e){return r(this,void 0,void 0,(function*(){this.socket.close(1e3,e&&JSON.stringify(e)),yield this.socketManager.removeSocket(this.getId())}))}}let y=class LocalSocketManager extends u.AbstractServerSocketManager{constructor(e,t,i,n,o){super(e,i,t,n,o),this.authenticationRequired=e,this.redisServerUrl=t,this.logger=i,this.authProvider=n,this.authResolver=o,this.allSockets=[],this.subscribedChannels=[],this.subClient=this.redisClient.duplicate(),this.channelSubClient=this.redisClient.duplicate(),this.sendClient=this.redisClient.duplicate()}init(){return r(this,void 0,void 0,(function*(){this.logger.info("LocalSocketManager init"),this.channelSubClient.on("message",((e,t)=>{this.logger.debug("channelSubClient: ",t,e),this.channelMessageListenner(t,e)})),this.subClient.on("message",((e,t)=>{this.logger.debug("subClient: ",t,e),this.socketMessageListener(t,e)}))}))}exit(){this.sendClient.disconnect(),this.subClient.disconnect(),this.channelSubClient.disconnect(),this.redisClient.disconnect(),this.logger.info("LocalSocketManager exit")}channelMessageListenner(e,t){this.logger.debug("Receiving message from channel",t,e);const i=JSON.parse(e);i.type===a.MessageType.PLAIN&&this.allSockets.forEach((e=>{e.send(i.data.message,i.data.channel)}))}socketMessageListener(e,t){this.logger.debug("Receiving message from remote socket channel",t,e);const i=t.substring(this.getSocketChannelKeyPrefix().length),n=this.allSockets.find((e=>e.getId()===i));if(n){const t=JSON.parse(e);switch(t.type){case f.SEND:n.physicSend(t.data);break;case f.SAVE:n.socketInfo.channels=t.data,n.saveSocketInfo();break;case f.CLOSE:n.disconnect(t.data);break;default:this.logger.debug("Invalid remote command",t)}}}getUniqueDataChannelName(e){return`CHANNEL_DATA:${e}`}getSocketChannelKeyPrefix(){return"SOCKET_CHANNEL:"}getSocketChannelKey(e){return`${this.getSocketChannelKeyPrefix()}${e}`}broadcastToChannel(e,t){return r(this,void 0,void 0,(function*(){const i=this.formatBroadcastData(e,t);yield this.redisClient.publish(this.getUniqueDataChannelName(e),JSON.stringify(i))}))}addSocketToChannel(e,t){const i=Object.create(null,{addSocketToChannel:{get:()=>super.addSocketToChannel}});return r(this,void 0,void 0,(function*(){const n=yield i.addSocketToChannel.call(this,e,t),o=t.map((e=>e.name)).filter((e=>!this.subscribedChannels.includes(e)));return o.length&&(yield Promise.all(o.map((e=>this.channelSubClient.subscribe(this.getUniqueDataChannelName(e))))),this.subscribedChannels.push(...o)),n}))}removeSocketFromChannel(e,t,i=!0){const n=Object.create(null,{removeSocketFromChannel:{get:()=>super.removeSocketFromChannel}});return r(this,void 0,void 0,(function*(){yield n.removeSocketFromChannel.call(this,e,t,i),yield Promise.all(t.map((e=>this.channelSubClient.unsubscribe(this.getUniqueChannelName(e))))),this.subscribedChannels=this.subscribedChannels.filter((e=>!t.includes(e)))}))}addSocket(e,{socket:t}){return r(this,void 0,void 0,(function*(){const i=new ExpressSocket(this,this.logger,t,e,(e=>r(this,void 0,void 0,(function*(){yield this.redisClient.hset(this.getSocketInfoHashKey(),e.id,JSON.stringify(e))})))),n=this.getSocketChannelKey(e.id);return yield this.subClient.subscribe(n),this.allSockets.push(i),i}))}removeSocket(e,t=!0){const i=Object.create(null,{removeSocket:{get:()=>super.removeSocket}});return r(this,void 0,void 0,(function*(){yield i.removeSocket.call(this,e,t);const n=this.getSocketChannelKey(e);yield this.subClient.unsubscribe(n),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 i=yield new Promise((t=>this.redisClient.hget(this.getSocketInfoHashKey(),e).then((e=>t(e?JSON.parse(e):void 0))).catch((e=>{this.logger.error(e),t(void 0)}))));i&&(t=new RedisSocket(this.getSocketChannelKey(e),this.sendClient,i))}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 i=t.headers["sec-websocket-key"];let n=!1,o=[];const r=(0,l.default)({url:t.url}),s=c.default.parse(decodeURIComponent(r.search||""));this.handle({method:a.SocketMethod.CONNECT,socketId:i,data:{queries:s,socket:e}}).then((()=>{n=!0;for(const e of o)this.handle(e).catch((e=>{this.logger.error(e)}))})).catch((t=>{o=[],e.close(1e3,`${t.name}:${t.message}`)})),e.onmessage=e=>{const t={method:a.SocketMethod.MESSAGE,socketId:i,data:e.data&&JSON.parse(e.data)};n?this.handle(t).catch((e=>{this.logger.error(e)})):o.push(t)},e.onclose=()=>{this.handle({method:a.SocketMethod.DISCONNECT,socketId:i}).catch((e=>{this.logger.error(e)}))}}))}};y=n([(0,a.Initable)(),o("design:paramtypes",[Boolean,String,a.AbstractLogger,p.AbstractHttpAuthorizationProvider,Function])],y),t.LocalSocketManager=y},5537:function(e,t,i){var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(o,r){function fulfilled(e){try{step(n.next(e))}catch(e){r(e)}}function rejected(e){try{step(n.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((n=n.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.ClaireServer=void 0;const o=i(2318),r=i(137),s=i(4972);class ClaireServer extends o.ClaireApp{constructor(e,t,i){super(),this.logger=e,this.httpRequestHandler=t,this.socketManager=i,this.booted=!1}init(){return n(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},226:function(e,t,i){var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(o,r){function fulfilled(e){try{step(n.next(e))}catch(e){r(e)}}function rejected(e){try{step(n.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((n=n.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=i(2318),s=o(i(6860)),a=o(i(3685)),d=o(i(3582)),l=o(i(6674)),c=i(5530),u=i(767);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(c.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,i;return n(this,void 0,void 0,(function*(){yield this.server.init(),yield this.injector.initInstances();const o=(0,s.default)(),c=a.default.createServer(o);return null===(t=this.socketManager)||void 0===t||t.configure(c),o.use((0,d.default)()),o.use(s.default.raw({limit:1024*((null===(i=this.config)||void 0===i?void 0:i.maxBodySizeKB)||4096)})),o.use((0,l.default)()),o.use(((e,t,i)=>{e.files&&(e.body||(e.body={}),Object.keys(e.files).forEach((t=>{e.body[t]=e.files[t]}))),i()})),o.use(s.default.urlencoded({extended:!1})),o.use(s.default.json()),o.all("*",((e,t)=>{(()=>n(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 i={socketId:e.body.connectionId,data:e.body.data,method:e.body.type.toLowerCase()};if(i.method===r.SocketMethod.CONNECT){const t=e.body.data.querystring,n=t.substring(1,t.length-1).split(",").map((e=>e.trim().split("="))).reduce(((e,t)=>Object.assign(e,{[t[0]]:t[1]})),{});i.data={queries:n}}yield this.socketManager.handle(i).then((()=>{t.status(200).send()})).catch((e=>{this.logger.debug("Handle error",e),t.status(400).json({name:e.name,message:e.message})}))}else{if(!this.httpRequestHandler)throw r.ErrorBuilder.systemError("Http request handler not found");const i={fullPath:e.url,method:e.method.toLowerCase(),headers:e.headers,body:e.body},n=yield this.httpRequestHandler.handle(i);n.headers&&Object.keys(n.headers).forEach((e=>{t.set(e,n.headers[e])})),t.status(n.code||200).send(n.value)}})))().catch((e=>{this.logger.error(e),t.status(400).json({name:e.name,message:e.message})}))})),new Promise(((t,i)=>{this.httpServer=c.listen(e,t).on("error",i)}))}))}}},8836:function(e,t,i){var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(o,r){function fulfilled(e){try{step(n.next(e))}catch(e){r(e)}}function rejected(e){try{step(n.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((n=n.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.LambdaWrapper=void 0;const o=i(2318),r=i(767),s=i(3376),a=i(2363),d=i(5530),l=i(6721),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.serverFactory=e,this.requestMapper=t,this.requestMapper=t,this.handler=this.handler.bind(this),this.injector=(0,o.getServiceProvider)().getInjector(),this.logger=this.injector.resolve(o.AbstractLogger),this.socketManager=this.injector.resolveOptional(d.AbstractServerSocketManager),this.httpRequestHandler=this.injector.resolveOptional(r.AbstractHttpRequestHandler),this.jobScheduler=this.injector.resolveOptional(s.AwsJobScheduler)}bootServer(){var e;return n(this,void 0,void 0,(function*(){return this._server||(this._server=yield this.serverFactory(),yield this.injector.initInstances(),null===(e=this.socketManager)||void 0===e||e.configure(),yield this._server.init()),this._server}))}handler(e){var t,i;return n(this,void 0,void 0,(function*(){yield this.bootServer();const n=this.requestMapper(e);if(!n)return toApiGatewayFormat(400,"Cannot resolve event");if(n.method===o.HttpMethod.OPTIONS)return toApiGatewayFormat(200);if(n.method===a.INTERVAL_REQUEST_METHOD)return yield null===(t=this.jobScheduler)||void 0===t?void 0:t.handleInterval(n.body),toApiGatewayFormat(200);if(n.method===a.CRON_REQUEST_METHOD)return yield null===(i=this.jobScheduler)||void 0===i?void 0:i.handleCron(n.body),toApiGatewayFormat(200);try{if(Object.values(o.HttpMethod).includes(n.method)){if(!this.httpRequestHandler)throw o.ErrorBuilder.error(l.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||200,t.value)}if(!Object.values(o.SocketMethod).includes(n.method))throw o.ErrorBuilder.error(l.Errors.HTTP_REQUEST_ERROR,"Not allow request method: "+n.method);{if(!this.socketManager)throw o.ErrorBuilder.error(l.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})}}))}}},9627:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getSystemLocale=t.setSystemLocale=void 0;const n=i(2318);t.setSystemLocale=e=>{(0,n.getGlobalStore)().systemLocale=e};t.getSystemLocale=()=>{var e;return(null===(e=(0,n.getGlobalStore)().systemLocale)||void 0===e?void 0:e.toLowerCase())||""}},6721:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Errors=void 0;const n=i(2318);t.Errors=Object.assign(Object.assign({},n.Errors),{TFA_REQUIRED:"TFA_REQUIRED"})},889:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.lambdaRequestMapper=void 0;const n=i(2318),o=i(2363);t.lambdaRequestMapper=e=>{if(e.requestContext.eventType){const t=e.requestContext.eventType.toLowerCase(),i=e.body&&JSON.parse(e.body);return{method:t,rawPath:e.requestContext.connectionId,body:t===n.SocketMethod.CONNECT?{queries:e.queryStringParameters}:i}}return e.requestContext.intervalScheduler?{method:o.INTERVAL_REQUEST_METHOD,rawPath:"",body:e.requestContext.intervalScheduler.time}:e.requestContext.cronScheduler?{method:o.CRON_REQUEST_METHOD,rawPath:"",body:e.requestContext.cronScheduler.data}:{method:e.requestContext.http.method.toLowerCase(),rawPath:`${e.rawPath}?${e.rawQueryString}`,body:e.body&&JSON.parse(e.body),headers:e.headers}}},5481:function(e,t,i){var n=this&&this.__decorate||function(e,t,i,n){var o,r=arguments.length,s=r<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,n);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,i,s):o(t,i))||s);return r>3&&s&&Object.defineProperty(t,i,s),s};Object.defineProperty(t,"__esModule",{value:!0}),t.LocaleEntry=void 0;const o=i(2318);let r=class LocaleEntry extends o.AbstractModel{};r=n([(0,o.Model)()],r),t.LocaleEntry=r},2552:function(e,t,i){var n=this&&this.__decorate||function(e,t,i,n){var o,r=arguments.length,s=r<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,n);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,i,s):o(t,i))||s);return r>3&&s&&Object.defineProperty(t,i,s),s},o=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};Object.defineProperty(t,"__esModule",{value:!0}),t.LocaleTranslation=void 0;const r=i(2318),s=i(5481),a="translation_unique";let d=class LocaleTranslation extends r.AbstractModel{};n([(0,r.Column)(Object.assign(Object.assign({description:"Id of the locale",isRequired:!0},(0,r.FK)({model:s.LocaleEntry,cascade:"delete"})),{unique:{groupName:a}})),o("design:type",Number)],d.prototype,"entryId",void 0),n([(0,r.Column)({description:"Code of locale",isRequired:!0,unique:{groupName:a},textLength:3}),o("design:type",String)],d.prototype,"localeCode",void 0),n([(0,r.Column)({description:"Translation of locale",isRequired:!0}),o("design:type",String)],d.prototype,"translation",void 0),d=n([(0,r.Model)()],d),t.LocaleTranslation=d},10:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.LocaleOf=void 0;const n=i(2318),o=i(5481);t.LocaleOf=e=>(t,i)=>{const r=(0,n.initFieldMetadata)(t,i);r.multiLocaleColumn=e,r.fk=(0,n.FK)({model:o.LocaleEntry,cascade:"nullify"}).fk,r.dataType=n.DataType.NUMBER;(0,n.initFieldMetadata)(t,e).isMultiLocale=!0}},2318:e=>{e.exports=require("@clairejs/core")},7756:e=>{e.exports=require("@clairejs/orm")},9336:e=>{e.exports=require("aws-sdk")},3582:e=>{e.exports=require("cors")},6860:e=>{e.exports=require("express")},6674:e=>{e.exports=require("express-fileupload")},1495:e=>{e.exports=require("ioredis")},7344:e=>{e.exports=require("node-schedule")},9215:e=>{e.exports=require("parseurl")},99:e=>{e.exports=require("path-to-regexp")},9103:e=>{e.exports=require("query-string")},9896:e=>{e.exports=require("redlock")},5352:e=>{e.exports=require("ws")},7147:e=>{e.exports=require("fs")},3685:e=>{e.exports=require("http")},1017:e=>{e.exports=require("path")},9512:e=>{e.exports=require("timers")}},t={};var i=function __webpack_require__(i){var n=t[i];if(void 0!==n)return n.exports;var o=t[i]={exports:{}};return e[i].call(o.exports,o,o.exports,__webpack_require__),o.exports}(341);return i})()));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@clairejs/server",
3
- "version": "3.8.6",
3
+ "version": "3.9.0",
4
4
  "description": "Claire server NodeJs framework written in Typescript.",
5
5
  "types": "dist/index.d.ts",
6
6
  "main": "dist/index.js",
@@ -32,7 +32,7 @@
32
32
  "ws": "^7.5.5"
33
33
  },
34
34
  "peerDependencies": {
35
- "@clairejs/core": "^3.1.28",
35
+ "@clairejs/core": "^3.1.34",
36
36
  "@clairejs/orm": "^3.1.2"
37
37
  },
38
38
  "devDependencies": {