@clairejs/server 3.6.9 → 3.6.10
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 +2 -1
- package/dist/index.js +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
## Change Log
|
|
2
2
|
|
|
3
|
-
#### 3.6.
|
|
3
|
+
#### 3.6.10
|
|
4
4
|
|
|
5
|
+
- fix AwsSocketManager does not remove socket from redis when disconnect
|
|
5
6
|
- handle default "" or "/" endpoint correctly
|
|
6
7
|
- fix CrudHttpController filter by boolean field
|
|
7
8
|
- fix AwsSocketManager not remove socket from channel after disconnection
|
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 o in n)("object"==typeof exports?exports:e)[o]=n[o]}}(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 o=this&&this.__awaiter||function(e,t,n,o){return new(n||(n=Promise))((function(i,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?i(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractRbacAuthProvider=void 0;const i=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 o(this,void 0,void 0,(function*(){if(n.endpointMetadata.openAccess)return;const o=yield this.getRbacCache();if(!o)throw i.ErrorBuilder.error(i.Errors.SYSTEM_ERROR,"Cannot read rbac cache");let r=[];if(e){const t=yield this.getRolesOfPrincipal(e);r=(o.roles||[]).filter((e=>!!t.find((t=>t===e.roleId))))}else r=(o.roles||[]).filter((e=>e.isAnonymousRole));if(!r.length)throw i.ErrorBuilder.error(i.Errors.ACCESS_DENIED,"No role attached");if(r.find((e=>e.isSuperRole)))return;const a=(o.rolePolicies||[]).filter((e=>!!r.find((t=>t.roleId===e.roleId)))),d=(o.policies||[]).filter((e=>!!a.find((t=>t.policyId===e.policyId)))),l=(o.policyPermissions||[]).filter((e=>!!d.find((t=>t.policyId===e.policyId)))),c=(o.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 i.ErrorBuilder.error(i.Errors.ACCESS_DENIED,`Not permitted: ${(0,s.getEndpointId)(n.endpoint)}`);let h=!1;for(const e of u){const o=c.filter((t=>t.policyPermissionId===e.id));if(o.length){let e=!0;const r=(0,i.getServiceProvider)().getInjector(),s=(n.endpointMetadata.accessConditions||[]).map((e=>r.resolve(e)));yield r.initInstances();for(const n of o){const o=s.find((e=>e.getConditionMetadata().name===n.conditionName));if(!o)continue;const i=yield o.resolveConditionValue(t),r=JSON.parse(n.conditionValue);if(e=yield o.validate(i,r),!e){this.logger.debug("Condition check failed: condition, requested, permitted",n.conditionName,i,r);break}}h=e}else h=!0;if(h)break}if(!h)throw i.ErrorBuilder.error(i.Errors.ACCESS_DENIED,"Condition check failed")}))}}t.AbstractRbacAuthProvider=AbstractRbacAuthProvider},531:function(e,t,n){var o=this&&this.__awaiter||function(e,t,n,o){return new(n||(n=Promise))((function(i,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?i(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.RedisRbacAuthProvider=void 0;const i=n(2085);class RedisRbacAuthProvider extends i.AbstractRbacAuthProvider{constructor(e,t,n,o,i,r,s,a=3e4){super(o,i,s),this.serviceId=e,this.rbacChannel=t,this.principalChannel=n,this.authDataResolver=o,this.principalResolver=i,this.cacheService=r,this.logger=s,this.redisDataRetentionDurationMs=a,this.lastRbacFetchTimestamp=0,this.principalCache={}}getRbacCache(){return o(this,void 0,void 0,(function*(){if(this.lastRbacFetchTimestamp+this.redisDataRetentionDurationMs<Date.now()){const e=yield this.cacheService.hget(this.rbacChannel,this.serviceId);this.rbacCache=e,this.lastRbacFetchTimestamp=Date.now()}return this.rbacCache}))}getRolesOfPrincipal(e){return o(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),o=e?"string"==typeof e?JSON.parse(e):e:[];n={lastFetchTimestamp:Date.now(),roles:o},this.principalCache[t]=n}return n.roles}))}}t.RedisRbacAuthProvider=RedisRbacAuthProvider},7825:function(e,t,n){var o=this&&this.__decorate||function(e,t,n,o){var i,r=arguments.length,s=r<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,n):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,o);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(r<3?i(s):r>3?i(t,n,s):i(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},i=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,o){return new(n||(n=Promise))((function(i,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?i(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.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,o,i,r){super(n,o,i),this.rbacCacheChannel=e,this.principalCacheChannel=t,this.authDataResolver=n,this.principalResolver=o,this.logger=i,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,o=this.idResolvers.find((e=>e.principalId===t));if(o){for(const e of o.resolvers)e(n);o.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 o=this.idResolvers.find((t=>t.principalId===e.id));o||(o={principalId:e.id,resolvers:[]},this.idResolvers.push(o)),o.resolvers.length||null===(n=this.socket)||void 0===n||n.send(e.id,this.principalCacheChannel),o.resolvers.push(t)}))}))}};l=o([(0,s.Initable)(),i("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 o=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,o.validateData)(this.params,null==t?void 0:t.paramsValidationDto)),this.query=e.query||{},(null==t?void 0:t.queriesValidationDto)&&(this.query=(0,o.validateData)(this.jsonParsing(this.query,t.queriesValidationDto),t.queriesValidationDto)),this.body=e.body||{},t&&(t.httpMethod===o.HttpMethod.POST||t.httpMethod===o.HttpMethod.PUT)&&(null==t?void 0:t.bodyValidationDto)&&(this.body=(0,o.validateData)(this.body||{},t.bodyValidationDto))}jsonParsing(e,t){const n=Object.assign({},e);for(const i of t.fields)try{(void 0!==e[i.name]||i.isRequired)&&(n[i.name]=JSON.parse(e[i.name]))}catch(e){throw o.ErrorBuilder.error(o.Errors.VALIDATION_ERROR,`JSON parsing failed for field ${i.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 o=this&&this.__awaiter||function(e,t,n,o){return new(n||(n=Promise))((function(i,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?i(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractHttpController=void 0;const i=n(2318),r=n(7756);t.AbstractHttpController=class AbstractHttpController{constructor(e){this.databaseAdapter=e}createTransaction(){return o(this,void 0,void 0,(function*(){return this.databaseAdapter.createTransaction()}))}getCurrentTransaction(){return o(this,void 0,void 0,(function*(){return(0,r.getTransactionFromContext)(this)}))}getEndpointMetadata(){const e=(0,i.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 o=this&&this.__awaiter||function(e,t,n,o){return new(n||(n=Promise))((function(i,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?i(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractHttpRequestHandler=void 0;const i=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 o(this,void 0,void 0,(function*(){if(!this.mountedEndpointInfo){const o=[],a=(0,i.getServiceProvider)().getInjector(),d=a.resolveMultiple(s.AbstractHttpController);yield a.initInstances();for(const e of d){const t=(0,i.getObjectMetadata)(e.constructor),n=e.getEndpointMetadata();for(const r of n){const n={mount:r.httpMethod===i.SocketMethod.MESSAGE?r.url:this.resolverMountPoint(t,[this.mountPoint||"/",r.url]),httpMethod:r.httpMethod,controller:e,handlerFunctionName:r.name};o.push({endpointMetadata:r,endpoint:n})}}const l=[];for(const i of o){const o=l.find((e=>e.endpoint.mount===i.endpoint.mount&&e.endpoint.httpMethod===i.endpoint.httpMethod));o?null===(e=this.logger)||void 0===e||e.warn(`Implicit overriding endpoint: ${(0,r.getEndpointId)(o.endpoint)} of ${null===(t=o.endpoint.controller)||void 0===t?void 0:t.constructor.name}:${o.endpoint.handlerFunctionName}`,`Ignore ${(0,r.getEndpointId)(i.endpoint)} of ${null===(n=i.endpoint.controller)||void 0===n?void 0:n.constructor.name}:${i.endpoint.handlerFunctionName}`):l.push(i)}this.mountedEndpointInfo=l}return this.mountedEndpointInfo}))}}},7282:function(e,t,n){var o=this&&this.__decorate||function(e,t,n,o){var i,r=arguments.length,s=r<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,n):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,o);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(r<3?i(s):r>3?i(t,n,s):i(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},i=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,o){t(n,o,e)}},s=this&&this.__awaiter||function(e,t,n,o){return new(n||(n=Promise))((function(i,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?i(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.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),v=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 o={id:"",fields:[]};let i=e.fields.filter((e=>!e.hasMany));i="get_response"===t||"query"===t?i:"create_response"===t?i.filter((e=>e.pk||e.serverValue)):"create_body"===t||"update_body"===t?i.filter((e=>{var t;return!e.serverValue&&!(null===(t=e.pk)||void 0===t?void 0:t.isAutoIncrement)||!!n&&!n.fields.find((t=>{var n;return(null===(n=t.hasMany)||void 0===n?void 0:n.column)===e.name}))})):[];const r=e.fields.filter((e=>!!e.hasMany));return o.fields.push(...i.map((e=>Object.assign(Object.assign({},e),{elementDto:e.elementDto&&("update_body"===t?(0,a.partialize)(e.elementDto):e.elementDto),isRequired:!("query"===t||"update_body"===t||"get_response"===t&&!n)&&e.isRequired}))),...r.map((n=>{var o,i,r,s;const d=CrudHttpController.getBodyDtoRecordClass(n.hasMany.relationDto,t,e);return{description:`All records of "${null===(o=n.hasMany)||void 0===o?void 0:o.relationDto.id}" table in this relationship.`,name:n.name,dataType:(null===(i=n.hasMany)||void 0===i?void 0:i.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))})}}))),o}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,v.DtoFieldValidation)(this.model,(e=>e.getBody().records))],e.params={0:{source:"raw"}},e}getManyEndpointMetadata(){const e={};return e.httpMethod=a.HttpMethod.GET,e.url=this.getMountedUrl(),e.name=CrudHttpController.prototype.getMany.name,e.displayName="getAll"+this.model.name,e.queriesValidationDto=CrudHttpController.getGetManyQueryValidator(this.modelMetadata),e.responseValidationDto=CrudHttpController.getGetManyResponseValidator(this.modelMetadata),e.accessConditions=[(0,v.DtoFieldValidation)(this.model,(e=>[e.getQuery().fields])),(0,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,v.DtoFieldValidation)(this.model,(e=>[e.getQuery().fields]),"dto_field_validation_query"),(0,v.DtoFieldValidation)(this.model,(e=>[e.getBody().update]),"dto_field_validation_body")],e.params={0:{source:"raw"}},e}deleteManyEndpoinMetadata(){const e={};return e.httpMethod=a.HttpMethod.DEL,e.url=this.getMountedUrl(),e.name=CrudHttpController.prototype.deleteMany.name,e.displayName="delete"+this.model.name,e.queriesValidationDto=CrudHttpController.getUpdateManyQueryValidator(this.modelMetadata),e.responseValidationDto=CrudHttpController.getUpdateManyResponseValidator(this.modelMetadata),e.params={0:{source:"raw"}},e.accessConditions=[(0,v.DtoFieldValidation)(this.model,(e=>[e.getQuery().fields]))],e}static getCreateManyBodyValidator(e){const t={id:"",fields:[]},n={name:"records",description:"Array of records to be created."};return n.dataType=a.DataType.ARRAY,n.isRequired=!0,n.vectorProps={elementDataType:a.DataType.OBJECT,minLength:0},n.elementDto=CrudHttpController.getBodyDtoRecordClass(e,"create_body"),t.fields.push(n),t}static getCreateManyResponseValidator(e){const t={id:"",fields:[]},n={name:"records",description:"Array of records had just been created."};return n.dataType=a.DataType.ARRAY,n.isRequired=!0,n.vectorProps={elementDataType:a.DataType.OBJECT,minLength:0},n.elementDto=CrudHttpController.getBodyDtoRecordClass(e,"create_response"),t.fields.push(n),t}static getGetManyResponseValidator(e){const t={id:"",fields:[]},n={name:"total",description:"Number of records found, zero is returned if the request is not paged."};n.dataType=a.DataType.NUMBER,n.isRequired=!0,t.fields.push(n);const o={name:"records",description:"The found records. All records will be returned if the request is not paged."};return o.dataType=a.DataType.ARRAY,o.isRequired=!0,o.vectorProps={elementDataType:a.DataType.OBJECT,minLength:0},o.elementDto=CrudHttpController.getBodyDtoRecordClass(e,"get_response"),t.fields.push(o),t}static getGetManyQueryValidator(e){const t={id:"",fields:[CrudHttpController.queryFieldDto(e)]},n={name:"search",description:"Filter records for their @Searchable denoted fields."};n.dataType=a.DataType.STRING,t.fields.push(n),t.fields.push(CrudHttpController.projectionFieldDto(e));const 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 i={id:"",fields:[]};i.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=i,t.fields.push(o);const r={name:"limit",description:"Limit the number of returning result."};r.dataType=a.DataType.NUMBER,r.rangeProps={min:1},t.fields.push(r);const s={name:"page",description:"Page the returning result, default to 1 if ommited. Has no effect if limit is not set."};return s.dataType=a.DataType.NUMBER,s.rangeProps={min:1},t.fields.push(s),t}static getUpdateManyQueryValidator(e){const t={name:"returning",description:"Whether to return the affected records by this request."};return t.dataType=a.DataType.BOOLEAN,t.isRequired=!1,{id:"",fields:[t,CrudHttpController.queryFieldDto(e)]}}static getUpdateManyBodyValidator(e){const t={id:"",fields:[]},n={name:"update",isRequired:!0,description:"The update data to apply to found records."};return n.dataType=a.DataType.OBJECT,n.elementDto=CrudHttpController.getBodyDtoRecordClass(e,"update_body"),t.fields.push(n),t}static getUpdateManyResponseValidator(e){const t={id:"",fields:[]},n={name:"modified",description:"Array of affected records."};return n.dataType=a.DataType.ARRAY,n.vectorProps={minLength:0,elementDataType:a.DataType.OBJECT},n.elementDto=n.elementDto=CrudHttpController.getBodyDtoRecordClass(e,"get_response"),t.fields.push(n),t}getEndpointMetadata(){var e,t,n,o;let i=super.getEndpointMetadata();const r=[];(null===(e=this.modelMetadata.ignoreCrud)||void 0===e?void 0:e.includes(a.HttpMethod.GET))?i=i.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))?i=i.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))?i=i.filter((e=>e.name!==CrudHttpController.prototype.updateMany.name)):r.push(this.updateManyEndpoinMetadata()),(null===(o=this.modelMetadata.ignoreCrud)||void 0===o?void 0:o.includes(a.HttpMethod.DEL))?i=i.filter((e=>e.name!==CrudHttpController.prototype.deleteMany.name)):r.push(this.deleteManyEndpoinMetadata());for(const e of r){const t=i.findIndex((t=>t.httpMethod===e.httpMethod&&t.url===e.url||t.name===e.name&&(!t.httpMethod||!t.url)));t>=0?i[t]=Object.assign(Object.assign(Object.assign({},e),i[t]),{accessConditions:[...e.accessConditions||[],...i[t].accessConditions||[]]}):i.push(e)}return i}createMany(e){return s(this,void 0,void 0,(function*(){const t=yield this.getCurrentTransaction(),n=yield this.getAuthProvider(),o=n&&(yield n.resolvePrincipal(e)),i=yield this.crudRepository.createMany({principal:o,body:e.getBody(),tx:t});return f.ResponseBuilder.json(i).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(),o=n&&(yield n.resolvePrincipal(e)),i=yield this.crudRepository.updateMany({principal:o,queries:e.getQuery(),body:e.getBody(),tx:t});return f.ResponseBuilder.json(i).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()}))}}o([(0,d.Transactional)(d.TransactionLink.INHERIT_OR_CREATE),(0,u.ApiDescription)("Create records of this table."),(0,u.AccessCondition)([]),r(0,(0,u.Raw)()),i("design:type",Function),i("design:paramtypes",[c.HttpRequest]),i("design:returntype",Promise)],CrudHttpController.prototype,"createMany",null),o([(0,u.AccessCondition)([]),(0,u.ApiDescription)("Get records of this table."),r(0,(0,u.Raw)()),i("design:type",Function),i("design:paramtypes",[c.HttpRequest]),i("design:returntype",Promise)],CrudHttpController.prototype,"getMany",null),o([(0,d.Transactional)(d.TransactionLink.INHERIT_OR_CREATE),(0,u.ApiDescription)("Find and update records which match search condition."),(0,u.AccessCondition)([]),r(0,(0,u.Raw)()),i("design:type",Function),i("design:paramtypes",[c.HttpRequest]),i("design:returntype",Promise)],CrudHttpController.prototype,"updateMany",null),o([(0,d.Transactional)(d.TransactionLink.INHERIT_OR_CREATE),(0,u.ApiDescription)("Find and remove records which match search condition."),(0,u.AccessCondition)([]),r(0,(0,u.Raw)()),i("design:type",Function),i("design:paramtypes",[c.HttpRequest]),i("design:returntype",Promise)],CrudHttpController.prototype,"deleteMany",null),t.CrudHttpController=CrudHttpController},5879:function(e,t,n){var o=this&&this.__decorate||function(e,t,n,o){var i,r=arguments.length,s=r<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,n):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,o);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(r<3?i(s):r>3?i(t,n,s):i(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},i=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,o){return new(n||(n=Promise))((function(i,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?i(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.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 v=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}})),o=yield e.endpoint.controller[e.endpointMetadata.name](...n);return e.endpointMetadata.responseValidationDto&&(o.value=(0,a.stripData)(o.value,e.endpointMetadata.responseValidationDto)),o}))}exit(){}handle(e){return r(this,void 0,void 0,(function*(){const t=e.method,n=(0,d.default)({url:e.fullPath});let o={};const i=(yield this.getMountedEndpointInfo()).find((e=>{const i=e.endpointMetadata.httpMethod===t&&(0,l.match)(e.endpointMetadata.url,{decode:decodeURIComponent})(n.pathname||"/");return!!i&&(o=i,!0)}));if(!i)throw this.logger.debug(e),a.ErrorBuilder.error(y.Errors.NOT_FOUND,"Handler not found");const r=new h.HttpRequest({method:t,headers:e.headers,pathName:n.pathname||"",hash:n.hash||"",query:c.default.parse(decodeURIComponent(n.search||"")),params:o.params,body:e.body},i.endpointMetadata);let s;try{for(const e of this.getMiddleware())if(s=yield e.intercept(r),s)break;if(s||(s=yield this.handleRequest(i,r)),!(s&&s instanceof u.HttpResponse))throw a.ErrorBuilder.systemError(`Invalid response value returned ${i.endpoint.httpMethod}:${i.endpoint.mount}, required instance of ${u.HttpResponse.name}, found ${s?null==s?void 0:s.constructor.name:s}`)}catch(e){this.logger.error(e),s=u.ResponseBuilder.json({name:e.name,message:e.message}).status([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 s}))}getMiddleware(){return[]}};v=o([(0,a.Injectable)(),i("design:paramtypes",[a.AbstractLogger,p.AbstractHttpAuthorizationProvider])],v),t.DefaultHttpRequestHandler=v},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 o=n(2318);t.Controller=e=>t=>{(0,o.getServiceProvider)().register(t,"singleton");(0,o.initObjectMetadata)(t.prototype).permissionGroup=null==e?void 0:e.permissionGroup};t.ApiDescription=e=>(t,n)=>{(0,o.initFieldMetadata)(t,n).description=e};t.Endpoint=e=>(t,n)=>{const i=(0,o.initFieldMetadata)(t,n);i.httpMethod=e.method,i.url=e.url||"/"};t.Post=e=>(n,i,r)=>(0,t.Endpoint)({method:o.HttpMethod.POST,url:e})(n,i);t.Put=e=>(n,i,r)=>(0,t.Endpoint)({method:o.HttpMethod.PUT,url:e})(n,i);t.Del=e=>(n,i,r)=>(0,t.Endpoint)({method:o.HttpMethod.DEL,url:e})(n,i);t.Get=e=>(n,i,r)=>(0,t.Endpoint)({method:o.HttpMethod.GET,url:e})(n,i);t.ApiResponse=e=>(t,n,i)=>{const r=(0,o.initFieldMetadata)(t,n);e===String?r.responseValidationDto={id:"",primitiveType:o.DataType.STRING,fields:[]}:e===Number?r.responseValidationDto={id:"",primitiveType:o.DataType.NUMBER,fields:[]}:e===Boolean?r.responseValidationDto={id:"",primitiveType:o.DataType.BOOLEAN,fields:[]}:r.responseValidationDto=(0,o.getObjectMetadata)(e)};t.OpenAccess=()=>(e,t)=>{(0,o.initFieldMetadata)(e,t).openAccess=!0};t.TfaRequired=()=>(e,t)=>{(0,o.initFieldMetadata)(e,t).tfaRequired=!0};t.AccessCondition=e=>(t,n)=>{(0,o.initFieldMetadata)(t,n).accessConditions=e};const RequestDeco=e=>(t,n,i)=>{const r=(0,o.initFieldMetadata)(t,n),s=Reflect.getMetadata("design:paramtypes",t,n)||[];switch(e){case"body":r.bodyValidationDto=(0,o.getObjectMetadata)(s[i]);break;case"params":r.paramsValidationDto=(0,o.getObjectMetadata)(s[i]);break;case"queries":r.queriesValidationDto=(0,o.getObjectMetadata)(s[i])}r.params||(r.params={}),r.params[i]={source:e,diClass:s[i]}};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,o.initFieldMetadata)(t,n).uriMapper=e};t.CurrentUser=e=>(t,n)=>{const i=(0,o.initFieldMetadata)(t,n);i.userResolver=e,i.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 o=this&&this.__decorate||function(e,t,n,o){var i,r=arguments.length,s=r<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,n):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,o);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(r<3?i(s):r>3?i(t,n,s):i(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},i=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,o){return new(n||(n=Promise))((function(i,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?i(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.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=o([(0,s.Injectable)(),i("design:paramtypes",[a.AbstractFileService])],l),t.FileUploadHandler=l},5232:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},5048:function(e,t,n){var o=this&&this.__awaiter||function(e,t,n,o){return new(n||(n=Promise))((function(i,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?i(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractRepository=void 0;const i=n(2318);t.AbstractRepository=class AbstractRepository{constructor(e){this.model=e,this.modelMetadata=(0,i.getObjectMetadata)(this.model)}beforeCreating(e,t){return o(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 o=this&&this.__awaiter||function(e,t,n,o){return new(n||(n=Promise))((function(i,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?i(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.DtoRepository=t.MultipleMap=t.SingleMap=void 0;const i=n(2318),r=n(5048),s=n(3355);t.SingleMap=(e,t,n,o,i)=>({multiple:!1,modelClass:e,forwardOps:t,forwardMapping:e=>{const t=n(e[0]||{});return t&&[t]},rootMapping:e=>{const t=e&&e[0];return o(t)},nestedMapping:i});t.MultipleMap=(e,t,n,o,i)=>({multiple:!0,modelClass:e,forwardOps:t,forwardMapping:n,rootMapping:o,nestedMapping:i});class DtoRepository extends r.AbstractRepository{constructor(e,t){super(e),this.model=e,this.dissolver=t}getMapValue(e,t,n,r,s){return o(this,void 0,void 0,(function*(){for(const o of n){const n=yield t(o);let a=r?yield r(o,o.forwardMapping(n),n):o.forwardMapping(n);if(o.nestedMapping&&a)for(const n of a)yield this.getMapValue(e,t,o.nestedMapping(n),r,s);s&&(a=yield s(o,o.forwardMapping(n),n));const d=o.rootMapping(a);(0,i.deepMerge)(e,d)}}))}createMany({principal:e,body:t,tx:n}){return o(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=>o(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)=>o(this,void 0,void 0,(function*(){if(!r)return[];const o=new s.ModelRepository(t.modelClass),d=t.forwardOps();if(t.multiple){yield o.deleteMany({ops:d,tx:n});return(yield o.createMany({principal:e,body:{records:r},tx:n})).records}{const s=r[0];if(!s)return[];if(0===a.length){return(yield o.createMany({principal:e,body:{records:r},tx:n})).records}if(1===a.length){const t=yield o.updateMany({principal:e,ops:d,body:{update:s},tx:n});return[Object.assign(Object.assign(Object.assign({},a[0]),s),t.modified[0])]}throw i.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 o(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 i.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=>o(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,i,r)=>o(this,void 0,void 0,(function*(){if(!i)return[];const o=new s.ModelRepository(t.modelClass),d=t.forwardOps(n);if(t.multiple){yield o.deleteMany({ops:d,tx:a});return(yield o.createMany({principal:e,body:{records:i},tx:a})).records}{const t=i[0];return t?0==r.length?[]:(r.length>1?(yield o.deleteMany({ops:d,tx:a}),yield o.createMany({principal:e,body:{records:[t]},tx:a})):yield o.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 o(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 i.ErrorBuilder.validationError("Missing required id field in query");const a={id:e.fields.id[0]};return yield this.getMapValue(a,(()=>o(this,void 0,void 0,(function*(){return[]}))),this.dissolver(a),(e=>o(this,void 0,void 0,(function*(){const o=new s.ModelRepository(e.modelClass);return(yield o.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 o(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 i.ErrorBuilder.validationError("Missing required id field in query");const a={id:e.fields.id[0]};return yield this.getMapValue(a,(()=>o(this,void 0,void 0,(function*(){return[]}))),this.dissolver(a),void 0,(i=>o(this,void 0,void 0,(function*(){const o=new s.ModelRepository(i.modelClass),r=i.forwardOps(t);return(yield o.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 o=this&&this.__awaiter||function(e,t,n,o){return new(n||(n=Promise))((function(i,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?i(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.ModelRepository=void 0;const i=n(2318),r=n(7756),s=n(6507),a=n(5048);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,o=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:o.length?{_and:o}:{}}}))}getUploadHandler(){return o(this,void 0,void 0,(function*(){if(void 0===this.fileUploadHandler){const e=(0,i.getServiceProvider)().getInjector();this.fileUploadHandler=e.resolveOptional(s.AbstractFileUploadHandler)||null,yield e.initInstances()}return this.fileUploadHandler}))}getRequestQueryConditionFromQuery(e,t){var n;const o=[];for(const s of(0,r.getDirectFields)(t)){const t=e[s.name];if(void 0!==t)if(s.pk||s.fk||s.isSymbol)o.push({_in:{[s.name]:t}});else if(s.enum)o.push({_in:{[s.name]:t}});else switch(s.dataType){case i.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}};o.push(e)}else o.push({_eq:{[s.name]:t}});break;case i.DataType.NUMBER:const e=new i.RangeQueryDto;Object.assign(e,t),e.min&&(e.minExclusive?o.push({_gt:{[s.name]:e.min}}):o.push({_gte:{[s.name]:e.min}})),e.max&&(e.maxExclusive?o.push({_lt:{[s.name]:e.max}}):o.push({_lte:{[s.name]:e.max}}));break;case i.DataType.BOOLEAN:o.push({_eq:{[s.name]:t}})}}return o}uriHandling(e,t){return o(this,void 0,void 0,(function*(){const n=yield this.getUploadHandler();if(!n)return;const o=t.use(this.model);for(const i of this.modelMetadata.fields)if(i.uriMapper)for(const r of e){const e=r[i.name];if(!e)continue;const s=yield i.uriMapper(t,r,e);s&&(yield n.moveFile(e,s),r[i.name]=s,yield o.updateOne(r))}}))}beforeReturning(e){var t;return o(this,void 0,void 0,(function*(){const n=yield this.getUploadHandler();for(const o of e)for(const e of this.modelMetadata.fields)if(e.uriMapper&&n){if(!o[e.name])continue;o[e.name]=(null===(t=e.mimeProps)||void 0===t?void 0:t.public)?yield n.resolvePublicUrl(o[e.name]):yield n.resolvePrivateUrl(o[e.name])}}))}createMany({principal:e,body:t,tx:n}){var s;return o(this,void 0,void 0,(function*(){const o=t.records;if(!o.length)return{records:[]};const a=(0,r.getDirectFields)(this.modelMetadata),d=this.modelMetadata.fields.filter((e=>!!e.hasMany));t.records=o.map((e=>a.reduce(((t,n)=>Object.assign(t,void 0!==e[n.name]?{[n.name]:e[n.name]}:{})),{}))),yield this.beforeCreating(e,t.records);let l=t.records.length?yield n.use(this.model).createMany(t.records):[];yield this.uriHandling(l,n),yield this.beforeReturning(l);const c=this.modelMetadata.fields.filter((e=>e.pk||e.serverValue||e.mimeProps)).map((e=>e.name));l=this.project(l,c);for(const r of d){const a=l.flatMap(((e,t)=>{var n;const i=o[t][r.name];return i?((null===(n=r.hasMany)||void 0===n?void 0:n.single)?[i]:i).map((t=>Object.assign(Object.assign({},t),{[r.hasMany.column]:e.id}))):[]}));if(a.length){const o=new ModelRepository((0,i.getModelById)(r.hasMany.relationDto.id));t.records=a;const d=yield o.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<l.length;e++){const t=[];for(let n=0;n<a.length;n++)a[n][r.hasMany.column]===l[e].id&&t.push(d.records[e]);l[e]=Object.assign(Object.assign({},l[e]),{[r.name]:(null===(s=r.hasMany)||void 0===s?void 0:s.single)?t[0]:t})}}}return{records:l}}))}updateMany({principal:e,ops:t,queries:n,body:s,tx:a}){var d,l;return o(this,void 0,void 0,(function*(){const o=t||[],c=this.modelMetadata.fields.filter((e=>!!e.hasMany)),u=(0,r.getDirectFields)(this.modelMetadata).filter((e=>void 0!==s.update[e.name])),h=u.reduce(((e,t)=>Object.assign(e,{[t.name]:s.update[t.name]})),{});if(null==n?void 0:n.fields){const e=this.getRequestQueryConditionFromQuery(n.fields,this.modelMetadata);e.length&&o.push(...e)}const p=o.length?{_and:[...o]}:{},f=this.getNestedQueries(n);let y=[];if(f.length){const e=yield a.use(this.model).getMany(p,{projection:["id"]},f);y=e.records.map((e=>e.id)),y.length&&u.length&&(yield a.use(this.model).updateMany({_in:{id:y}},h,!1))}else if(u.length)y=yield a.use(this.model).updateMany(p,h,!0);else{const e=yield a.use(this.model).getMany(p,{projection:["id"]});y=e.records.map((e=>e.id))}let v=y.map((e=>Object.assign(Object.assign({},h),{id:e})));yield this.uriHandling(v,a),yield this.beforeReturning(v);for(const t of c){const n=s.update[t.name];if(void 0===n||!y.length)continue;if(y.length>1)throw i.ErrorBuilder.systemError(`Multiple records found while updating @HasMany field: ${t.name}`);const o=v.find((e=>e.id===y[0])),r=(0,i.getModelById)(t.hasMany.relationDto.id),c=a.use(r),u=(yield c.getRecords({_eq:{[t.hasMany.column]:o.id}},{limit:(null===(d=t.hasMany)||void 0===d?void 0:d.single)?1:void 0})).map((e=>e.id)),h=n.map((e=>e.id)).filter((e=>!!e)),p=u.filter((e=>!h.includes(e))),f=n.filter((e=>!e.id)).map((e=>Object.assign(Object.assign({},e),{[t.hasMany.column]:o.id}))),g=n.filter((e=>!!e.id));yield c.deleteMany({_in:{id:p}});const m=new ModelRepository(r),b=yield m.createMany({principal:e,body:{records:f},tx:a}),M=f.map(((e,t)=>Object.assign(Object.assign({},e),b.records[t]))).concat(g);o[t.name]=(null===(l=t.hasMany)||void 0===l?void 0:l.single)?M[0]:M}let g=["id"];return(null==n?void 0:n.returning)&&(g=[...g,...Object.keys(s.update).filter((e=>void 0!==s.update[e]))]),{modified:this.project(v,g)}}))}getMany({queries:e,ops:t,queryProvider:n}){var r;return o(this,void 0,void 0,(function*(){const o=t||[];if((null==e?void 0:e.fields)&&o.push(...this.getRequestQueryConditionFromQuery(e.fields,this.modelMetadata)),console.log("conditio here",o,e),null==e?void 0:e.search){const t=this.modelMetadata.fields.filter((e=>e.searchable)).map((t=>({_iusub:{[t.name]:e.search}})));t.length&&o.push({_or:t})}const s=yield n.use(this.model).getMany(o.length?{_and:o}:{},{limit:(null==e?void 0:e.limit)||void 0,page:null==e?void 0:e.page,projection:null==e?void 0:e.projection,order:null===(r=null==e?void 0:e.order)||void 0===r?void 0:r.map((e=>{const t=Object.keys(e).find((t=>!!e[t]));return[t,e[t]]}))},this.getNestedQueries(e)),a=s.records.map((e=>e.id));for(const t of this.modelMetadata.fields){if(!t.hasMany||(null==e?void 0:e.projection)&&!e.projection.includes(t.name))continue;const o=(0,i.getModelById)(t.hasMany.relationDto.id),r=new ModelRepository(o),d=a.length?yield r.getMany({queries:{fields:{[t.hasMany.column]:a},limit:t.hasMany.single?1:0},queryProvider:n}):{records:[]};for(const e of s.records){const n=d.records.filter((n=>n[t.hasMany.column]===e.id));e[t.name]=t.hasMany.single?n[0]:n}}return yield this.beforeReturning(s.records),{total:s.total,records:this.project(s.records,null==e?void 0:e.projection)}}))}deleteMany({queries:e,ops:t,tx:n}){return o(this,void 0,void 0,(function*(){let o=t||[];if(null==e?void 0:e.fields){const t=this.getRequestQueryConditionFromQuery(e.fields,this.modelMetadata);t.length&&o.push(...t)}const i=o.length?{_and:[...o,...t||[]]}:{},r=this.getNestedQueries(e);let s=[];if(r.length){const e=yield n.use(this.model).getRecords(i,{},r);yield n.use(this.model).deleteMany({_in:{id:e.map((e=>e.id))}}),s=e}else s=yield n.use(this.model).deleteMany(i,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 o=this&&this.__decorate||function(e,t,n,o){var i,r=arguments.length,s=r<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,n):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,o);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(r<3?i(s):r>3?i(t,n,s):i(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__awaiter||function(e,t,n,o){return new(n||(n=Promise))((function(i,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?i(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.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 i(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 i(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=o([(0,r.Register)()],a),a}},1071:function(e,t,n){var o=this&&this.__decorate||function(e,t,n,o){var i,r=arguments.length,s=r<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,n):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,o);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(r<3?i(s):r>3?i(t,n,s):i(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__awaiter||function(e,t,n,o){return new(n||(n=Promise))((function(i,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?i(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.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 i(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 i(this,void 0,void 0,(function*(){return!!e&&e.every((e=>t.includes(e)))}))}};return n=o([(0,r.Register)()],n),n}},3198:function(e,t,n){var o=this&&this.__decorate||function(e,t,n,o){var i,r=arguments.length,s=r<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,n):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,o);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(r<3?i(s):r>3?i(t,n,s):i(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__awaiter||function(e,t,n,o){return new(n||(n=Promise))((function(i,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?i(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.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 i(this,void 0,void 0,(function*(){let t=e.getQuery().limit;return t&&(t=parseInt(t)),t||0}))}validate(e,t){return i(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=o([(0,r.Register)()],a),t.MaximumQueryLimit=a},341:function(e,t,n){var o=this&&this.__createBinding||(Object.create?function(e,t,n,o){void 0===o&&(o=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,o,i)}:function(e,t,n,o){void 0===o&&(o=n),e[o]=t[n]}),i=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||o(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),i(n(9025),t),i(n(4638),t),i(n(1820),t),i(n(1870),t),i(n(4972),t),i(n(8903),t),i(n(2417),t),i(n(1532),t),i(n(5879),t),i(n(6004),t),i(n(7282),t),i(n(4435),t),i(n(767),t),i(n(225),t),i(n(2255),t),i(n(1071),t),i(n(3198),t),i(n(4192),t),i(n(859),t),i(n(2085),t),i(n(531),t),i(n(7825),t),i(n(9837),t),i(n(3355),t),i(n(9073),t),i(n(8023),t),i(n(5048),t),i(n(5530),t),i(n(2841),t),i(n(7152),t),i(n(8577),t),i(n(2665),t),i(n(9990),t),i(n(6507),t),i(n(4839),t),i(n(5232),t),i(n(5572),t),i(n(889),t),i(n(5537),t),i(n(226),t),i(n(8836),t),i(n(9627),t),i(n(6721),t),i(n(204),t),i(n(7577),t),i(n(8709),t),i(n(1556),t),i(n(2363),t),i(n(4683),t),i(n(3346),t),i(n(9527),t),i(n(3581),t),i(n(3376),t),i(n(8104),t),i(n(5033),t)},4683:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractJobController=void 0;const o=n(2318);t.AbstractJobController=class AbstractJobController{getAllJobs(){const e=(0,o.getObjectMetadata)(this.constructor);return(null==e?void 0:e.jobs)||[]}}},3346:function(e,t,n){var o=this&&this.__awaiter||function(e,t,n,o){return new(n||(n=Promise))((function(i,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?i(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractJobExecutor=void 0;const i=n(2318),r=n(4683);t.AbstractJobExecutor=class AbstractJobExecutor{constructor(){this._allJobs=null}init(){return o(this,void 0,void 0,(function*(){}))}getAllJobs(){return o(this,void 0,void 0,(function*(){if(!this._allJobs){const e=(0,i.getServiceProvider)().getInjector(),t=e.resolveMultiple(r.AbstractJobController);yield e.initInstances(),this._allJobs=t.map((e=>e.getAllJobs().map((t=>({jobName:t.jobName,handlerFn:e[t.handlerName].bind(e)}))))).reduce(((e,t)=>e.concat(t)),[])}return this._allJobs}))}}},9527:function(e,t,n){var o=this&&this.__awaiter||function(e,t,n,o){return new(n||(n=Promise))((function(i,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?i(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractJobScheduler=void 0;const i=n(2318),r=n(4683);t.AbstractJobScheduler=class AbstractJobScheduler{constructor(e){this.logger=e}schedule(){return o(this,void 0,void 0,(function*(){const e=(0,i.getServiceProvider)().getInjector(),t=e.resolveMultiple(r.AbstractJobController);yield e.initInstances();const n=t.map((e=>e.getAllJobs())).reduce(((e,t)=>e.concat(t)),[]).filter((e=>e.interval||e.cron));for(const e of n)this.logger.debug(`Scheduling: ${e.jobName}, at: ${e.cron||e.interval}`),this.scheduleJob({jobName:e.jobName,cron:e.cron,interval:e.interval}),this.logger.debug(`Job scheduled: ${e.jobName}`)}))}}},3581:function(e,t,n){var o=this&&this.__awaiter||function(e,t,n,o){return new(n||(n=Promise))((function(i,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?i(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AwsJobExecutor=void 0;const i=n(3346);class AwsJobExecutor extends i.AbstractJobExecutor{constructor(e){super(),this.logger=e}executeJob(e,t){return o(this,void 0,void 0,(function*(){(yield this.getAllJobs()).find((t=>t.jobName===e.jobName))?e.interval||e.cron:this.logger.error(`Job not found: ${e.jobName}`)}))}}t.AwsJobExecutor=AwsJobExecutor},3376:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AwsJobScheduler=void 0;const o=n(9527);class AwsJobScheduler extends o.AbstractJobScheduler{scheduleJob(e){}}t.AwsJobScheduler=AwsJobScheduler},8104:function(e,t,n){var o=this&&this.__awaiter||function(e,t,n,o){return new(n||(n=Promise))((function(i,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?i(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.LocalJobExecutor=void 0;const i=n(3346);class LocalJobExecutor extends i.AbstractJobExecutor{constructor(e){super(),this.logger=e}executeJob(e,t){return o(this,void 0,void 0,(function*(){const t=(yield this.getAllJobs()).find((t=>t.jobName===e.jobName));t?yield t.handlerFn(e):this.logger.error(`Job not found: ${e.jobName}`)}))}}t.LocalJobExecutor=LocalJobExecutor},5033:function(e,t,n){var o=this&&this.__decorate||function(e,t,n,o){var i,r=arguments.length,s=r<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,n):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,o);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(r<3?i(s):r>3?i(t,n,s):i(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},i=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,o){return new(n||(n=Promise))((function(i,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?i(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.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(8311)),l=s(n(1495)),c=s(n(9896)),u=n(3346),h=n(9527);let p=class LocalJobScheduler extends h.AbstractJobScheduler{constructor(e,t,n,o,i,r=30){super(e),this.logger=e,this.jobExecutor=t,this.redisServerUrl=n,this.lockMutexKey=o,this.holdMutexKey=i,this.keyRetentionDurationSecond=r,this.intervals=[]}init(){return r(this,void 0,void 0,(function*(){this.logger.debug("LocalJobScheduler init")}))}exit(){var e;this.mutexHoldInterval&&clearInterval(this.mutexHoldInterval),null===(e=this.redisClient)||void 0===e||e.quit();for(const e of this.intervals)clearInterval(e);this.logger.debug("LocalJobScheduler exit")}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"))}))}schedule(){const e=Object.create(null,{schedule:{get:()=>super.schedule}});return r(this,void 0,void 0,(function*(){this.redisClient||(this.redisClient=new l.default(this.redisServerUrl));if(yield this.redisClient.exists(this.holdMutexKey))return void this.logger.info("Scheduler is active, ignore");const t=new c.default([this.redisClient]);try{const n=yield t.acquire([this.lockMutexKey],this.keyRetentionDurationSecond);yield e.schedule.call(this),yield this.extendMutexKey(),yield n.release(),this.logger.debug("Schedule finished"),this.mutexHoldInterval=setInterval((()=>{this.extendMutexKey()}),Math.trunc(1e3*this.keyRetentionDurationSecond/2)+1)}catch(e){console.log(e),this.logger.info("Failed to lock mutex key, ignore")}}))}scheduleJob(e){if(e.interval){const t=setInterval((()=>this.jobExecutor.executeJob(e,0)),1e3*e.interval);this.intervals.push(t)}else if(e.cron){if(!d.default.validate(e.cron))throw a.ErrorBuilder.systemError(`Invalid cron job expression for job ${e.jobName}: ${e.cron}`);d.default.schedule(e.cron,(()=>this.jobExecutor.executeJob(e,0)))}}};p=o([(0,a.Initable)(),i("design:paramtypes",[a.AbstractLogger,u.AbstractJobExecutor,String,String,String,Number])],p),t.LocalJobScheduler=p},1556:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CustomJob=t.CronJob=t.IntervalJob=void 0;const o=n(2318);t.IntervalJob=(e,t)=>(n,i)=>{const r=(0,o.initObjectMetadata)(n);r.jobs||(r.jobs=[]),r.jobs.push({jobName:e,interval:t,handlerName:i})};t.CronJob=(e,t)=>(n,i)=>{const r=(0,o.initObjectMetadata)(n);r.jobs||(r.jobs=[]),r.jobs.push({jobName:e,cron:t,handlerName:i})};t.CustomJob=e=>(t,n)=>{const i=(0,o.initObjectMetadata)(t);i.jobs||(i.jobs=[]),i.jobs.push({jobName:e,handlerName:n})}},2363:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},5572:function(e,t,n){var o,i=this&&this.__decorate||function(e,t,n,o){var i,r=arguments.length,s=r<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,n):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,o);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(r<3?i(s):r>3?i(t,n,s):i(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,o){return new(n||(n=Promise))((function(i,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?i(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.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=o=class FileLogMedium{constructor(e){const t=e.separated?o.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[o.levels.indexOf(e)]:0;d.default.appendFileSync(n,t)}};u.levels=Object.values(c.LogLevel),u=o=i([(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 o=this&&this.__awaiter||function(e,t,n,o){return new(n||(n=Promise))((function(i,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?i(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractService=void 0;const i=n(7756);t.AbstractService=class AbstractService{constructor(e){this.databaseAdapter=e}createTransaction(){return this.databaseAdapter.createTransaction()}getCurrentTransaction(){return o(this,void 0,void 0,(function*(){return(0,i.getTransactionFromContext)(this)}))}}},6862:(e,t,n)=>{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){t?this.socketInfo.channels.find((e=>e.name===t&&e.serverToClientAllowed))&&this.sendRaw({type:o.MessageType.PLAIN,data:{message:e,channel:t}}):this.sendRaw({type:o.MessageType.PLAIN,data:{message:e}})}sendRaw(e){this.physicSend(e)}disconnect(e){this.physicClose(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 o=this&&this.__decorate||function(e,t,n,o){var i,r=arguments.length,s=r<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,n):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,o);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(r<3?i(s):r>3?i(t,n,s):i(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__awaiter||function(e,t,n,o){return new(n||(n=Promise))((function(i,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?i(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.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 i(this,void 0,void 0,(function*(){return e.getHeaders()["x-socket-action"]===p}))}validate(e){return i(this,void 0,void 0,(function*(){return!!e}))}getConditionMetadata(){return{name:"socket_read",description:"Can receive message from channel",valueType:s.AccessConditionValueType.BOOLEAN}}};y=o([(0,s.Register)()],y);let v=class SocketWriteCondition extends c.AbstractAccessCondition{resolveConditionValue(e){return i(this,void 0,void 0,(function*(){return e.getHeaders()["x-socket-action"]===f}))}validate(e){return i(this,void 0,void 0,(function*(){return!!e}))}getConditionMetadata(){return{name:"socket_write",description:"Can send message to channel",valueType:s.AccessConditionValueType.BOOLEAN}}};v=o([(0,s.Register)()],v);t.AbstractServerSocketManager=class AbstractServerSocketManager{constructor(e,t,n,o,i){this.requireAuthentication=e,this.logger=t,this.redisServerUrl=n,this.authProvider=o,this.authResolver=i,this._connectionHandler=null,this.redisClient=new a.default(this.redisServerUrl)}getUniqueChannelPrefix(){return"CHANNEL:"}getConnectionHandler(){return i(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 i(this,void 0,void 0,(function*(){return(yield this.redisClient.smembers(this.getUniqueChannelName(e)))||[]}))}addSocketToChannel(e,t){return i(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){return i(this,void 0,void 0,(function*(){const n=yield this.getById(e);n&&(n.removeChannels(t),yield Promise.all(t.map((t=>this.redisClient.srem(this.getUniqueChannelName(t),e)))),yield n.saveSocketInfo())}))}handle(e){var t;return i(this,void 0,void 0,(function*(){const n=yield this.getConnectionHandler();switch(e.method){case s.SocketMethod.CONNECT:{this.logger.debug("Socket connection attempt",e);const o=this.authResolver(null===(t=e.data)||void 0===t?void 0:t.queries),i=yield this.authProvider.getPrincipalResolver().resolvePrincipal(o);if(!i&&this.requireAuthentication)throw s.ErrorBuilder.error(s.Errors.AUTHENTICATION_ERROR);const r=yield this.addSocket({id:e.socketId,authInfo:i,channels:[],createdAt:Date.now()},e.data);if(!r)throw s.ErrorBuilder.error(s.Errors.SYSTEM_ERROR,"Socket not found after create: "+e.socketId);r.sendRaw({type:s.MessageType.READY,data:void 0}),null==n||n.onSocketConnect(r);break}case s.SocketMethod.DISCONNECT:{this.logger.debug("Socket disconnect",e);const t=yield this.getById(e.socketId);if(t){const o=yield this.getMountedEndpointInfo();for(const n of t.getChannelsInfo()){const i=o.find((e=>e.endpointMetadata.url===n.name));i&&i.endpoint.controller.onChannelLeave(t),yield this.removeSocketFromChannel(e.socketId,t.getChannelsInfo().map((e=>e.name)))}null==n||n.onSocketDisconnect(t)}break}case s.SocketMethod.MESSAGE:{this.logger.debug("Socket message",e);const t=e.data;let o=yield this.getById(e.socketId);if(o)switch(t.type){case s.MessageType.PING_PONG:null==o||o.sendRaw({type:s.MessageType.PING_PONG,data:t.data});break;case s.MessageType.CHANNEL_JOIN:{const e=t.data,n=[],i=[];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(o.getAuthInfo(),e,a),r=!0}catch(e){}try{const n=new u.HttpRequest({method:s.SocketMethod.MESSAGE,pathName:t,headers:{[h]:f}},a.endpointMetadata);yield this.authProvider.authorize(o.getAuthInfo(),n,a),e=!0}catch(e){}(e||r)&&(this.logger.debug("Adding channel info",t,e,r),n.push({name:t,clientToServerAllowed:e,serverToClientAllowed:r}),i.push(a))}}if(o=yield this.addSocketToChannel(o.getId(),n),o){o.sendRaw({type:s.MessageType.CHANNEL_JOIN,data:n.map((e=>e.name))});for(const e of i)e.endpoint.controller.onChannelJoin(o)}else this.logger.debug("Socket not found after addSocketToChannel")}break;case s.MessageType.CHANNEL_LEAVE:{const e=t.data;for(const t of e){const e=(yield this.getMountedEndpointInfo()).find((e=>e.endpointMetadata.url===t));e&&e.endpoint.controller.onChannelLeave(o)}yield this.removeSocketFromChannel(o.getId(),e)}break;case s.MessageType.PLAIN:{const e=t.data.channel,i=t.data.message;if(e){if(o.getChannelsInfo().find((t=>t.name===e&&t.clientToServerAllowed))){const t=(yield this.getMountedEndpointInfo()).find((t=>t.endpointMetadata.url===e));if(t){!1!==t.endpoint.controller.onMessage(o,i)&&(this.logger.debug("broadcasting to channel",e,i),this.broadcastToChannel(e,i))}}}else null==n||n.onMessage(o,i)}break;default:this.logger.debug("Invalid message format",t)}else this.logger.debug("Socket not found",e.socketId);break}default:return}}))}getMountedEndpointInfo(){return i(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,v]}})))}return this.mountedEndpointInfo}))}}},9990:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractSocketConnectionHandler=void 0;t.AbstractSocketConnectionHandler=class AbstractSocketConnectionHandler{}},2665:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractSocketController=void 0;t.AbstractSocketController=class AbstractSocketController{constructor(e){this.channel=e}onChannelJoin(e){}onChannelLeave(e){}onMessage(e,t){}}},7152:function(e,t,n){var o=this&&this.__decorate||function(e,t,n,o){var i,r=arguments.length,s=r<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,n):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,o);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(r<3?i(s):r>3?i(t,n,s):i(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},i=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,o){return new(n||(n=Promise))((function(i,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?i(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.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,o,i,r){super(n),this.socketManager=e,this.logger=t,this.socketInfo=n,this.apiGateway=o,this.socketNamespace=i,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){this.socketManager.physicSend(this.getId(),e).catch((e=>this.logger.debug("Socket send error",e)))}physicClose(e){e&&this.physicSend(e),this.socketManager.removeSocketFromRedis(this.getId()).catch((e=>this.logger.debug("Socket close error",e))),this.socketManager.removeSocket(this.getId()).catch((e=>this.logger.debug("Socket remove error",e)))}serialize(){return JSON.stringify(this.socketInfo)}}let p=class AwsSocketManager extends c.AbstractServerSocketManager{constructor(e,t,n,o,i,r,s,a){super(e,a,o,r,s),this.authenticationRequired=e,this.region=t,this.socketDomainUrl=n,this.redisServerUrl=o,this.httpRequestHandler=i,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)}))}getSocketInfoHashKey(){return"__SOCKET_INFO__"}physicSend(e,t){return r(this,void 0,void 0,(function*(){try{yield this.apiGatewayManagement.postToConnection({ConnectionId:e,Data:JSON.stringify(t)}).promise(),this.logger.debug(`Socket ${e} send OK`,t)}catch(t){if(this.logger.debug(`Socket ${e} post error`,t),410===t.statusCode){this.logger.debug(`Disconnect & remove stale socket ${e}`);const t=yield this.getById(e);t&&this.removeSocketFromChannel(e,t.getChannelsInfo().map((e=>e.name))).catch((e=>this.logger.error("Cannot remove socket from channels",e))),this.removeSocketFromRedis(e).catch((e=>this.logger.error("Cannot remove socket from redis",e))),this.logger.debug(`Socket removed ${e}`)}throw 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 o=this.formatBroadcastData(e,t);n.map((e=>this.physicSend(e,o).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){return r(this,void 0,void 0,(function*(){yield this.apiGatewayManagement.deleteConnection({ConnectionId:e}).promise()}))}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=o([(0,a.Initable)(),i("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 o=this&&this.__decorate||function(e,t,n,o){var i,r=arguments.length,s=r<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,n):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,o);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(r<3?i(s):r>3?i(t,n,s):i(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},i=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,o){return new(n||(n=Promise))((function(i,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?i(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.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){this.redisClient.publish(this.socketChannelName,JSON.stringify({type:f.SEND,data:e}))}physicClose(){this.redisClient.publish(this.socketChannelName,JSON.stringify({type:f.CLOSE}))}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){super(t),this.socket=e,this.socketInfo=t,this.infoSaver=n}saveSocketInfo(){return r(this,void 0,void 0,(function*(){yield this.infoSaver(this.socketInfo)}))}physicSend(e){this.socket.send(JSON.stringify(e))}physicClose(e){this.socket.close(1e3,e&&JSON.stringify(e))}}let y=class LocalSocketManager extends u.AbstractServerSocketManager{constructor(e,t,n,o,i){super(e,n,t,o,i),this.authenticationRequired=e,this.redisServerUrl=t,this.logger=n,this.authProvider=o,this.authResolver=i,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),o=this.allSockets.find((e=>e.getId()===n));if(o){const t=JSON.parse(e);switch(t.type){case f.SEND:o.physicSend(t.data);break;case f.SAVE:o.socketInfo.channels=t.data,o.saveSocketInfo();break;case f.CLOSE:o.disconnect();break;default:this.logger.debug("Invalid remote command",t)}}}getUniqueDataChannelName(e){return`CHANNEL_DATA:${e}`}getSocketChannelKeyPrefix(){return"SOCKET_CHANNEL:"}getSocketInfoHashKey(){return"__SOCKET_INFO__"}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 o=yield n.addSocketToChannel.call(this,e,t),i=t.map((e=>e.name)).filter((e=>!this.subscribedChannels.includes(e)));return i.length&&(yield Promise.all(i.map((e=>this.channelSubClient.subscribe(this.getUniqueDataChannelName(e))))),this.subscribedChannels.push(...i)),o}))}removeSocketFromChannel(e,t){const n=Object.create(null,{removeSocketFromChannel:{get:()=>super.removeSocketFromChannel}});return r(this,void 0,void 0,(function*(){yield n.removeSocketFromChannel.call(this,e,t),yield Promise.all(t.map((e=>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(t,e,(e=>r(this,void 0,void 0,(function*(){yield this.redisClient.hset(this.getSocketInfoHashKey(),e.id,JSON.stringify(e))})))),o=this.getSocketChannelKey(e.id);return this.subClient.subscribe(o),this.allSockets.push(n),n}))}removeSocket(e){return r(this,void 0,void 0,(function*(){yield this.redisClient.hdel(this.getSocketInfoHashKey(),e);const t=this.getSocketChannelKey(e);this.subClient.unsubscribe(t),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"],o=(0,l.default)({url:t.url}),i=c.default.parse(decodeURIComponent(o.search||""));this.handle({method:a.SocketMethod.CONNECT,socketId:n,data:{queries:i,socket:e}}).catch((t=>{e.close(1e3,`${t.name}:${t.message}`)})),e.onmessage=e=>{this.handle({method:a.SocketMethod.MESSAGE,socketId:n,data:e.data&&JSON.parse(e.data)}).catch((e=>{this.logger.error(e)}))},e.onclose=()=>{this.handle({method:a.SocketMethod.DISCONNECT,socketId:n}).catch((e=>{this.logger.error(e)}))}}))}};y=o([(0,a.Initable)(),i("design:paramtypes",[Boolean,String,a.AbstractLogger,p.AbstractHttpAuthorizationProvider,Function])],y),t.LocalSocketManager=y},5537:function(e,t,n){var o=this&&this.__awaiter||function(e,t,n,o){return new(n||(n=Promise))((function(i,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?i(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.ClaireServer=void 0;const i=n(2318),r=n(137),s=n(4972);class ClaireServer extends i.ClaireApp{constructor(e,t,n){super(),this.logger=e,this.httpRequestHandler=t,this.socketManager=n,this.booted=!1}init(){return o(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,i.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 o=this&&this.__awaiter||function(e,t,n,o){return new(n||(n=Promise))((function(i,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?i(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))},i=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=i(n(6860)),a=i(n(3685)),d=i(n(3582)),l=i(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 o(this,void 0,void 0,(function*(){yield this.server.init(),yield this.injector.initInstances();const i=(0,s.default)(),c=a.default.createServer(i);return null===(t=this.socketManager)||void 0===t||t.configure(c),i.use((0,d.default)()),i.use(s.default.raw({limit:1024*((null===(n=this.config)||void 0===n?void 0:n.maxBodySizeKB)||4096)})),i.use((0,l.default)()),i.use(((e,t,n)=>{e.files&&(e.body||(e.body={}),Object.keys(e.files).forEach((t=>{e.body[t]=e.files[t]}))),n()})),i.use(s.default.urlencoded({extended:!1})),i.use(s.default.json()),i.all("*",((e,t)=>{(()=>o(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,o=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:o}}yield this.socketManager.handle(n).then((()=>{t.status(200).send()})).catch((e=>{var t;this.logger.debug("Handle error",e),null===(t=this.socketManager)||void 0===t||t.removeSocket(n.socketId).catch((e=>{this.logger.debug(e)}))}))}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},o=yield this.httpRequestHandler.handle(n);o.headers&&Object.keys(o.headers).forEach((e=>{t.set(e,o.headers[e])})),t.status(o.code).send(o.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 o=this&&this.__awaiter||function(e,t,n,o){return new(n||(n=Promise))((function(i,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?i(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.LambdaWrapper=void 0;const i=n(2318),r=n(767),s=n(5530),a=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,i.getServiceProvider)().getInjector(),this.socketManager=this.injector.resolveOptional(s.AbstractServerSocketManager),this.httpRequestHandler=this.injector.resolveOptional(r.AbstractHttpRequestHandler)}bootServer(){var e;return o(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){return o(this,void 0,void 0,(function*(){yield this.bootServer();const t=this.requestMapper(e);if(!t)return toApiGatewayFormat(400,"Cannot resolve event");if(t.method===i.HttpMethod.OPTIONS)return toApiGatewayFormat(200);try{if(Object.values(i.HttpMethod).includes(t.method)){if(!this.httpRequestHandler)throw i.ErrorBuilder.error(a.Errors.SYSTEM_ERROR,"Http request handler not found");const e={fullPath:t.rawPath,method:t.method,headers:t.headers,body:t.body},n=yield this.httpRequestHandler.handle(e);return toApiGatewayFormat(n.code,n.value)}if(!Object.values(i.SocketMethod).includes(t.method))throw i.ErrorBuilder.error(a.Errors.HTTP_REQUEST_ERROR,"Not allow request method: "+t.method);{if(!this.socketManager)throw i.ErrorBuilder.error(a.Errors.SYSTEM_ERROR,"Socket manager not found");const e={socketId:t.rawPath,method:t.method,data:t.body};yield this.socketManager.handle(e)}return toApiGatewayFormat(200)}catch(e){return toApiGatewayFormat(400,{name:e.name,message:e.message})}}))}}},9627:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},6721:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Errors=void 0;const o=n(2318);t.Errors=Object.assign(Object.assign({},o.Errors),{TFA_REQUIRED:"TFA_REQUIRED"})},889:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.lambdaRequestMapper=void 0;const o=n(2318);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===o.SocketMethod.CONNECT?{queries:e.queryStringParameters}:n}}return{method:e.requestContext.http.method.toLowerCase(),rawPath:`${e.rawPath}?${e.rawQueryString}`,body:e.body&&JSON.parse(e.body),headers:e.headers}}},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")},8311:e=>{e.exports=require("node-cron")},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")}},t={};var n=function __webpack_require__(n){var o=t[n];if(void 0!==o)return o.exports;var i=t[n]={exports:{}};return e[n].call(i.exports,i,i.exports,__webpack_require__),i.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 n=t();for(var o in n)("object"==typeof exports?exports:e)[o]=n[o]}}(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 o=this&&this.__awaiter||function(e,t,n,o){return new(n||(n=Promise))((function(i,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?i(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractRbacAuthProvider=void 0;const i=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 o(this,void 0,void 0,(function*(){if(n.endpointMetadata.openAccess)return;const o=yield this.getRbacCache();if(!o)throw i.ErrorBuilder.error(i.Errors.SYSTEM_ERROR,"Cannot read rbac cache");let r=[];if(e){const t=yield this.getRolesOfPrincipal(e);r=(o.roles||[]).filter((e=>!!t.find((t=>t===e.roleId))))}else r=(o.roles||[]).filter((e=>e.isAnonymousRole));if(!r.length)throw i.ErrorBuilder.error(i.Errors.ACCESS_DENIED,"No role attached");if(r.find((e=>e.isSuperRole)))return;const a=(o.rolePolicies||[]).filter((e=>!!r.find((t=>t.roleId===e.roleId)))),d=(o.policies||[]).filter((e=>!!a.find((t=>t.policyId===e.policyId)))),l=(o.policyPermissions||[]).filter((e=>!!d.find((t=>t.policyId===e.policyId)))),c=(o.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 i.ErrorBuilder.error(i.Errors.ACCESS_DENIED,`Not permitted: ${(0,s.getEndpointId)(n.endpoint)}`);let h=!1;for(const e of u){const o=c.filter((t=>t.policyPermissionId===e.id));if(o.length){let e=!0;const r=(0,i.getServiceProvider)().getInjector(),s=(n.endpointMetadata.accessConditions||[]).map((e=>r.resolve(e)));yield r.initInstances();for(const n of o){const o=s.find((e=>e.getConditionMetadata().name===n.conditionName));if(!o)continue;const i=yield o.resolveConditionValue(t),r=JSON.parse(n.conditionValue);if(e=yield o.validate(i,r),!e){this.logger.debug("Condition check failed: condition, requested, permitted",n.conditionName,i,r);break}}h=e}else h=!0;if(h)break}if(!h)throw i.ErrorBuilder.error(i.Errors.ACCESS_DENIED,"Condition check failed")}))}}t.AbstractRbacAuthProvider=AbstractRbacAuthProvider},531:function(e,t,n){var o=this&&this.__awaiter||function(e,t,n,o){return new(n||(n=Promise))((function(i,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?i(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.RedisRbacAuthProvider=void 0;const i=n(2085);class RedisRbacAuthProvider extends i.AbstractRbacAuthProvider{constructor(e,t,n,o,i,r,s,a=3e4){super(o,i,s),this.serviceId=e,this.rbacChannel=t,this.principalChannel=n,this.authDataResolver=o,this.principalResolver=i,this.cacheService=r,this.logger=s,this.redisDataRetentionDurationMs=a,this.lastRbacFetchTimestamp=0,this.principalCache={}}getRbacCache(){return o(this,void 0,void 0,(function*(){if(this.lastRbacFetchTimestamp+this.redisDataRetentionDurationMs<Date.now()){const e=yield this.cacheService.hget(this.rbacChannel,this.serviceId);this.rbacCache=e,this.lastRbacFetchTimestamp=Date.now()}return this.rbacCache}))}getRolesOfPrincipal(e){return o(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),o=e?"string"==typeof e?JSON.parse(e):e:[];n={lastFetchTimestamp:Date.now(),roles:o},this.principalCache[t]=n}return n.roles}))}}t.RedisRbacAuthProvider=RedisRbacAuthProvider},7825:function(e,t,n){var o=this&&this.__decorate||function(e,t,n,o){var i,r=arguments.length,s=r<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,n):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,o);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(r<3?i(s):r>3?i(t,n,s):i(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},i=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,o){return new(n||(n=Promise))((function(i,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?i(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.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,o,i,r){super(n,o,i),this.rbacCacheChannel=e,this.principalCacheChannel=t,this.authDataResolver=n,this.principalResolver=o,this.logger=i,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,o=this.idResolvers.find((e=>e.principalId===t));if(o){for(const e of o.resolvers)e(n);o.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 o=this.idResolvers.find((t=>t.principalId===e.id));o||(o={principalId:e.id,resolvers:[]},this.idResolvers.push(o)),o.resolvers.length||null===(n=this.socket)||void 0===n||n.send(e.id,this.principalCacheChannel),o.resolvers.push(t)}))}))}};l=o([(0,s.Initable)(),i("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 o=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,o.validateData)(this.params,null==t?void 0:t.paramsValidationDto)),this.query=e.query||{},(null==t?void 0:t.queriesValidationDto)&&(this.query=(0,o.validateData)(this.jsonParsing(this.query,t.queriesValidationDto),t.queriesValidationDto)),this.body=e.body||{},t&&(t.httpMethod===o.HttpMethod.POST||t.httpMethod===o.HttpMethod.PUT)&&(null==t?void 0:t.bodyValidationDto)&&(this.body=(0,o.validateData)(this.body||{},t.bodyValidationDto))}jsonParsing(e,t){const n=Object.assign({},e);for(const i of t.fields)try{(void 0!==e[i.name]||i.isRequired)&&(n[i.name]=JSON.parse(e[i.name]))}catch(e){throw o.ErrorBuilder.error(o.Errors.VALIDATION_ERROR,`JSON parsing failed for field ${i.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 o=this&&this.__awaiter||function(e,t,n,o){return new(n||(n=Promise))((function(i,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?i(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractHttpController=void 0;const i=n(2318),r=n(7756);t.AbstractHttpController=class AbstractHttpController{constructor(e){this.databaseAdapter=e}createTransaction(){return o(this,void 0,void 0,(function*(){return this.databaseAdapter.createTransaction()}))}getCurrentTransaction(){return o(this,void 0,void 0,(function*(){return(0,r.getTransactionFromContext)(this)}))}getEndpointMetadata(){const e=(0,i.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 o=this&&this.__awaiter||function(e,t,n,o){return new(n||(n=Promise))((function(i,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?i(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractHttpRequestHandler=void 0;const i=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 o(this,void 0,void 0,(function*(){if(!this.mountedEndpointInfo){const o=[],a=(0,i.getServiceProvider)().getInjector(),d=a.resolveMultiple(s.AbstractHttpController);yield a.initInstances();for(const e of d){const t=(0,i.getObjectMetadata)(e.constructor),n=e.getEndpointMetadata();for(const r of n){const n={mount:r.httpMethod===i.SocketMethod.MESSAGE?r.url:this.resolverMountPoint(t,[this.mountPoint||"/",r.url]),httpMethod:r.httpMethod,controller:e,handlerFunctionName:r.name};o.push({endpointMetadata:r,endpoint:n})}}const l=[];for(const i of o){const o=l.find((e=>e.endpoint.mount===i.endpoint.mount&&e.endpoint.httpMethod===i.endpoint.httpMethod));o?null===(e=this.logger)||void 0===e||e.warn(`Implicit overriding endpoint: ${(0,r.getEndpointId)(o.endpoint)} of ${null===(t=o.endpoint.controller)||void 0===t?void 0:t.constructor.name}:${o.endpoint.handlerFunctionName}`,`Ignore ${(0,r.getEndpointId)(i.endpoint)} of ${null===(n=i.endpoint.controller)||void 0===n?void 0:n.constructor.name}:${i.endpoint.handlerFunctionName}`):l.push(i)}this.mountedEndpointInfo=l}return this.mountedEndpointInfo}))}}},7282:function(e,t,n){var o=this&&this.__decorate||function(e,t,n,o){var i,r=arguments.length,s=r<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,n):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,o);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(r<3?i(s):r>3?i(t,n,s):i(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},i=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,o){t(n,o,e)}},s=this&&this.__awaiter||function(e,t,n,o){return new(n||(n=Promise))((function(i,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?i(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.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),v=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 o={id:"",fields:[]};let i=e.fields.filter((e=>!e.hasMany));i="get_response"===t||"query"===t?i:"create_response"===t?i.filter((e=>e.pk||e.serverValue)):"create_body"===t||"update_body"===t?i.filter((e=>{var t;return!e.serverValue&&!(null===(t=e.pk)||void 0===t?void 0:t.isAutoIncrement)||!!n&&!n.fields.find((t=>{var n;return(null===(n=t.hasMany)||void 0===n?void 0:n.column)===e.name}))})):[];const r=e.fields.filter((e=>!!e.hasMany));return o.fields.push(...i.map((e=>Object.assign(Object.assign({},e),{elementDto:e.elementDto&&("update_body"===t?(0,a.partialize)(e.elementDto):e.elementDto),isRequired:!("query"===t||"update_body"===t||"get_response"===t&&!n)&&e.isRequired}))),...r.map((n=>{var o,i,r,s;const d=CrudHttpController.getBodyDtoRecordClass(n.hasMany.relationDto,t,e);return{description:`All records of "${null===(o=n.hasMany)||void 0===o?void 0:o.relationDto.id}" table in this relationship.`,name:n.name,dataType:(null===(i=n.hasMany)||void 0===i?void 0:i.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))})}}))),o}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,v.DtoFieldValidation)(this.model,(e=>e.getBody().records))],e.params={0:{source:"raw"}},e}getManyEndpointMetadata(){const e={};return e.httpMethod=a.HttpMethod.GET,e.url=this.getMountedUrl(),e.name=CrudHttpController.prototype.getMany.name,e.displayName="getAll"+this.model.name,e.queriesValidationDto=CrudHttpController.getGetManyQueryValidator(this.modelMetadata),e.responseValidationDto=CrudHttpController.getGetManyResponseValidator(this.modelMetadata),e.accessConditions=[(0,v.DtoFieldValidation)(this.model,(e=>[e.getQuery().fields])),(0,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,v.DtoFieldValidation)(this.model,(e=>[e.getQuery().fields]),"dto_field_validation_query"),(0,v.DtoFieldValidation)(this.model,(e=>[e.getBody().update]),"dto_field_validation_body")],e.params={0:{source:"raw"}},e}deleteManyEndpoinMetadata(){const e={};return e.httpMethod=a.HttpMethod.DEL,e.url=this.getMountedUrl(),e.name=CrudHttpController.prototype.deleteMany.name,e.displayName="delete"+this.model.name,e.queriesValidationDto=CrudHttpController.getUpdateManyQueryValidator(this.modelMetadata),e.responseValidationDto=CrudHttpController.getUpdateManyResponseValidator(this.modelMetadata),e.params={0:{source:"raw"}},e.accessConditions=[(0,v.DtoFieldValidation)(this.model,(e=>[e.getQuery().fields]))],e}static getCreateManyBodyValidator(e){const t={id:"",fields:[]},n={name:"records",description:"Array of records to be created."};return n.dataType=a.DataType.ARRAY,n.isRequired=!0,n.vectorProps={elementDataType:a.DataType.OBJECT,minLength:0},n.elementDto=CrudHttpController.getBodyDtoRecordClass(e,"create_body"),t.fields.push(n),t}static getCreateManyResponseValidator(e){const t={id:"",fields:[]},n={name:"records",description:"Array of records had just been created."};return n.dataType=a.DataType.ARRAY,n.isRequired=!0,n.vectorProps={elementDataType:a.DataType.OBJECT,minLength:0},n.elementDto=CrudHttpController.getBodyDtoRecordClass(e,"create_response"),t.fields.push(n),t}static getGetManyResponseValidator(e){const t={id:"",fields:[]},n={name:"total",description:"Number of records found, zero is returned if the request is not paged."};n.dataType=a.DataType.NUMBER,n.isRequired=!0,t.fields.push(n);const o={name:"records",description:"The found records. All records will be returned if the request is not paged."};return o.dataType=a.DataType.ARRAY,o.isRequired=!0,o.vectorProps={elementDataType:a.DataType.OBJECT,minLength:0},o.elementDto=CrudHttpController.getBodyDtoRecordClass(e,"get_response"),t.fields.push(o),t}static getGetManyQueryValidator(e){const t={id:"",fields:[CrudHttpController.queryFieldDto(e)]},n={name:"search",description:"Filter records for their @Searchable denoted fields."};n.dataType=a.DataType.STRING,t.fields.push(n),t.fields.push(CrudHttpController.projectionFieldDto(e));const 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 i={id:"",fields:[]};i.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=i,t.fields.push(o);const r={name:"limit",description:"Limit the number of returning result."};r.dataType=a.DataType.NUMBER,r.rangeProps={min:1},t.fields.push(r);const s={name:"page",description:"Page the returning result, default to 1 if ommited. Has no effect if limit is not set."};return s.dataType=a.DataType.NUMBER,s.rangeProps={min:1},t.fields.push(s),t}static getUpdateManyQueryValidator(e){const t={name:"returning",description:"Whether to return the affected records by this request."};return t.dataType=a.DataType.BOOLEAN,t.isRequired=!1,{id:"",fields:[t,CrudHttpController.queryFieldDto(e)]}}static getUpdateManyBodyValidator(e){const t={id:"",fields:[]},n={name:"update",isRequired:!0,description:"The update data to apply to found records."};return n.dataType=a.DataType.OBJECT,n.elementDto=CrudHttpController.getBodyDtoRecordClass(e,"update_body"),t.fields.push(n),t}static getUpdateManyResponseValidator(e){const t={id:"",fields:[]},n={name:"modified",description:"Array of affected records."};return n.dataType=a.DataType.ARRAY,n.vectorProps={minLength:0,elementDataType:a.DataType.OBJECT},n.elementDto=n.elementDto=CrudHttpController.getBodyDtoRecordClass(e,"get_response"),t.fields.push(n),t}getEndpointMetadata(){var e,t,n,o;let i=super.getEndpointMetadata();const r=[];(null===(e=this.modelMetadata.ignoreCrud)||void 0===e?void 0:e.includes(a.HttpMethod.GET))?i=i.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))?i=i.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))?i=i.filter((e=>e.name!==CrudHttpController.prototype.updateMany.name)):r.push(this.updateManyEndpoinMetadata()),(null===(o=this.modelMetadata.ignoreCrud)||void 0===o?void 0:o.includes(a.HttpMethod.DEL))?i=i.filter((e=>e.name!==CrudHttpController.prototype.deleteMany.name)):r.push(this.deleteManyEndpoinMetadata());for(const e of r){const t=i.findIndex((t=>t.httpMethod===e.httpMethod&&t.url===e.url||t.name===e.name&&(!t.httpMethod||!t.url)));t>=0?i[t]=Object.assign(Object.assign(Object.assign({},e),i[t]),{accessConditions:[...e.accessConditions||[],...i[t].accessConditions||[]]}):i.push(e)}return i}createMany(e){return s(this,void 0,void 0,(function*(){const t=yield this.getCurrentTransaction(),n=yield this.getAuthProvider(),o=n&&(yield n.resolvePrincipal(e)),i=yield this.crudRepository.createMany({principal:o,body:e.getBody(),tx:t});return f.ResponseBuilder.json(i).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(),o=n&&(yield n.resolvePrincipal(e)),i=yield this.crudRepository.updateMany({principal:o,queries:e.getQuery(),body:e.getBody(),tx:t});return f.ResponseBuilder.json(i).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()}))}}o([(0,d.Transactional)(d.TransactionLink.INHERIT_OR_CREATE),(0,u.ApiDescription)("Create records of this table."),(0,u.AccessCondition)([]),r(0,(0,u.Raw)()),i("design:type",Function),i("design:paramtypes",[c.HttpRequest]),i("design:returntype",Promise)],CrudHttpController.prototype,"createMany",null),o([(0,u.AccessCondition)([]),(0,u.ApiDescription)("Get records of this table."),r(0,(0,u.Raw)()),i("design:type",Function),i("design:paramtypes",[c.HttpRequest]),i("design:returntype",Promise)],CrudHttpController.prototype,"getMany",null),o([(0,d.Transactional)(d.TransactionLink.INHERIT_OR_CREATE),(0,u.ApiDescription)("Find and update records which match search condition."),(0,u.AccessCondition)([]),r(0,(0,u.Raw)()),i("design:type",Function),i("design:paramtypes",[c.HttpRequest]),i("design:returntype",Promise)],CrudHttpController.prototype,"updateMany",null),o([(0,d.Transactional)(d.TransactionLink.INHERIT_OR_CREATE),(0,u.ApiDescription)("Find and remove records which match search condition."),(0,u.AccessCondition)([]),r(0,(0,u.Raw)()),i("design:type",Function),i("design:paramtypes",[c.HttpRequest]),i("design:returntype",Promise)],CrudHttpController.prototype,"deleteMany",null),t.CrudHttpController=CrudHttpController},5879:function(e,t,n){var o=this&&this.__decorate||function(e,t,n,o){var i,r=arguments.length,s=r<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,n):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,o);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(r<3?i(s):r>3?i(t,n,s):i(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},i=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,o){return new(n||(n=Promise))((function(i,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?i(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.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 v=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}})),o=yield e.endpoint.controller[e.endpointMetadata.name](...n);return e.endpointMetadata.responseValidationDto&&(o.value=(0,a.stripData)(o.value,e.endpointMetadata.responseValidationDto)),o}))}exit(){}handle(e){return r(this,void 0,void 0,(function*(){const t=e.method,n=(0,d.default)({url:e.fullPath});let o={};const i=(yield this.getMountedEndpointInfo()).find((e=>{const i=e.endpointMetadata.httpMethod===t&&(0,l.match)(e.endpointMetadata.url,{decode:decodeURIComponent})(n.pathname||"/");return!!i&&(o=i,!0)}));if(!i)throw this.logger.debug(e),a.ErrorBuilder.error(y.Errors.NOT_FOUND,"Handler not found");const r=new h.HttpRequest({method:t,headers:e.headers,pathName:n.pathname||"",hash:n.hash||"",query:c.default.parse(decodeURIComponent(n.search||"")),params:o.params,body:e.body},i.endpointMetadata);let s;try{for(const e of this.getMiddleware())if(s=yield e.intercept(r),s)break;if(s||(s=yield this.handleRequest(i,r)),!(s&&s instanceof u.HttpResponse))throw a.ErrorBuilder.systemError(`Invalid response value returned ${i.endpoint.httpMethod}:${i.endpoint.mount}, required instance of ${u.HttpResponse.name}, found ${s?null==s?void 0:s.constructor.name:s}`)}catch(e){this.logger.error(e),s=u.ResponseBuilder.json({name:e.name,message:e.message}).status([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 s}))}getMiddleware(){return[]}};v=o([(0,a.Injectable)(),i("design:paramtypes",[a.AbstractLogger,p.AbstractHttpAuthorizationProvider])],v),t.DefaultHttpRequestHandler=v},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 o=n(2318);t.Controller=e=>t=>{(0,o.getServiceProvider)().register(t,"singleton");(0,o.initObjectMetadata)(t.prototype).permissionGroup=null==e?void 0:e.permissionGroup};t.ApiDescription=e=>(t,n)=>{(0,o.initFieldMetadata)(t,n).description=e};t.Endpoint=e=>(t,n)=>{const i=(0,o.initFieldMetadata)(t,n);i.httpMethod=e.method,i.url=e.url||"/"};t.Post=e=>(n,i,r)=>(0,t.Endpoint)({method:o.HttpMethod.POST,url:e})(n,i);t.Put=e=>(n,i,r)=>(0,t.Endpoint)({method:o.HttpMethod.PUT,url:e})(n,i);t.Del=e=>(n,i,r)=>(0,t.Endpoint)({method:o.HttpMethod.DEL,url:e})(n,i);t.Get=e=>(n,i,r)=>(0,t.Endpoint)({method:o.HttpMethod.GET,url:e})(n,i);t.ApiResponse=e=>(t,n,i)=>{const r=(0,o.initFieldMetadata)(t,n);e===String?r.responseValidationDto={id:"",primitiveType:o.DataType.STRING,fields:[]}:e===Number?r.responseValidationDto={id:"",primitiveType:o.DataType.NUMBER,fields:[]}:e===Boolean?r.responseValidationDto={id:"",primitiveType:o.DataType.BOOLEAN,fields:[]}:r.responseValidationDto=(0,o.getObjectMetadata)(e)};t.OpenAccess=()=>(e,t)=>{(0,o.initFieldMetadata)(e,t).openAccess=!0};t.TfaRequired=()=>(e,t)=>{(0,o.initFieldMetadata)(e,t).tfaRequired=!0};t.AccessCondition=e=>(t,n)=>{(0,o.initFieldMetadata)(t,n).accessConditions=e};const RequestDeco=e=>(t,n,i)=>{const r=(0,o.initFieldMetadata)(t,n),s=Reflect.getMetadata("design:paramtypes",t,n)||[];switch(e){case"body":r.bodyValidationDto=(0,o.getObjectMetadata)(s[i]);break;case"params":r.paramsValidationDto=(0,o.getObjectMetadata)(s[i]);break;case"queries":r.queriesValidationDto=(0,o.getObjectMetadata)(s[i])}r.params||(r.params={}),r.params[i]={source:e,diClass:s[i]}};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,o.initFieldMetadata)(t,n).uriMapper=e};t.CurrentUser=e=>(t,n)=>{const i=(0,o.initFieldMetadata)(t,n);i.userResolver=e,i.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 o=this&&this.__decorate||function(e,t,n,o){var i,r=arguments.length,s=r<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,n):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,o);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(r<3?i(s):r>3?i(t,n,s):i(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},i=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,o){return new(n||(n=Promise))((function(i,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?i(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.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=o([(0,s.Injectable)(),i("design:paramtypes",[a.AbstractFileService])],l),t.FileUploadHandler=l},5232:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},5048:function(e,t,n){var o=this&&this.__awaiter||function(e,t,n,o){return new(n||(n=Promise))((function(i,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?i(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractRepository=void 0;const i=n(2318);t.AbstractRepository=class AbstractRepository{constructor(e){this.model=e,this.modelMetadata=(0,i.getObjectMetadata)(this.model)}beforeCreating(e,t){return o(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 o=this&&this.__awaiter||function(e,t,n,o){return new(n||(n=Promise))((function(i,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?i(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.DtoRepository=t.MultipleMap=t.SingleMap=void 0;const i=n(2318),r=n(5048),s=n(3355);t.SingleMap=(e,t,n,o,i)=>({multiple:!1,modelClass:e,forwardOps:t,forwardMapping:e=>{const t=n(e[0]||{});return t&&[t]},rootMapping:e=>{const t=e&&e[0];return o(t)},nestedMapping:i});t.MultipleMap=(e,t,n,o,i)=>({multiple:!0,modelClass:e,forwardOps:t,forwardMapping:n,rootMapping:o,nestedMapping:i});class DtoRepository extends r.AbstractRepository{constructor(e,t){super(e),this.model=e,this.dissolver=t}getMapValue(e,t,n,r,s){return o(this,void 0,void 0,(function*(){for(const o of n){const n=yield t(o);let a=r?yield r(o,o.forwardMapping(n),n):o.forwardMapping(n);if(o.nestedMapping&&a)for(const n of a)yield this.getMapValue(e,t,o.nestedMapping(n),r,s);s&&(a=yield s(o,o.forwardMapping(n),n));const d=o.rootMapping(a);(0,i.deepMerge)(e,d)}}))}createMany({principal:e,body:t,tx:n}){return o(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=>o(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)=>o(this,void 0,void 0,(function*(){if(!r)return[];const o=new s.ModelRepository(t.modelClass),d=t.forwardOps();if(t.multiple){yield o.deleteMany({ops:d,tx:n});return(yield o.createMany({principal:e,body:{records:r},tx:n})).records}{const s=r[0];if(!s)return[];if(0===a.length){return(yield o.createMany({principal:e,body:{records:r},tx:n})).records}if(1===a.length){const t=yield o.updateMany({principal:e,ops:d,body:{update:s},tx:n});return[Object.assign(Object.assign(Object.assign({},a[0]),s),t.modified[0])]}throw i.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 o(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 i.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=>o(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,i,r)=>o(this,void 0,void 0,(function*(){if(!i)return[];const o=new s.ModelRepository(t.modelClass),d=t.forwardOps(n);if(t.multiple){yield o.deleteMany({ops:d,tx:a});return(yield o.createMany({principal:e,body:{records:i},tx:a})).records}{const t=i[0];return t?0==r.length?[]:(r.length>1?(yield o.deleteMany({ops:d,tx:a}),yield o.createMany({principal:e,body:{records:[t]},tx:a})):yield o.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 o(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 i.ErrorBuilder.validationError("Missing required id field in query");const a={id:e.fields.id[0]};return yield this.getMapValue(a,(()=>o(this,void 0,void 0,(function*(){return[]}))),this.dissolver(a),(e=>o(this,void 0,void 0,(function*(){const o=new s.ModelRepository(e.modelClass);return(yield o.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 o(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 i.ErrorBuilder.validationError("Missing required id field in query");const a={id:e.fields.id[0]};return yield this.getMapValue(a,(()=>o(this,void 0,void 0,(function*(){return[]}))),this.dissolver(a),void 0,(i=>o(this,void 0,void 0,(function*(){const o=new s.ModelRepository(i.modelClass),r=i.forwardOps(t);return(yield o.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 o=this&&this.__awaiter||function(e,t,n,o){return new(n||(n=Promise))((function(i,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?i(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.ModelRepository=void 0;const i=n(2318),r=n(7756),s=n(6507),a=n(5048);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,o=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:o.length?{_and:o}:{}}}))}getUploadHandler(){return o(this,void 0,void 0,(function*(){if(void 0===this.fileUploadHandler){const e=(0,i.getServiceProvider)().getInjector();this.fileUploadHandler=e.resolveOptional(s.AbstractFileUploadHandler)||null,yield e.initInstances()}return this.fileUploadHandler}))}getRequestQueryConditionFromQuery(e,t){var n;const o=[];for(const s of(0,r.getDirectFields)(t)){const t=e[s.name];if(void 0!==t)if(s.pk||s.fk||s.isSymbol)o.push({_in:{[s.name]:t}});else if(s.enum)o.push({_in:{[s.name]:t}});else switch(s.dataType){case i.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}};o.push(e)}else o.push({_eq:{[s.name]:t}});break;case i.DataType.NUMBER:const e=new i.RangeQueryDto;Object.assign(e,t),e.min&&(e.minExclusive?o.push({_gt:{[s.name]:e.min}}):o.push({_gte:{[s.name]:e.min}})),e.max&&(e.maxExclusive?o.push({_lt:{[s.name]:e.max}}):o.push({_lte:{[s.name]:e.max}}));break;case i.DataType.BOOLEAN:o.push({_eq:{[s.name]:t}})}}return o}uriHandling(e,t){return o(this,void 0,void 0,(function*(){const n=yield this.getUploadHandler();if(!n)return;const o=t.use(this.model);for(const i of this.modelMetadata.fields)if(i.uriMapper)for(const r of e){const e=r[i.name];if(!e)continue;const s=yield i.uriMapper(t,r,e);s&&(yield n.moveFile(e,s),r[i.name]=s,yield o.updateOne(r))}}))}beforeReturning(e){var t;return o(this,void 0,void 0,(function*(){const n=yield this.getUploadHandler();for(const o of e)for(const e of this.modelMetadata.fields)if(e.uriMapper&&n){if(!o[e.name])continue;o[e.name]=(null===(t=e.mimeProps)||void 0===t?void 0:t.public)?yield n.resolvePublicUrl(o[e.name]):yield n.resolvePrivateUrl(o[e.name])}}))}createMany({principal:e,body:t,tx:n}){var s;return o(this,void 0,void 0,(function*(){const o=t.records;if(!o.length)return{records:[]};const a=(0,r.getDirectFields)(this.modelMetadata),d=this.modelMetadata.fields.filter((e=>!!e.hasMany));t.records=o.map((e=>a.reduce(((t,n)=>Object.assign(t,void 0!==e[n.name]?{[n.name]:e[n.name]}:{})),{}))),yield this.beforeCreating(e,t.records);let l=t.records.length?yield n.use(this.model).createMany(t.records):[];yield this.uriHandling(l,n),yield this.beforeReturning(l);const c=this.modelMetadata.fields.filter((e=>e.pk||e.serverValue||e.mimeProps)).map((e=>e.name));l=this.project(l,c);for(const r of d){const a=l.flatMap(((e,t)=>{var n;const i=o[t][r.name];return i?((null===(n=r.hasMany)||void 0===n?void 0:n.single)?[i]:i).map((t=>Object.assign(Object.assign({},t),{[r.hasMany.column]:e.id}))):[]}));if(a.length){const o=new ModelRepository((0,i.getModelById)(r.hasMany.relationDto.id));t.records=a;const d=yield o.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<l.length;e++){const t=[];for(let n=0;n<a.length;n++)a[n][r.hasMany.column]===l[e].id&&t.push(d.records[e]);l[e]=Object.assign(Object.assign({},l[e]),{[r.name]:(null===(s=r.hasMany)||void 0===s?void 0:s.single)?t[0]:t})}}}return{records:l}}))}updateMany({principal:e,ops:t,queries:n,body:s,tx:a}){var d,l;return o(this,void 0,void 0,(function*(){const o=t||[],c=this.modelMetadata.fields.filter((e=>!!e.hasMany)),u=(0,r.getDirectFields)(this.modelMetadata).filter((e=>void 0!==s.update[e.name])),h=u.reduce(((e,t)=>Object.assign(e,{[t.name]:s.update[t.name]})),{});if(null==n?void 0:n.fields){const e=this.getRequestQueryConditionFromQuery(n.fields,this.modelMetadata);e.length&&o.push(...e)}const p=o.length?{_and:[...o]}:{},f=this.getNestedQueries(n);let y=[];if(f.length){const e=yield a.use(this.model).getMany(p,{projection:["id"]},f);y=e.records.map((e=>e.id)),y.length&&u.length&&(yield a.use(this.model).updateMany({_in:{id:y}},h,!1))}else if(u.length)y=yield a.use(this.model).updateMany(p,h,!0);else{const e=yield a.use(this.model).getMany(p,{projection:["id"]});y=e.records.map((e=>e.id))}let v=y.map((e=>Object.assign(Object.assign({},h),{id:e})));yield this.uriHandling(v,a),yield this.beforeReturning(v);for(const t of c){const n=s.update[t.name];if(void 0===n||!y.length)continue;if(y.length>1)throw i.ErrorBuilder.systemError(`Multiple records found while updating @HasMany field: ${t.name}`);const o=v.find((e=>e.id===y[0])),r=(0,i.getModelById)(t.hasMany.relationDto.id),c=a.use(r),u=(yield c.getRecords({_eq:{[t.hasMany.column]:o.id}},{limit:(null===(d=t.hasMany)||void 0===d?void 0:d.single)?1:void 0})).map((e=>e.id)),h=n.map((e=>e.id)).filter((e=>!!e)),p=u.filter((e=>!h.includes(e))),f=n.filter((e=>!e.id)).map((e=>Object.assign(Object.assign({},e),{[t.hasMany.column]:o.id}))),g=n.filter((e=>!!e.id));yield c.deleteMany({_in:{id:p}});const m=new ModelRepository(r),b=yield m.createMany({principal:e,body:{records:f},tx:a}),M=f.map(((e,t)=>Object.assign(Object.assign({},e),b.records[t]))).concat(g);o[t.name]=(null===(l=t.hasMany)||void 0===l?void 0:l.single)?M[0]:M}let g=["id"];return(null==n?void 0:n.returning)&&(g=[...g,...Object.keys(s.update).filter((e=>void 0!==s.update[e]))]),{modified:this.project(v,g)}}))}getMany({queries:e,ops:t,queryProvider:n}){var r;return o(this,void 0,void 0,(function*(){const o=t||[];if((null==e?void 0:e.fields)&&o.push(...this.getRequestQueryConditionFromQuery(e.fields,this.modelMetadata)),console.log("conditio here",o,e),null==e?void 0:e.search){const t=this.modelMetadata.fields.filter((e=>e.searchable)).map((t=>({_iusub:{[t.name]:e.search}})));t.length&&o.push({_or:t})}const s=yield n.use(this.model).getMany(o.length?{_and:o}:{},{limit:(null==e?void 0:e.limit)||void 0,page:null==e?void 0:e.page,projection:null==e?void 0:e.projection,order:null===(r=null==e?void 0:e.order)||void 0===r?void 0:r.map((e=>{const t=Object.keys(e).find((t=>!!e[t]));return[t,e[t]]}))},this.getNestedQueries(e)),a=s.records.map((e=>e.id));for(const t of this.modelMetadata.fields){if(!t.hasMany||(null==e?void 0:e.projection)&&!e.projection.includes(t.name))continue;const o=(0,i.getModelById)(t.hasMany.relationDto.id),r=new ModelRepository(o),d=a.length?yield r.getMany({queries:{fields:{[t.hasMany.column]:a},limit:t.hasMany.single?1:0},queryProvider:n}):{records:[]};for(const e of s.records){const n=d.records.filter((n=>n[t.hasMany.column]===e.id));e[t.name]=t.hasMany.single?n[0]:n}}return yield this.beforeReturning(s.records),{total:s.total,records:this.project(s.records,null==e?void 0:e.projection)}}))}deleteMany({queries:e,ops:t,tx:n}){return o(this,void 0,void 0,(function*(){let o=t||[];if(null==e?void 0:e.fields){const t=this.getRequestQueryConditionFromQuery(e.fields,this.modelMetadata);t.length&&o.push(...t)}const i=o.length?{_and:[...o,...t||[]]}:{},r=this.getNestedQueries(e);let s=[];if(r.length){const e=yield n.use(this.model).getRecords(i,{},r);yield n.use(this.model).deleteMany({_in:{id:e.map((e=>e.id))}}),s=e}else s=yield n.use(this.model).deleteMany(i,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 o=this&&this.__decorate||function(e,t,n,o){var i,r=arguments.length,s=r<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,n):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,o);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(r<3?i(s):r>3?i(t,n,s):i(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__awaiter||function(e,t,n,o){return new(n||(n=Promise))((function(i,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?i(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.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 i(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 i(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=o([(0,r.Register)()],a),a}},1071:function(e,t,n){var o=this&&this.__decorate||function(e,t,n,o){var i,r=arguments.length,s=r<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,n):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,o);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(r<3?i(s):r>3?i(t,n,s):i(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__awaiter||function(e,t,n,o){return new(n||(n=Promise))((function(i,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?i(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.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 i(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 i(this,void 0,void 0,(function*(){return!!e&&e.every((e=>t.includes(e)))}))}};return n=o([(0,r.Register)()],n),n}},3198:function(e,t,n){var o=this&&this.__decorate||function(e,t,n,o){var i,r=arguments.length,s=r<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,n):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,o);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(r<3?i(s):r>3?i(t,n,s):i(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__awaiter||function(e,t,n,o){return new(n||(n=Promise))((function(i,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?i(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.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 i(this,void 0,void 0,(function*(){let t=e.getQuery().limit;return t&&(t=parseInt(t)),t||0}))}validate(e,t){return i(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=o([(0,r.Register)()],a),t.MaximumQueryLimit=a},341:function(e,t,n){var o=this&&this.__createBinding||(Object.create?function(e,t,n,o){void 0===o&&(o=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,o,i)}:function(e,t,n,o){void 0===o&&(o=n),e[o]=t[n]}),i=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||o(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),i(n(9025),t),i(n(4638),t),i(n(1820),t),i(n(1870),t),i(n(4972),t),i(n(8903),t),i(n(2417),t),i(n(1532),t),i(n(5879),t),i(n(6004),t),i(n(7282),t),i(n(4435),t),i(n(767),t),i(n(225),t),i(n(2255),t),i(n(1071),t),i(n(3198),t),i(n(4192),t),i(n(859),t),i(n(2085),t),i(n(531),t),i(n(7825),t),i(n(9837),t),i(n(3355),t),i(n(9073),t),i(n(8023),t),i(n(5048),t),i(n(5530),t),i(n(2841),t),i(n(7152),t),i(n(8577),t),i(n(2665),t),i(n(9990),t),i(n(6507),t),i(n(4839),t),i(n(5232),t),i(n(5572),t),i(n(889),t),i(n(5537),t),i(n(226),t),i(n(8836),t),i(n(9627),t),i(n(6721),t),i(n(204),t),i(n(7577),t),i(n(8709),t),i(n(1556),t),i(n(2363),t),i(n(4683),t),i(n(3346),t),i(n(9527),t),i(n(3581),t),i(n(3376),t),i(n(8104),t),i(n(5033),t)},4683:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractJobController=void 0;const o=n(2318);t.AbstractJobController=class AbstractJobController{getAllJobs(){const e=(0,o.getObjectMetadata)(this.constructor);return(null==e?void 0:e.jobs)||[]}}},3346:function(e,t,n){var o=this&&this.__awaiter||function(e,t,n,o){return new(n||(n=Promise))((function(i,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?i(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractJobExecutor=void 0;const i=n(2318),r=n(4683);t.AbstractJobExecutor=class AbstractJobExecutor{constructor(){this._allJobs=null}init(){return o(this,void 0,void 0,(function*(){}))}getAllJobs(){return o(this,void 0,void 0,(function*(){if(!this._allJobs){const e=(0,i.getServiceProvider)().getInjector(),t=e.resolveMultiple(r.AbstractJobController);yield e.initInstances(),this._allJobs=t.map((e=>e.getAllJobs().map((t=>({jobName:t.jobName,handlerFn:e[t.handlerName].bind(e)}))))).reduce(((e,t)=>e.concat(t)),[])}return this._allJobs}))}}},9527:function(e,t,n){var o=this&&this.__awaiter||function(e,t,n,o){return new(n||(n=Promise))((function(i,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?i(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractJobScheduler=void 0;const i=n(2318),r=n(4683);t.AbstractJobScheduler=class AbstractJobScheduler{constructor(e){this.logger=e}schedule(){return o(this,void 0,void 0,(function*(){const e=(0,i.getServiceProvider)().getInjector(),t=e.resolveMultiple(r.AbstractJobController);yield e.initInstances();const n=t.map((e=>e.getAllJobs())).reduce(((e,t)=>e.concat(t)),[]).filter((e=>e.interval||e.cron));for(const e of n)this.logger.debug(`Scheduling: ${e.jobName}, at: ${e.cron||e.interval}`),this.scheduleJob({jobName:e.jobName,cron:e.cron,interval:e.interval}),this.logger.debug(`Job scheduled: ${e.jobName}`)}))}}},3581:function(e,t,n){var o=this&&this.__awaiter||function(e,t,n,o){return new(n||(n=Promise))((function(i,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?i(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AwsJobExecutor=void 0;const i=n(3346);class AwsJobExecutor extends i.AbstractJobExecutor{constructor(e){super(),this.logger=e}executeJob(e,t){return o(this,void 0,void 0,(function*(){(yield this.getAllJobs()).find((t=>t.jobName===e.jobName))?e.interval||e.cron:this.logger.error(`Job not found: ${e.jobName}`)}))}}t.AwsJobExecutor=AwsJobExecutor},3376:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AwsJobScheduler=void 0;const o=n(9527);class AwsJobScheduler extends o.AbstractJobScheduler{scheduleJob(e){}}t.AwsJobScheduler=AwsJobScheduler},8104:function(e,t,n){var o=this&&this.__awaiter||function(e,t,n,o){return new(n||(n=Promise))((function(i,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?i(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.LocalJobExecutor=void 0;const i=n(3346);class LocalJobExecutor extends i.AbstractJobExecutor{constructor(e){super(),this.logger=e}executeJob(e,t){return o(this,void 0,void 0,(function*(){const t=(yield this.getAllJobs()).find((t=>t.jobName===e.jobName));t?yield t.handlerFn(e):this.logger.error(`Job not found: ${e.jobName}`)}))}}t.LocalJobExecutor=LocalJobExecutor},5033:function(e,t,n){var o=this&&this.__decorate||function(e,t,n,o){var i,r=arguments.length,s=r<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,n):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,o);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(r<3?i(s):r>3?i(t,n,s):i(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},i=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,o){return new(n||(n=Promise))((function(i,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?i(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.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(8311)),l=s(n(1495)),c=s(n(9896)),u=n(3346),h=n(9527);let p=class LocalJobScheduler extends h.AbstractJobScheduler{constructor(e,t,n,o,i,r=30){super(e),this.logger=e,this.jobExecutor=t,this.redisServerUrl=n,this.lockMutexKey=o,this.holdMutexKey=i,this.keyRetentionDurationSecond=r,this.intervals=[]}init(){return r(this,void 0,void 0,(function*(){this.logger.debug("LocalJobScheduler init")}))}exit(){var e;this.mutexHoldInterval&&clearInterval(this.mutexHoldInterval),null===(e=this.redisClient)||void 0===e||e.quit();for(const e of this.intervals)clearInterval(e);this.logger.debug("LocalJobScheduler exit")}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"))}))}schedule(){const e=Object.create(null,{schedule:{get:()=>super.schedule}});return r(this,void 0,void 0,(function*(){this.redisClient||(this.redisClient=new l.default(this.redisServerUrl));if(yield this.redisClient.exists(this.holdMutexKey))return void this.logger.info("Scheduler is active, ignore");const t=new c.default([this.redisClient]);try{const n=yield t.acquire([this.lockMutexKey],this.keyRetentionDurationSecond);yield e.schedule.call(this),yield this.extendMutexKey(),yield n.release(),this.logger.debug("Schedule finished"),this.mutexHoldInterval=setInterval((()=>{this.extendMutexKey()}),Math.trunc(1e3*this.keyRetentionDurationSecond/2)+1)}catch(e){console.log(e),this.logger.info("Failed to lock mutex key, ignore")}}))}scheduleJob(e){if(e.interval){const t=setInterval((()=>this.jobExecutor.executeJob(e,0)),1e3*e.interval);this.intervals.push(t)}else if(e.cron){if(!d.default.validate(e.cron))throw a.ErrorBuilder.systemError(`Invalid cron job expression for job ${e.jobName}: ${e.cron}`);d.default.schedule(e.cron,(()=>this.jobExecutor.executeJob(e,0)))}}};p=o([(0,a.Initable)(),i("design:paramtypes",[a.AbstractLogger,u.AbstractJobExecutor,String,String,String,Number])],p),t.LocalJobScheduler=p},1556:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CustomJob=t.CronJob=t.IntervalJob=void 0;const o=n(2318);t.IntervalJob=(e,t)=>(n,i)=>{const r=(0,o.initObjectMetadata)(n);r.jobs||(r.jobs=[]),r.jobs.push({jobName:e,interval:t,handlerName:i})};t.CronJob=(e,t)=>(n,i)=>{const r=(0,o.initObjectMetadata)(n);r.jobs||(r.jobs=[]),r.jobs.push({jobName:e,cron:t,handlerName:i})};t.CustomJob=e=>(t,n)=>{const i=(0,o.initObjectMetadata)(t);i.jobs||(i.jobs=[]),i.jobs.push({jobName:e,handlerName:n})}},2363:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},5572:function(e,t,n){var o,i=this&&this.__decorate||function(e,t,n,o){var i,r=arguments.length,s=r<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,n):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,o);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(r<3?i(s):r>3?i(t,n,s):i(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,o){return new(n||(n=Promise))((function(i,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?i(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.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=o=class FileLogMedium{constructor(e){const t=e.separated?o.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[o.levels.indexOf(e)]:0;d.default.appendFileSync(n,t)}};u.levels=Object.values(c.LogLevel),u=o=i([(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 o=this&&this.__awaiter||function(e,t,n,o){return new(n||(n=Promise))((function(i,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?i(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractService=void 0;const i=n(7756);t.AbstractService=class AbstractService{constructor(e){this.databaseAdapter=e}createTransaction(){return this.databaseAdapter.createTransaction()}getCurrentTransaction(){return o(this,void 0,void 0,(function*(){return(0,i.getTransactionFromContext)(this)}))}}},6862:(e,t,n)=>{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){t?this.socketInfo.channels.find((e=>e.name===t&&e.serverToClientAllowed))&&this.sendRaw({type:o.MessageType.PLAIN,data:{message:e,channel:t}}):this.sendRaw({type:o.MessageType.PLAIN,data:{message:e}})}sendRaw(e){this.physicSend(e)}disconnect(e){this.physicClose(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 o=this&&this.__decorate||function(e,t,n,o){var i,r=arguments.length,s=r<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,n):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,o);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(r<3?i(s):r>3?i(t,n,s):i(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},i=this&&this.__awaiter||function(e,t,n,o){return new(n||(n=Promise))((function(i,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?i(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.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 i(this,void 0,void 0,(function*(){return e.getHeaders()["x-socket-action"]===p}))}validate(e){return i(this,void 0,void 0,(function*(){return!!e}))}getConditionMetadata(){return{name:"socket_read",description:"Can receive message from channel",valueType:s.AccessConditionValueType.BOOLEAN}}};y=o([(0,s.Register)()],y);let v=class SocketWriteCondition extends c.AbstractAccessCondition{resolveConditionValue(e){return i(this,void 0,void 0,(function*(){return e.getHeaders()["x-socket-action"]===f}))}validate(e){return i(this,void 0,void 0,(function*(){return!!e}))}getConditionMetadata(){return{name:"socket_write",description:"Can send message to channel",valueType:s.AccessConditionValueType.BOOLEAN}}};v=o([(0,s.Register)()],v);t.AbstractServerSocketManager=class AbstractServerSocketManager{constructor(e,t,n,o,i){this.requireAuthentication=e,this.logger=t,this.redisServerUrl=n,this.authProvider=o,this.authResolver=i,this._connectionHandler=null,this.redisClient=new a.default(this.redisServerUrl)}getUniqueChannelPrefix(){return"CHANNEL:"}getConnectionHandler(){return i(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 i(this,void 0,void 0,(function*(){return(yield this.redisClient.smembers(this.getUniqueChannelName(e)))||[]}))}addSocketToChannel(e,t){return i(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){return i(this,void 0,void 0,(function*(){const n=yield this.getById(e);n&&(n.removeChannels(t),yield Promise.all(t.map((t=>this.redisClient.srem(this.getUniqueChannelName(t),e)))),yield n.saveSocketInfo())}))}handle(e){var t;return i(this,void 0,void 0,(function*(){const n=yield this.getConnectionHandler();switch(e.method){case s.SocketMethod.CONNECT:{this.logger.debug("Socket connection attempt",e);const o=this.authResolver(null===(t=e.data)||void 0===t?void 0:t.queries),i=yield this.authProvider.getPrincipalResolver().resolvePrincipal(o);if(!i&&this.requireAuthentication)throw s.ErrorBuilder.error(s.Errors.AUTHENTICATION_ERROR);const r=yield this.addSocket({id:e.socketId,authInfo:i,channels:[],createdAt:Date.now()},e.data);if(!r)throw s.ErrorBuilder.error(s.Errors.SYSTEM_ERROR,"Socket not found after create: "+e.socketId);r.sendRaw({type:s.MessageType.READY,data:void 0}),null==n||n.onSocketConnect(r);break}case s.SocketMethod.DISCONNECT:{this.logger.debug("Socket disconnect",e);const t=yield this.getById(e.socketId);if(t){const o=yield this.getMountedEndpointInfo();for(const n of t.getChannelsInfo()){const i=o.find((e=>e.endpointMetadata.url===n.name));i&&i.endpoint.controller.onChannelLeave(t),yield this.removeSocketFromChannel(e.socketId,t.getChannelsInfo().map((e=>e.name)))}null==n||n.onSocketDisconnect(t),t.physicClose()}break}case s.SocketMethod.MESSAGE:{this.logger.debug("Socket message",e);const t=e.data;let o=yield this.getById(e.socketId);if(o)switch(t.type){case s.MessageType.PING_PONG:null==o||o.sendRaw({type:s.MessageType.PING_PONG,data:t.data});break;case s.MessageType.CHANNEL_JOIN:{const e=t.data,n=[],i=[];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(o.getAuthInfo(),e,a),r=!0}catch(e){}try{const n=new u.HttpRequest({method:s.SocketMethod.MESSAGE,pathName:t,headers:{[h]:f}},a.endpointMetadata);yield this.authProvider.authorize(o.getAuthInfo(),n,a),e=!0}catch(e){}(e||r)&&(this.logger.debug("Adding channel info",t,e,r),n.push({name:t,clientToServerAllowed:e,serverToClientAllowed:r}),i.push(a))}}if(o=yield this.addSocketToChannel(o.getId(),n),o){o.sendRaw({type:s.MessageType.CHANNEL_JOIN,data:n.map((e=>e.name))});for(const e of i)e.endpoint.controller.onChannelJoin(o)}else this.logger.debug("Socket not found after addSocketToChannel")}break;case s.MessageType.CHANNEL_LEAVE:{const e=t.data;for(const t of e){const e=(yield this.getMountedEndpointInfo()).find((e=>e.endpointMetadata.url===t));e&&e.endpoint.controller.onChannelLeave(o)}yield this.removeSocketFromChannel(o.getId(),e)}break;case s.MessageType.PLAIN:{const e=t.data.channel,i=t.data.message;if(e){if(o.getChannelsInfo().find((t=>t.name===e&&t.clientToServerAllowed))){const t=(yield this.getMountedEndpointInfo()).find((t=>t.endpointMetadata.url===e));if(t){!1!==t.endpoint.controller.onMessage(o,i)&&(this.logger.debug("broadcasting to channel",e,i),this.broadcastToChannel(e,i))}}}else null==n||n.onMessage(o,i)}break;default:this.logger.debug("Invalid message format",t)}else this.logger.debug("Socket not found",e.socketId);break}default:return}}))}getMountedEndpointInfo(){return i(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,v]}})))}return this.mountedEndpointInfo}))}}},9990:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractSocketConnectionHandler=void 0;t.AbstractSocketConnectionHandler=class AbstractSocketConnectionHandler{}},2665:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractSocketController=void 0;t.AbstractSocketController=class AbstractSocketController{constructor(e){this.channel=e}onChannelJoin(e){}onChannelLeave(e){}onMessage(e,t){}}},7152:function(e,t,n){var o=this&&this.__decorate||function(e,t,n,o){var i,r=arguments.length,s=r<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,n):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,o);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(r<3?i(s):r>3?i(t,n,s):i(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},i=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,o){return new(n||(n=Promise))((function(i,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?i(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.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,o,i,r){super(n),this.socketManager=e,this.logger=t,this.socketInfo=n,this.apiGateway=o,this.socketNamespace=i,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){this.socketManager.physicSend(this.getId(),e).catch((e=>this.logger.debug("Socket send error",e)))}physicClose(e){e&&this.physicSend(e),this.socketManager.removeSocketFromRedis(this.getId()).catch((e=>this.logger.debug("Socket close error",e))),this.socketManager.removeSocket(this.getId()).catch((e=>this.logger.debug("Socket remove error",e)))}serialize(){return JSON.stringify(this.socketInfo)}}let p=class AwsSocketManager extends c.AbstractServerSocketManager{constructor(e,t,n,o,i,r,s,a){super(e,a,o,r,s),this.authenticationRequired=e,this.region=t,this.socketDomainUrl=n,this.redisServerUrl=o,this.httpRequestHandler=i,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)}))}getSocketInfoHashKey(){return"__SOCKET_INFO__"}physicSend(e,t){return r(this,void 0,void 0,(function*(){try{yield this.apiGatewayManagement.postToConnection({ConnectionId:e,Data:JSON.stringify(t)}).promise(),this.logger.debug(`Socket ${e} send OK`,t)}catch(t){if(this.logger.debug(`Socket ${e} post error`,t),410===t.statusCode){this.logger.debug(`Disconnect & remove stale socket ${e}`);const t=yield this.getById(e);t&&this.removeSocketFromChannel(e,t.getChannelsInfo().map((e=>e.name))).catch((e=>this.logger.error("Cannot remove socket from channels",e))),this.removeSocketFromRedis(e).catch((e=>this.logger.error("Cannot remove socket from redis",e))),this.logger.debug(`Socket removed ${e}`)}throw 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 o=this.formatBroadcastData(e,t);n.map((e=>this.physicSend(e,o).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){return r(this,void 0,void 0,(function*(){yield this.apiGatewayManagement.deleteConnection({ConnectionId:e}).promise()}))}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=o([(0,a.Initable)(),i("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 o=this&&this.__decorate||function(e,t,n,o){var i,r=arguments.length,s=r<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,n):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,o);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(r<3?i(s):r>3?i(t,n,s):i(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},i=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,o){return new(n||(n=Promise))((function(i,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?i(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.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){this.redisClient.publish(this.socketChannelName,JSON.stringify({type:f.SEND,data:e}))}physicClose(){this.redisClient.publish(this.socketChannelName,JSON.stringify({type:f.CLOSE}))}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){super(t),this.socket=e,this.socketInfo=t,this.infoSaver=n}saveSocketInfo(){return r(this,void 0,void 0,(function*(){yield this.infoSaver(this.socketInfo)}))}physicSend(e){this.socket.send(JSON.stringify(e))}physicClose(e){this.socket.close(1e3,e&&JSON.stringify(e))}}let y=class LocalSocketManager extends u.AbstractServerSocketManager{constructor(e,t,n,o,i){super(e,n,t,o,i),this.authenticationRequired=e,this.redisServerUrl=t,this.logger=n,this.authProvider=o,this.authResolver=i,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),o=this.allSockets.find((e=>e.getId()===n));if(o){const t=JSON.parse(e);switch(t.type){case f.SEND:o.physicSend(t.data);break;case f.SAVE:o.socketInfo.channels=t.data,o.saveSocketInfo();break;case f.CLOSE:o.disconnect();break;default:this.logger.debug("Invalid remote command",t)}}}getUniqueDataChannelName(e){return`CHANNEL_DATA:${e}`}getSocketChannelKeyPrefix(){return"SOCKET_CHANNEL:"}getSocketInfoHashKey(){return"__SOCKET_INFO__"}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 o=yield n.addSocketToChannel.call(this,e,t),i=t.map((e=>e.name)).filter((e=>!this.subscribedChannels.includes(e)));return i.length&&(yield Promise.all(i.map((e=>this.channelSubClient.subscribe(this.getUniqueDataChannelName(e))))),this.subscribedChannels.push(...i)),o}))}removeSocketFromChannel(e,t){const n=Object.create(null,{removeSocketFromChannel:{get:()=>super.removeSocketFromChannel}});return r(this,void 0,void 0,(function*(){yield n.removeSocketFromChannel.call(this,e,t),yield Promise.all(t.map((e=>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(t,e,(e=>r(this,void 0,void 0,(function*(){yield this.redisClient.hset(this.getSocketInfoHashKey(),e.id,JSON.stringify(e))})))),o=this.getSocketChannelKey(e.id);return this.subClient.subscribe(o),this.allSockets.push(n),n}))}removeSocket(e){return r(this,void 0,void 0,(function*(){yield this.redisClient.hdel(this.getSocketInfoHashKey(),e);const t=this.getSocketChannelKey(e);this.subClient.unsubscribe(t),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"],o=(0,l.default)({url:t.url}),i=c.default.parse(decodeURIComponent(o.search||""));this.handle({method:a.SocketMethod.CONNECT,socketId:n,data:{queries:i,socket:e}}).catch((t=>{e.close(1e3,`${t.name}:${t.message}`)})),e.onmessage=e=>{this.handle({method:a.SocketMethod.MESSAGE,socketId:n,data:e.data&&JSON.parse(e.data)}).catch((e=>{this.logger.error(e)}))},e.onclose=()=>{this.handle({method:a.SocketMethod.DISCONNECT,socketId:n}).catch((e=>{this.logger.error(e)}))}}))}};y=o([(0,a.Initable)(),i("design:paramtypes",[Boolean,String,a.AbstractLogger,p.AbstractHttpAuthorizationProvider,Function])],y),t.LocalSocketManager=y},5537:function(e,t,n){var o=this&&this.__awaiter||function(e,t,n,o){return new(n||(n=Promise))((function(i,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?i(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.ClaireServer=void 0;const i=n(2318),r=n(137),s=n(4972);class ClaireServer extends i.ClaireApp{constructor(e,t,n){super(),this.logger=e,this.httpRequestHandler=t,this.socketManager=n,this.booted=!1}init(){return o(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,i.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 o=this&&this.__awaiter||function(e,t,n,o){return new(n||(n=Promise))((function(i,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?i(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))},i=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=i(n(6860)),a=i(n(3685)),d=i(n(3582)),l=i(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 o(this,void 0,void 0,(function*(){yield this.server.init(),yield this.injector.initInstances();const i=(0,s.default)(),c=a.default.createServer(i);return null===(t=this.socketManager)||void 0===t||t.configure(c),i.use((0,d.default)()),i.use(s.default.raw({limit:1024*((null===(n=this.config)||void 0===n?void 0:n.maxBodySizeKB)||4096)})),i.use((0,l.default)()),i.use(((e,t,n)=>{e.files&&(e.body||(e.body={}),Object.keys(e.files).forEach((t=>{e.body[t]=e.files[t]}))),n()})),i.use(s.default.urlencoded({extended:!1})),i.use(s.default.json()),i.all("*",((e,t)=>{(()=>o(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,o=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:o}}yield this.socketManager.handle(n).then((()=>{t.status(200).send()})).catch((e=>{var t;this.logger.debug("Handle error",e),null===(t=this.socketManager)||void 0===t||t.removeSocket(n.socketId).catch((e=>{this.logger.debug(e)}))}))}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},o=yield this.httpRequestHandler.handle(n);o.headers&&Object.keys(o.headers).forEach((e=>{t.set(e,o.headers[e])})),t.status(o.code).send(o.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 o=this&&this.__awaiter||function(e,t,n,o){return new(n||(n=Promise))((function(i,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?i(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.LambdaWrapper=void 0;const i=n(2318),r=n(767),s=n(5530),a=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,i.getServiceProvider)().getInjector(),this.socketManager=this.injector.resolveOptional(s.AbstractServerSocketManager),this.httpRequestHandler=this.injector.resolveOptional(r.AbstractHttpRequestHandler)}bootServer(){var e;return o(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){return o(this,void 0,void 0,(function*(){yield this.bootServer();const t=this.requestMapper(e);if(!t)return toApiGatewayFormat(400,"Cannot resolve event");if(t.method===i.HttpMethod.OPTIONS)return toApiGatewayFormat(200);try{if(Object.values(i.HttpMethod).includes(t.method)){if(!this.httpRequestHandler)throw i.ErrorBuilder.error(a.Errors.SYSTEM_ERROR,"Http request handler not found");const e={fullPath:t.rawPath,method:t.method,headers:t.headers,body:t.body},n=yield this.httpRequestHandler.handle(e);return toApiGatewayFormat(n.code,n.value)}if(!Object.values(i.SocketMethod).includes(t.method))throw i.ErrorBuilder.error(a.Errors.HTTP_REQUEST_ERROR,"Not allow request method: "+t.method);{if(!this.socketManager)throw i.ErrorBuilder.error(a.Errors.SYSTEM_ERROR,"Socket manager not found");const e={socketId:t.rawPath,method:t.method,data:t.body};yield this.socketManager.handle(e)}return toApiGatewayFormat(200)}catch(e){return toApiGatewayFormat(400,{name:e.name,message:e.message})}}))}}},9627:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},6721:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Errors=void 0;const o=n(2318);t.Errors=Object.assign(Object.assign({},o.Errors),{TFA_REQUIRED:"TFA_REQUIRED"})},889:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.lambdaRequestMapper=void 0;const o=n(2318);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===o.SocketMethod.CONNECT?{queries:e.queryStringParameters}:n}}return{method:e.requestContext.http.method.toLowerCase(),rawPath:`${e.rawPath}?${e.rawQueryString}`,body:e.body&&JSON.parse(e.body),headers:e.headers}}},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")},8311:e=>{e.exports=require("node-cron")},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")}},t={};var n=function __webpack_require__(n){var o=t[n];if(void 0!==o)return o.exports;var i=t[n]={exports:{}};return e[n].call(i.exports,i,i.exports,__webpack_require__),i.exports}(341);return n})()));
|