@clairejs/server 2.3.10 → 2.3.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,5 +1,9 @@
1
1
  ## Change Log
2
2
 
3
+ #### 2.3.11:
4
+
5
+ - export CrudService
6
+
3
7
  #### 2.3.10:
4
8
 
5
9
  - Array & Object model field persist & parse
package/dist/index.d.ts CHANGED
@@ -33,4 +33,5 @@ import { IPrincipal } from "./http/security/IPrincipal";
33
33
  import { IServerSocket } from "./socket/IServerSocket";
34
34
  import { ServerGlobalStore } from "./system/ServerGlobalStore";
35
35
  import { AbstractFileUploadHandler } from "./system/AbstractFileUploadHandler";
36
- export { FileLogMedium, Controller, Endpoint, Socket, Get, Del, Put, Post, Validator, Transactional, HttpRequest, HttpResponse, AbstractHttpController, AbstractHttpRequestHandler, CrudHttpController, DefaultHttpRequestHandler, MountedEndpointInfo, EndpointMetadata, AbstractHttpMiddleware, RequestOptions, ResponseValues, AbstractServerSocketManager, LocalSocketManager, AwsSocketManager, IServerSocket, OpenAccess, AccessCondition, IPrincipal, AbstractAccessCondition, AbstractHttpAuthorizationProvider, FilterModelFieldAccessCondition, OwnedResourceAccessCondition, AbstractDatabaseAdapter, AbstractDatabaseMigrator, TransactionLink, DefaultSqlDatabaseAdapter, DefaultSqlDatabaseMigrator, SqlProvider, AbstractFileUploadHandler, ServerGlobalStore, ClaireServer, AbstractService, ExpressWrapper, LambdaWrapper, };
36
+ import { CrudService } from "./http/controller/CrudService";
37
+ export { FileLogMedium, Controller, Endpoint, Socket, Get, Del, Put, Post, Validator, Transactional, HttpRequest, HttpResponse, AbstractHttpController, AbstractHttpRequestHandler, CrudHttpController, DefaultHttpRequestHandler, MountedEndpointInfo, EndpointMetadata, AbstractHttpMiddleware, RequestOptions, ResponseValues, AbstractServerSocketManager, LocalSocketManager, AwsSocketManager, IServerSocket, OpenAccess, AccessCondition, IPrincipal, AbstractAccessCondition, AbstractHttpAuthorizationProvider, FilterModelFieldAccessCondition, OwnedResourceAccessCondition, AbstractDatabaseAdapter, AbstractDatabaseMigrator, TransactionLink, DefaultSqlDatabaseAdapter, DefaultSqlDatabaseMigrator, SqlProvider, CrudService, AbstractFileUploadHandler, ServerGlobalStore, ClaireServer, AbstractService, ExpressWrapper, LambdaWrapper, };
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 r in n)("object"==typeof exports?exports:e)[r]=n[r]}}(global,(function(){return function(e){var t={};function __webpack_require__(n){if(t[n])return t[n].exports;var r=t[n]={i:n,l:!1,exports:{}};return e[n].call(r.exports,r,r.exports,__webpack_require__),r.l=!0,r.exports}return __webpack_require__.m=e,__webpack_require__.c=t,__webpack_require__.d=function(e,t,n){__webpack_require__.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},__webpack_require__.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},__webpack_require__.t=function(e,t){if(1&t&&(e=__webpack_require__(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(__webpack_require__.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var r in e)__webpack_require__.d(n,r,function(t){return e[t]}.bind(null,r));return n},__webpack_require__.n=function(e){var t=e&&e.__esModule?function getDefault(){return e.default}:function getModuleExports(){return e};return __webpack_require__.d(t,"a",t),t},__webpack_require__.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},__webpack_require__.p="",__webpack_require__(__webpack_require__.s=25)}([function(e,t){e.exports=require("@clairejs/core")},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractHttpRequestHandler=void 0;t.AbstractHttpRequestHandler=class AbstractHttpRequestHandler{resolverMountPoint(e,t){if(!e)return"";const n=[];return n.push(...t),n.reduce(((e,t)=>`${e}/${t}`),"").replace(/(\/)\/+/g,"$1")}}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getDirectFields=t.getFieldByName=t.getTransactionFromContext=void 0;const r=n(0),o=n(7);t.getTransactionFromContext=e=>{const t=e[o.INJECTED_TRANSACTION];if(!t)throw new r.ClaireError(r.Errors.SYSTEM_ERROR,"Cannot get transaction from current context");return t},t.getFieldByName=(e,t)=>e.fields.find((e=>e.name===t)),t.getDirectFields=e=>e.fields.filter((e=>!e.hasManyProps))},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractHttpAuthorizationProvider=void 0;t.AbstractHttpAuthorizationProvider=class AbstractHttpAuthorizationProvider{}},function(e,t,n){"use strict";var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function fulfilled(e){try{step(r.next(e))}catch(e){i(e)}}function rejected(e){try{step(r.throw(e))}catch(e){i(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((r=r.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractServerSocketManager=void 0;const o=n(23);t.AbstractServerSocketManager=class AbstractServerSocketManager{constructor(e){this.logger=e}getAllAliveSockets(){return r(this,void 0,void 0,(function*(){const e=yield this.getAllSockets(),t=Date.now();return e.filter((e=>!e.isAuthorized()&&t-e.createdTime()>12e4)).forEach((e=>e.disconnect().catch((e=>this.logger.error(e))))),e.filter((e=>e.isOpen()&&e.isAuthorized()))}))}getSocketsByChannel(e){return r(this,void 0,void 0,(function*(){return(yield this.getAllAliveSockets()).filter((t=>t.getChannels().includes(e))).map((t=>new o.ServerSocket(e,t)))}))}}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HttpRequest=void 0;const r=n(0);t.HttpRequest=class HttpRequest{constructor(e,t){this.valueHolder={},this.method=e.method,this.pathName=e.pathName,this.headers=e.headers||{},this.hash=e.hash||"",this.socket=e.socket,this.params=e.params||{},(null==t?void 0:t.paramsDto)&&(this.params=r.validateDTO(this.params,t.paramsDto)),this.query=e.query||{},(null==t?void 0:t.queryDto)&&(this.query=r.validateDTO(this.jsonParsing(this.query,t.queryDto),t.queryDto)),this.body=e.body||{},t&&(t.httpMethod===r.HttpMethod.POST||t.httpMethod===r.HttpMethod.PUT)&&t.bodyDto&&(this.body=r.validateDTO(this.body||{},t.bodyDto))}jsonParsing(e,t){const n=Object.assign({},e);for(const o of t.fields)try{(void 0!==e[o.name]||o.isRequired)&&(n[o.name]=JSON.parse(e[o.name]))}catch(e){throw new r.ClaireError(r.Errors.BAD_REQUEST,`JSON parsing failed for field ${o.name}`)}return n}getAuthInfo(){return this.authInfo}setAuthInfo(e){this.authInfo=e}getHeaders(){return this.headers}getMethod(){return this.method}getHash(){return this.hash}getPathName(){return this.pathName}getValue(e){return this.valueHolder[e]}setValue(e,t){this.valueHolder[e]=t}getParams(){return this.params}getQuery(){return this.query}getBody(){return this.body}getSocket(){if(!this.socket)throw new r.ClaireError(r.Errors.SYSTEM_ERROR,"Socket not found for current request");return this.socket}}},function(e,t,n){"use strict";var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function fulfilled(e){try{step(r.next(e))}catch(e){i(e)}}function rejected(e){try{step(r.throw(e))}catch(e){i(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((r=r.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractHttpController=void 0;const o=n(0),i=n(2);t.AbstractHttpController=class AbstractHttpController{isEndpoint(e){return!!(e.httpMethod||void 0!==e.openAccess||e.queryDto||e.bodyDto||e.paramsDto||e.accessConditions)}getCurrentTransaction(){return r(this,void 0,void 0,(function*(){return i.getTransactionFromContext(this)}))}getEndpointMetadata(){const e=o.getObjectMetadata(this.constructor);return e?e.fields.filter((e=>this.isEndpoint(e))).map((t=>Object.assign(Object.assign({},t),{permissionGroup:e.permissionGroup}))):[]}}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ExitCode=t.INJECTED_TRANSACTION=void 0,t.INJECTED_TRANSACTION="__INJECTED_TRANSACTION__",t.ExitCode={SIGTERM_INTERUPTION:-1,SIGINT_INTERUPTION:-2,UNCAUGHT_EXCEPTION:-3,UNHANDLED_REJECTION:-4}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractAccessCondition=void 0;t.AbstractAccessCondition=class AbstractAccessCondition{}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TransactionLink=void 0,function(e){e.CREATE_NEW="create_new",e.INHERIT_OR_CREATE="inherit_or_create",e.INHERIT_OR_THROW="inherit_or_throw"}(t.TransactionLink||(t.TransactionLink={}))},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SqlProvider=t.NoSqlProvider=void 0,function(e){e.MONGODB="mongodb",e.DYNAMODB="dynamodb"}(t.NoSqlProvider||(t.NoSqlProvider={})),function(e){e.MYSQL="mysql",e.POSTGRES="postgres"}(t.SqlProvider||(t.SqlProvider={}))},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HttpResponse=void 0;t.HttpResponse=class HttpResponse{constructor(){this.code=200,this.headers={},this.cookies={}}setStatus(e){this.code=e}getStatus(){return this.code}setHeaders(e,t){this.headers[e]=t}getHeaders(){return this.headers}setCookie(e,t){this.cookies[e]=t}getCookies(){return this.cookies}}},function(e,t){e.exports=require("fs")},function(e,t){e.exports=require("path")},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AccessCondition=t.OpenAccess=t.Validator=t.Get=t.Del=t.Put=t.Post=t.Socket=t.Endpoint=t.Controller=void 0;const r=n(0);t.Controller=e=>t=>{r.getServiceProvider().register(t,"singleton");r.initObjectMetadata(t.prototype).permissionGroup=null==e?void 0:e.permissionGroup},t.Endpoint=e=>(t,n)=>{const o=r.initFieldMetadata(t,n);o.httpMethod=e.method,o.url=e.url},t.Socket=e=>(n,o)=>{t.Endpoint({method:r.SocketMethod.MESSAGE,url:e})(n,o)},t.Post=e=>(n,o)=>{t.Endpoint({method:r.HttpMethod.POST,url:e})(n,o)},t.Put=e=>(n,o)=>{t.Endpoint({method:r.HttpMethod.PUT,url:e})(n,o)},t.Del=e=>(n,o)=>{t.Endpoint({method:r.HttpMethod.DEL,url:e})(n,o)},t.Get=e=>(n,o)=>{t.Endpoint({method:r.HttpMethod.GET,url:e})(n,o)},t.Validator=e=>(t,n)=>{const o=r.initFieldMetadata(t,n);e.params&&(o.paramsDto=r.getObjectMetadata(e.params)),e.query&&(o.queryDto=r.getObjectMetadata(e.query)),e.body&&(o.bodyDto=r.getObjectMetadata(e.body))},t.OpenAccess=()=>(e,t)=>{r.initFieldMetadata(e,t).openAccess=!0},t.AccessCondition=e=>(t,n)=>{r.initFieldMetadata(t,n).accessConditions=e}},function(e,t,n){"use strict";var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function fulfilled(e){try{step(r.next(e))}catch(e){i(e)}}function rejected(e){try{step(r.throw(e))}catch(e){i(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((r=r.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.FilterModelFieldAccessCondition=void 0;const o=n(0),i=n(8);t.FilterModelFieldAccessCondition=(e,t)=>{const n=class extends i.AbstractAccessCondition{resolveRequestedConditionValue(e){return r(this,void 0,void 0,(function*(){return t(e)}))}getConditionMetadata(){return{name:"filter_model_field",valueType:o.AccessConditionValueType.CHOICES,valueConstraint:o.getObjectMetadata(e).fields.map((e=>e.name))}}validate(e,t){return r(this,void 0,void 0,(function*(){return!!e&&e.every((e=>t.includes(e)))}))}};return o.getServiceProvider().register(n),n}},function(e,t,n){"use strict";var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function fulfilled(e){try{step(r.next(e))}catch(e){i(e)}}function rejected(e){try{step(r.throw(e))}catch(e){i(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((r=r.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.Transactional=void 0;const o=n(0),i=n(7),s=n(9),a=n(17),getInjectedDatabaseAdapter=()=>{const e=o.getGlobalStore().databaseAdapter;if(!e)throw new o.ClaireError(o.Errors.SYSTEM_ERROR,"Database adapter does not present in server store");return e};t.Transactional=e=>(t,n,d)=>{const c=o.initObjectMetadata(t);o.initFieldMetadata(t,n),c.transactional=!0;const l=d.value;d.value=function(...d){return r(this,void 0,void 0,(function*(){const r=this;let c,u,h;try{c=yield r.getCurrentTransaction()}catch(e){}switch(e){case s.TransactionLink.CREATE_NEW:u=!0,h=yield getInjectedDatabaseAdapter().createTransaction();break;case s.TransactionLink.INHERIT_OR_CREATE:u=!c,h=c||(yield getInjectedDatabaseAdapter().createTransaction());break;case s.TransactionLink.INHERIT_OR_THROW:if(u=!1,!c)throw new o.ClaireError(o.Errors.SYSTEM_ERROR,`No transaction to inherit when executing ${t.constructor.name}:${n}`);h=c}const p=Object.assign(Object.create(r),r),f=Object.keys(p).filter((e=>{var t;return null===(t=o.getObjectMetadata(p[e].constructor))||void 0===t?void 0:t.transactional}));for(const e of f){const t=p[e],n=Object.assign(Object.create(t),t,{[i.INJECTED_TRANSACTION]:h});p[e]=n}try{Object.assign(p,{[i.INJECTED_TRANSACTION]:h});let e=yield l.call(p,...d);return h.getState()===a.TransactionState.EXECUTING&&u&&(yield h.commit()),e}catch(e){throw h.getState()===a.TransactionState.EXECUTING&&u&&(yield h.rollback()),new o.ClaireError(e.name||o.Errors.TRANSACTION_ERROR,e.message)}}))},Object.defineProperty(d.value,"name",{value:n})}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TransactionState=void 0,function(e){e.EXECUTING="executing",e.COMMITTED="commited",e.ROLLED_BACK="rolled_back"}(t.TransactionState||(t.TransactionState={}))},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractFileUploadHandler=void 0;t.AbstractFileUploadHandler=class AbstractFileUploadHandler{}},function(e,t,n){"use strict";var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function fulfilled(e){try{step(r.next(e))}catch(e){i(e)}}function rejected(e){try{step(r.throw(e))}catch(e){i(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((r=r.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractDatabaseAdapter=void 0;const o=n(0);t.AbstractDatabaseAdapter=class AbstractDatabaseAdapter{constructor(){this.modelMetadata=[],this.models=[],this.modelConnections={}}init(){return r(this,void 0,void 0,(function*(){this.models=(o.getGlobalStore().models||[]).slice(),this.modelMetadata=this.models.map((e=>o.getObjectMetadata(e))),this.modelConnections=this.modelMetadata.reduce(((e,t)=>Object.assign(e,{[t.id]:{connection:void 0}})),{})}))}exit(){}}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractDatabaseMigrator=void 0;t.AbstractDatabaseMigrator=class AbstractDatabaseMigrator{}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HttpEndpoint=void 0;t.HttpEndpoint=class HttpEndpoint{getEndpointId(){return`${this.httpMethod}:${this.mount}`}}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractHttpMiddleware=void 0;t.AbstractHttpMiddleware=class AbstractHttpMiddleware{}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ServerSocket=void 0;t.ServerSocket=class ServerSocket{constructor(e,t){this.channel=e,this.socket=t}getId(){return this.socket.getId()}isAuthorized(){return this.socket.isAuthorized()}getAuthInfo(){return this.socket.getAuthInfo()}isOpen(){return this.socket.isOpen()}send(e){return this.socket.send({channel:this.channel,data:e})}disconnect(e){return this.socket.disconnect(e)}}},function(e,t,n){"use strict";var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function fulfilled(e){try{step(r.next(e))}catch(e){i(e)}}function rejected(e){try{step(r.throw(e))}catch(e){i(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((r=r.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractServerSocket=void 0;const o=n(0),i=n(5),s=n(11),a=n(21),d=n(23);t.AbstractServerSocket=class AbstractServerSocket{constructor(e,t,n){this.logger=e,this.requestHandler=t,this.authorizationProvider=n,this.socketInfo={}}addChannels(e){return r(this,void 0,void 0,(function*(){this.socketInfo.channels=(this.socketInfo.channels||[]).concat(e)}))}removeChannels(e){return r(this,void 0,void 0,(function*(){this.socketInfo.channels=(this.socketInfo.channels||[]).filter((t=>!e.includes(t)))}))}isOpen(){return!!this.socketInfo.isOpen}createdTime(){return this.socketInfo.createdAt||0}isAuthorized(){return!!this.socketInfo.authorized}getAuthInfo(){return this.socketInfo.authInfo}getId(){return this.socketInfo.id||""}getChannels(){var e;return(null===(e=this.socketInfo.channels)||void 0===e?void 0:e.slice())||[]}send(e){return r(this,void 0,void 0,(function*(){yield this.sendToSocket(o.SocketChannels.MESSAGE_CHANNEL,e)}))}disconnect(e){return r(this,void 0,void 0,(function*(){e&&this.sendToSocket(o.SocketChannels.DISCONNECTION_CHANNEL,e).catch((e=>this.logger.error(e))),this.physicDisconnect().catch((e=>this.logger.error(e)))}))}authorize(e){return r(this,void 0,void 0,(function*(){this.socketInfo.authorized=!0,this.socketInfo.authInfo=e,yield this.setOpen(!0),yield this.sendToSocket(o.SocketChannels.AUTHENTICATION_CHANNEL,{socketId:this.getId()})}))}sendToSocket(e,t){var n;return r(this,void 0,void 0,(function*(){null===(n=this.logger)||void 0===n||n.debug("Physic send",e,t),yield this.physicSend(JSON.stringify({channel:e,message:t}))}))}handleDisconnect(){return r(this,void 0,void 0,(function*(){if(yield this.setOpen(!1),this.isAuthorized())for(const e of this.getChannels())yield this.requestHandler.handle({method:o.SocketMethod.MESSAGE,rawPath:e,body:{},socket:this})}))}handleMessage(e,t){var n,c,l,u,h,p,f;return r(this,void 0,void 0,(function*(){switch(null===(n=this.logger)||void 0===n||n.debug("Handle message",e,t),e){case o.SocketChannels.PING_PONG_CHANNEL:yield this.sendToSocket(o.SocketChannels.PING_PONG_CHANNEL);break;case o.SocketChannels.AUTHENTICATION_CHANNEL:{const e=t,n=new i.HttpRequest({method:o.SocketMethod.MESSAGE,pathName:"",headers:{authorization:e.authorizationData}}),r=new s.HttpResponse;for(const e of this.requestHandler.getMiddleware())yield e.intercept(n,r);try{const e=yield this.authorizationProvider.resolvePrincipal(n);yield this.authorize(e)}catch(e){yield this.disconnect(e)}}break;case o.SocketChannels.CHANNEL_LEAVE_REQUEST:{const e=t;let n,r;try{yield this.removeChannels(e.channels),n=!0}catch(e){n=!1,r=e}yield this.sendToSocket(o.SocketChannels.CHANNEL_LEAVE_REQUEST,{success:n,channels:e.channels,error:r})}break;case o.SocketChannels.CHANNEL_JOIN_REQUEST:{const e=t;if(!this.isAuthorized())return;const n=e.channels.filter((e=>!this.getChannels().includes(e)));let r,s=!0;for(const e of n){const t=new a.HttpEndpoint;t.httpMethod=o.SocketMethod.MESSAGE,t.mount=`/${e}`;const n=(o.getGlobalStore().mountedEndpointInfo||[]).find((e=>e.endpoint.getEndpointId()===t.getEndpointId()));if(!n){r=new o.ClaireError(o.Errors.SOCKET_ERROR,`Channel not found: ${e}`),s=!1;break}const d=new i.HttpRequest({method:o.SocketMethod.MESSAGE,pathName:`/${e}`});try{yield this.authorizationProvider.authorize(this.socketInfo.authInfo,d,n)}catch(t){r=new o.ClaireError(o.Errors.SOCKET_ERROR,`Not permitted to join: ${e}`),s=!1;break}}if(null===(c=this.logger)||void 0===c||c.debug("Sending channel connection success message"),yield this.sendToSocket(o.SocketChannels.CHANNEL_JOIN_REQUEST,{success:s,channels:e.channels,error:r}),!s)return;null===(l=this.logger)||void 0===l||l.debug("Not authenticated channels",n,e.channels),yield this.addChannels(n),null===(u=this.logger)||void 0===u||u.debug("Invoking socket connection handler");for(const t of e.channels){const e=new d.ServerSocket(t,this);null===(h=this.logger)||void 0===h||h.debug("Invoking",t),null===(p=this.logger)||void 0===p||p.debug("Socket status",e.getId(),e.isOpen()),yield this.requestHandler.handle({method:o.SocketMethod.MESSAGE,rawPath:t,socket:e}),null===(f=this.logger)||void 0===f||f.debug("Invoke success",t)}}break;case o.SocketChannels.MESSAGE_CHANNEL:{if(!this.isAuthorized())return;const e=t;if(!this.getChannels().includes(e.channel))return;yield this.requestHandler.handle({method:o.SocketMethod.MESSAGE,rawPath:e.channel,socket:new d.ServerSocket(e.channel,this),body:e.data})}break;case o.SocketChannels.DISCONNECTION_CHANNEL:yield this.handleDisconnect(),yield this.disconnect()}}))}}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LambdaWrapper=t.ExpressWrapper=t.AbstractService=t.ClaireServer=t.AbstractFileUploadHandler=t.SqlProvider=t.DefaultSqlDatabaseMigrator=t.DefaultSqlDatabaseAdapter=t.TransactionLink=t.AbstractDatabaseMigrator=t.AbstractDatabaseAdapter=t.OwnedResourceAccessCondition=t.FilterModelFieldAccessCondition=t.AbstractHttpAuthorizationProvider=t.AbstractAccessCondition=t.AccessCondition=t.OpenAccess=t.AwsSocketManager=t.LocalSocketManager=t.AbstractServerSocketManager=t.AbstractHttpMiddleware=t.DefaultHttpRequestHandler=t.CrudHttpController=t.AbstractHttpRequestHandler=t.AbstractHttpController=t.HttpResponse=t.HttpRequest=t.Transactional=t.Validator=t.Post=t.Put=t.Del=t.Get=t.Socket=t.Endpoint=t.Controller=t.FileLogMedium=void 0;const r=n(26);Object.defineProperty(t,"FileLogMedium",{enumerable:!0,get:function(){return r.FileLogMedium}});const o=n(14);Object.defineProperty(t,"Controller",{enumerable:!0,get:function(){return o.Controller}}),Object.defineProperty(t,"Endpoint",{enumerable:!0,get:function(){return o.Endpoint}}),Object.defineProperty(t,"Validator",{enumerable:!0,get:function(){return o.Validator}}),Object.defineProperty(t,"AccessCondition",{enumerable:!0,get:function(){return o.AccessCondition}}),Object.defineProperty(t,"OpenAccess",{enumerable:!0,get:function(){return o.OpenAccess}}),Object.defineProperty(t,"Get",{enumerable:!0,get:function(){return o.Get}}),Object.defineProperty(t,"Del",{enumerable:!0,get:function(){return o.Del}}),Object.defineProperty(t,"Put",{enumerable:!0,get:function(){return o.Put}}),Object.defineProperty(t,"Post",{enumerable:!0,get:function(){return o.Post}}),Object.defineProperty(t,"Socket",{enumerable:!0,get:function(){return o.Socket}});const i=n(5);Object.defineProperty(t,"HttpRequest",{enumerable:!0,get:function(){return i.HttpRequest}});const s=n(6);Object.defineProperty(t,"AbstractHttpController",{enumerable:!0,get:function(){return s.AbstractHttpController}});const a=n(27);Object.defineProperty(t,"CrudHttpController",{enumerable:!0,get:function(){return a.CrudHttpController}});const d=n(29);Object.defineProperty(t,"ClaireServer",{enumerable:!0,get:function(){return d.ClaireServer}});const c=n(16);Object.defineProperty(t,"Transactional",{enumerable:!0,get:function(){return c.Transactional}});const l=n(9);Object.defineProperty(t,"TransactionLink",{enumerable:!0,get:function(){return l.TransactionLink}});const u=n(30);Object.defineProperty(t,"DefaultSqlDatabaseAdapter",{enumerable:!0,get:function(){return u.DefaultSqlDatabaseAdapter}});const h=n(33);Object.defineProperty(t,"DefaultSqlDatabaseMigrator",{enumerable:!0,get:function(){return h.DefaultSqlDatabaseMigrator}});const p=n(10);Object.defineProperty(t,"SqlProvider",{enumerable:!0,get:function(){return p.SqlProvider}});const f=n(35);Object.defineProperty(t,"DefaultHttpRequestHandler",{enumerable:!0,get:function(){return f.DefaultHttpRequestHandler}});const g=n(19);Object.defineProperty(t,"AbstractDatabaseAdapter",{enumerable:!0,get:function(){return g.AbstractDatabaseAdapter}});const y=n(39);Object.defineProperty(t,"AbstractService",{enumerable:!0,get:function(){return y.AbstractService}});const m=n(8);Object.defineProperty(t,"AbstractAccessCondition",{enumerable:!0,get:function(){return m.AbstractAccessCondition}});const v=n(3);Object.defineProperty(t,"AbstractHttpAuthorizationProvider",{enumerable:!0,get:function(){return v.AbstractHttpAuthorizationProvider}});const b=n(15);Object.defineProperty(t,"FilterModelFieldAccessCondition",{enumerable:!0,get:function(){return b.FilterModelFieldAccessCondition}});const C=n(1);Object.defineProperty(t,"AbstractHttpRequestHandler",{enumerable:!0,get:function(){return C.AbstractHttpRequestHandler}});const M=n(22);Object.defineProperty(t,"AbstractHttpMiddleware",{enumerable:!0,get:function(){return M.AbstractHttpMiddleware}});const O=n(11);Object.defineProperty(t,"HttpResponse",{enumerable:!0,get:function(){return O.HttpResponse}});const _=n(40);Object.defineProperty(t,"ExpressWrapper",{enumerable:!0,get:function(){return _.ExpressWrapper}});const S=n(45);Object.defineProperty(t,"LambdaWrapper",{enumerable:!0,get:function(){return S.LambdaWrapper}});const A=n(20);Object.defineProperty(t,"AbstractDatabaseMigrator",{enumerable:!0,get:function(){return A.AbstractDatabaseMigrator}});const T=n(4);Object.defineProperty(t,"AbstractServerSocketManager",{enumerable:!0,get:function(){return T.AbstractServerSocketManager}});const w=n(46);Object.defineProperty(t,"LocalSocketManager",{enumerable:!0,get:function(){return w.LocalSocketManager}});const P=n(48);Object.defineProperty(t,"AwsSocketManager",{enumerable:!0,get:function(){return P.AwsSocketManager}});const j=n(51);Object.defineProperty(t,"OwnedResourceAccessCondition",{enumerable:!0,get:function(){return j.OwnedResourceAccessCondition}});const E=n(18);Object.defineProperty(t,"AbstractFileUploadHandler",{enumerable:!0,get:function(){return E.AbstractFileUploadHandler}})},function(e,t,n){"use strict";var r,o=this&&this.__decorate||function(e,t,n,r){var o,i=arguments.length,s=i<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(i<3?o(s):i>3?o(t,n,s):o(t,n))||s);return i>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)},s=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function fulfilled(e){try{step(r.next(e))}catch(e){i(e)}}function rejected(e){try{step(r.throw(e))}catch(e){i(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((r=r.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(12)),c=a(n(13)),l=n(0);let u=r=class FileLogMedium{constructor(e){const t=e.separated?r.levels.map((t=>c.default.join(e.destination,t+".log"))):[e.destination];this.destination=t.map((e=>(d.default.existsSync(c.default.dirname(e))||d.default.mkdirSync(c.default.dirname(e),{recursive:!0}),d.default.openSync(e,"a")))),this.separated=!!e.separated}init(){return s(this,void 0,void 0,(function*(){}))}exit(){this.destination.forEach((e=>d.default.closeSync(e)))}write(e,t){const n=this.separated?this.destination[r.levels.indexOf(e)]:0;d.default.appendFileSync(n,t)}};u.levels=Object.values(l.LogLevel),u=r=o([l.Initable(),i("design:paramtypes",[Object])],u),t.FileLogMedium=u},function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var o,i=arguments.length,s=i<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(i<3?o(s):i>3?o(t,n,s):o(t,n))||s);return i>3&&s&&Object.defineProperty(t,n,s),s},o=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},i=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function fulfilled(e){try{step(r.next(e))}catch(e){i(e)}}function rejected(e){try{step(r.throw(e))}catch(e){i(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((r=r.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.CrudHttpController=void 0;const s=n(0),a=n(15),d=n(5),c=n(16),l=n(9),u=n(14),h=n(6),p=n(28),f=n(3);class CrudHttpController extends h.AbstractHttpController{constructor(e,t){super();const n=s.getObjectMetadata(e);this.model=s.getModelById(n.id),this.modelMetadata=s.getObjectMetadata(this.model),s.getGlobalStore().databaseAdapter=t}getMountedUrl(e){return`/${this.modelMetadata.id}${e?"/"+e:""}`}static queryFieldDto(e){class FieldsDto{}const t={fields:CrudHttpController.getRequestQueryFieldFromModel(e)},n={name:"fields"};return n.dataType=s.DataType.OBJECT,s.setObjectMetadata(FieldsDto,t),n.objectTypeConstructor=FieldsDto,n}static queryOpsDto(e){class OpsDto{}const t={name:"ops"};return t.dataType=s.DataType.OBJECT,s.setObjectMetadata(OpsDto,{fields:[]}),t.objectTypeConstructor=OpsDto,t}static projectionFieldDto(e){const t={name:"projection"};return t.dataType=s.DataType.ARRAY,t.vectorProps={superSet:e.fields.map((e=>e.name)),allowDuplicated:!1,minLength:1,elementDataType:s.DataType.STRING},t}static getBodyDtoRecordClass(e,t,n){class InstanceDto{}const r={fields:[],strict:!0},o=e.fields.filter((e=>!e.serverValue||e.serverValue&&e.primaryKeyProps&&!t&&!n)),i=e.fields.filter((e=>!!e.hasManyProps));return r.fields.push(...o.map((e=>Object.assign(Object.assign({},e),{isRequired:t?e.isRequired:t}))),...i.map((e=>({name:e.name,dataType:s.DataType.ARRAY,vectorProps:{elementDataType:s.DataType.OBJECT,minLength:0},objectTypeConstructor:CrudHttpController.getBodyDtoRecordClass(s.getObjectMetadata(s.getModelById(e.hasManyProps.id)),t,!1)})))),s.setObjectMetadata(InstanceDto,r),InstanceDto}static getRequestQueryFieldFromModel(e){return e.fields.map((e=>{const t={};if(t.name=e.name,t.isRequired=!1,e.primaryKeyProps||e.foreignKeyProps)t.dataType=s.DataType.ARRAY,t.vectorProps={elementDataType:e.dataType,allowDuplicated:!1,minLength:1};else if(e.enum)t.dataType=s.DataType.ARRAY,t.vectorProps={superSet:e.enum,allowDuplicated:!1,minLength:1,elementDataType:e.dataType};else switch(e.dataType){case s.DataType.STRING:t.dataType=s.DataType.STRING;break;case s.DataType.NUMBER:t.dataType=s.DataType.OBJECT,t.objectTypeConstructor=s.RangeQueryDto}return t}))}getAuthProvider(){return i(this,void 0,void 0,(function*(){if(void 0===this.authProvider){const e=s.getServiceProvider().getInjector();this.authProvider=e.resolveOptional(f.AbstractHttpAuthorizationProvider)||null,yield e.initInstances()}return this.authProvider}))}createManyEndpoinMetadata(){const e={};return e.httpMethod=s.HttpMethod.POST,e.url=this.getMountedUrl(),e.name=CrudHttpController.prototype.createMany.name,e.displayName="createMany"+this.model.name,e.bodyDto=CrudHttpController.getCreateManyBodyValidator(this.modelMetadata),e}getManyEndpointMetadata(){const e={};return e.httpMethod=s.HttpMethod.GET,e.url=this.getMountedUrl(),e.name=CrudHttpController.prototype.getMany.name,e.displayName="getAll"+this.model.name,e.queryDto=CrudHttpController.getGetManyQueryValidator(this.modelMetadata),e.accessConditions=[a.FilterModelFieldAccessCondition(this.model,(e=>e.getQuery().projection))],e}updateManyEndpoinMetadata(){const e={};return e.httpMethod=s.HttpMethod.PUT,e.url=this.getMountedUrl(),e.name=CrudHttpController.prototype.updateMany.name,e.displayName="update"+this.model.name,e.queryDto=CrudHttpController.getUpdateManyQueryValidator(this.modelMetadata),e.bodyDto=CrudHttpController.getUpdateManyBodyValidator(this.modelMetadata),e.accessConditions=[a.FilterModelFieldAccessCondition(this.model,(e=>Object.keys(e.getBody().update)))],e}deleteManyEndpoinMetadata(){const e={};return e.httpMethod=s.HttpMethod.DEL,e.url=this.getMountedUrl(),e.name=CrudHttpController.prototype.deleteMany.name,e.displayName="delete"+this.model.name,e.queryDto=CrudHttpController.getUpdateManyQueryValidator(this.modelMetadata),e}static getCreateManyBodyValidator(e){const t={fields:[],strict:!0},n={name:"records"};return n.dataType=s.DataType.ARRAY,n.isRequired=!0,n.vectorProps={elementDataType:s.DataType.OBJECT,minLength:0},n.objectTypeConstructor=CrudHttpController.getBodyDtoRecordClass(e,!0,!0),t.fields.push(n),t}static getGetManyQueryValidator(e){const t={fields:[CrudHttpController.queryFieldDto(e),CrudHttpController.queryOpsDto(e)]},n={name:"search"};n.dataType=s.DataType.STRING,t.fields.push(n),t.fields.push(CrudHttpController.projectionFieldDto(e));const r={name:"order"};r.dataType=s.DataType.ARRAY,r.vectorProps={elementDataType:s.DataType.OBJECT,minLength:1};class SortElementDto{}const o={fields:[],strict:!0};o.fields.push(...e.fields.map((e=>{const t={};return t.name=e.name,t.isRequired=!1,t.dataType=s.DataType.OBJECT,t.enum=Object.values(s.OrderDirection),t}))),s.setObjectMetadata(SortElementDto,o),r.objectTypeConstructor=SortElementDto,t.fields.push(r);const i={name:"limit"};i.dataType=s.DataType.NUMBER,i.rangeProps={min:1},t.fields.push(i);const a={name:"page"};return a.dataType=s.DataType.NUMBER,a.rangeProps={min:1},t.fields.push(a),t}static getUpdateManyQueryValidator(e){const t={name:"returning"};return t.dataType=s.DataType.BOOLEAN,t.isRequired=!1,{fields:[t,CrudHttpController.queryFieldDto(e),CrudHttpController.queryOpsDto(e)]}}static getUpdateManyBodyValidator(e){const t={fields:[],strict:!0},n={name:"update"};return n.dataType=s.DataType.OBJECT,n.objectTypeConstructor=CrudHttpController.getBodyDtoRecordClass(e,!1,!0),t.fields.push(n),t}static createManyBodyValidator(e){class Validator{}return s.setObjectMetadata(Validator,CrudHttpController.getCreateManyBodyValidator(s.getObjectMetadata(e))),Validator}static getManyQueryValidator(e){class Validator{}return s.setObjectMetadata(Validator,CrudHttpController.getGetManyQueryValidator(s.getObjectMetadata(e))),Validator}static updateManyQueryValidator(e){class Validator{}return s.setObjectMetadata(Validator,CrudHttpController.getUpdateManyQueryValidator(s.getObjectMetadata(e))),Validator}static updateManyBodyValidator(e){class Validator{}return s.setObjectMetadata(Validator,CrudHttpController.getUpdateManyBodyValidator(s.getObjectMetadata(e))),Validator}getEndpointMetadata(){var e,t,n,r;const o=super.getEndpointMetadata(),i=[];(null===(e=this.modelMetadata.ignoreCrud)||void 0===e?void 0:e.includes(s.HttpMethod.GET))?o.splice(o.findIndex((e=>e.name===CrudHttpController.prototype.getMany.name)),1):i.push(this.getManyEndpointMetadata()),(null===(t=this.modelMetadata.ignoreCrud)||void 0===t?void 0:t.includes(s.HttpMethod.POST))?o.splice(o.findIndex((e=>e.name===CrudHttpController.prototype.createMany.name)),1):i.push(this.createManyEndpoinMetadata()),(null===(n=this.modelMetadata.ignoreCrud)||void 0===n?void 0:n.includes(s.HttpMethod.PUT))?o.splice(o.findIndex((e=>e.name===CrudHttpController.prototype.updateMany.name)),1):i.push(this.updateManyEndpoinMetadata()),(null===(r=this.modelMetadata.ignoreCrud)||void 0===r?void 0:r.includes(s.HttpMethod.DEL))?o.splice(o.findIndex((e=>e.name===CrudHttpController.prototype.deleteMany.name)),1):i.push(this.deleteManyEndpoinMetadata());for(const e of i){const t=o.findIndex((t=>t.httpMethod===e.httpMethod&&t.url===e.url||t.name===e.name));t>=0?o[t]=Object.assign(Object.assign(Object.assign({},e),o[t]),{accessConditions:[...e.accessConditions||[],...o[t].accessConditions||[]]}):o.push(e)}return o}createMany(e){return i(this,void 0,void 0,(function*(){const t=yield this.getCurrentTransaction(),n=new p.CrudService(this.model),r=yield this.getAuthProvider(),o=r&&(yield r.resolvePrincipal(e));return n.createMany({principal:o,body:e.getBody(),tx:t})}))}getMany(e){return i(this,void 0,void 0,(function*(){const t=yield this.getCurrentTransaction();return new p.CrudService(this.model).getMany({queries:e.getQuery(),tx:t})}))}updateMany(e){return i(this,void 0,void 0,(function*(){const t=yield this.getCurrentTransaction(),n=yield this.getAuthProvider(),r=n&&(yield n.resolvePrincipal(e));return new p.CrudService(this.model).updateMany({principal:r,queries:e.getQuery(),body:e.getBody(),tx:t})}))}deleteMany(e){return i(this,void 0,void 0,(function*(){const t=yield this.getCurrentTransaction();return new p.CrudService(this.model).deleteMany({queries:e.getQuery(),tx:t})}))}}r([c.Transactional(l.TransactionLink.INHERIT_OR_CREATE),u.AccessCondition([]),o("design:type",Function),o("design:paramtypes",[d.HttpRequest]),o("design:returntype",Promise)],CrudHttpController.prototype,"createMany",null),r([c.Transactional(l.TransactionLink.INHERIT_OR_CREATE),u.AccessCondition([]),o("design:type",Function),o("design:paramtypes",[d.HttpRequest]),o("design:returntype",Promise)],CrudHttpController.prototype,"getMany",null),r([c.Transactional(l.TransactionLink.INHERIT_OR_CREATE),u.AccessCondition([]),o("design:type",Function),o("design:paramtypes",[d.HttpRequest]),o("design:returntype",Promise)],CrudHttpController.prototype,"updateMany",null),r([c.Transactional(l.TransactionLink.INHERIT_OR_CREATE),u.AccessCondition([]),o("design:type",Function),o("design:paramtypes",[d.HttpRequest]),o("design:returntype",Promise)],CrudHttpController.prototype,"deleteMany",null),t.CrudHttpController=CrudHttpController},function(e,t,n){"use strict";var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function fulfilled(e){try{step(r.next(e))}catch(e){i(e)}}function rejected(e){try{step(r.throw(e))}catch(e){i(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((r=r.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.CrudService=void 0;const o=n(0),i=n(2),s=n(18);class CrudService{constructor(e){this.model=e,this.modelMetadata=o.getObjectMetadata(this.model)}getNestedQueries(e){return this.modelMetadata.fields.filter((e=>e.hasManyProps)).filter((t=>e.fields&&e.fields[t.name])).map((t=>{const n=this.getRequestQueryConditionFromQuery(e.fields[t.name],o.getObjectMetadata(o.getModelById(t.hasManyProps.id)));return{modelId:t.hasManyProps.id,queries:n.length?{_and:n}:{}}}))}getUploadHandler(){return r(this,void 0,void 0,(function*(){if(void 0===this.fileUploadHandler){const e=o.getServiceProvider().getInjector();this.fileUploadHandler=e.resolveOptional(s.AbstractFileUploadHandler)||null,yield e.initInstances()}return this.fileUploadHandler}))}getRequestQueryConditionFromQuery(e,t){const n=[];for(const r of i.getDirectFields(t))if(e[r.name])if(r.primaryKeyProps||r.foreignKeyProps)n.push({_in:{[r.name]:e[r.name]}});else if(r.enum)n.push({_in:{[r.name]:e[r.name]}});else switch(r.dataType){case o.DataType.STRING:if(r.searchable){const t={[r.caseSensitive?r.accentSensitive?"_sub":"_usub":r.accentSensitive?"_isub":"_iusub"]:{[r.name]:e[r.name]}};n.push(t)}else n.push({_eq:{[r.name]:e[r.name]}});break;case o.DataType.NUMBER:const t=new o.RangeQueryDto;Object.assign(t,e[r.name]),t.min&&(t.minExclusive?n.push({_gt:{[r.name]:t.min}}):n.push({_gte:{[r.name]:t.min}})),t.max&&(t.maxExclusive?n.push({_lt:{[r.name]:t.max}}):n.push({_lte:{[r.name]:t.max}}))}return n}beforeCreating(e,t){return r(this,void 0,void 0,(function*(){for(const n of t)for(const t of this.modelMetadata.fields)t.currentUser&&(n[t.name]=null==e?void 0:e.id)}))}uriHandling(e,t){var n;return r(this,void 0,void 0,(function*(){const r=yield this.getUploadHandler();if(!r)return;const o=t.use(this.model);for(const t of this.modelMetadata.fields)if(null===(n=t.mimeProps)||void 0===n?void 0:n.uriMapper)for(const n of e){const e=n[t.name],i=t.mimeProps.uriMapper(n);e&&i&&(yield r.moveFile(e,i),n[t.name]=i,yield o.updateOne(n))}}))}beforeReturning(e){var t,n;return r(this,void 0,void 0,(function*(){const r=yield this.getUploadHandler();for(const o of e)for(const e of this.modelMetadata.fields)if((null===(t=e.mimeProps)||void 0===t?void 0:t.uriMapper)&&r){if(!o[e.name])continue;o[e.name]=(null===(n=e.mimeProps)||void 0===n?void 0:n.public)?yield r.resolvePublicUrl(o[e.name]):yield r.resolvePrivateUrl(o[e.name])}}))}project(e,t){return t?e.map((e=>t.reduce(((t,n)=>Object.assign(t,{[n]:e[n]})),{}))):e}createMany({principal:e,body:t,tx:n}){return r(this,void 0,void 0,(function*(){const r=i.getDirectFields(this.modelMetadata),s=this.modelMetadata.fields.filter((e=>!!e.hasManyProps)),a=t.records;t.records=a.map((e=>r.reduce(((t,n)=>Object.assign(t,void 0!==e[n.name]?{[n.name]:e[n.name]}:{})),{}))),yield this.beforeCreating(e,t.records);let d=t.records.length?yield n.use(this.model).createMany(t.records):[];yield this.uriHandling(d,n),yield this.beforeReturning(d);const c=this.modelMetadata.fields.filter((e=>e.primaryKeyProps||e.serverValue||e.serverModify||e.mimeProps)).map((e=>e.name));d=this.project(d,c);for(const r of s){const i=d.map(((e,t)=>(a[t][r.name]||[]).map((t=>Object.assign(Object.assign({},t),{[r.hasManyProps.field]:e.id}))))).reduce(((e,t)=>e.concat(t)),[]);if(i.length){const s=new CrudService(o.getModelById(r.hasManyProps.id));t.records=i;const a=yield s.createMany({principal:e,body:t,tx:n});for(let e=0;e<a.records.length;e++)i[e]=Object.assign(Object.assign({},i[e]),a.records[e]);for(let e=0;e<d.length;e++){const t=[];for(let n=0;n<i.length;n++)i[n][r.hasManyProps.field]===d[e].id&&t.push(a.records[e]);d[e]=Object.assign(Object.assign({},d[e]),{[r.name]:t})}}}return{records:d}}))}updateMany({principal:e,queries:t,body:n,tx:s}){return r(this,void 0,void 0,(function*(){let r={};const a=this.modelMetadata.fields.filter((e=>!!e.hasManyProps)),d=i.getDirectFields(this.modelMetadata).filter((e=>void 0!==n.update[e.name])),c=d.reduce(((e,t)=>Object.assign(e,{[t.name]:n.update[t.name]})),{});if(t.fields){const e=this.getRequestQueryConditionFromQuery(t.fields,this.modelMetadata);e.length&&(r={_and:[...e]})}const l=this.getNestedQueries(t);let u=[];if(l.length){const e=yield s.use(this.model).getMany(r,{projection:["id"]},l);u=e.records.map((e=>e.id)),u.length&&d.length&&(yield s.use(this.model).updateMany({_in:{id:u}},c,!1))}else if(d.length)u=yield s.use(this.model).updateMany(r,c,!0);else{const e=yield s.use(this.model).getMany(r,{projection:["id"]});u=e.records.map((e=>e.id))}let h=u.map((e=>Object.assign(Object.assign({},c),{id:e})));yield this.uriHandling(h,s),yield this.beforeReturning(h);for(const t of a){const r=n.update[t.name];if(void 0===r||!u.length)continue;if(u.length>1)throw new o.ClaireError(o.Errors.QUERY_ERROR,`Multiple records found while updating @HasMany field: ${t.name}`);const i=h.find((e=>e.id===u[0])),a=o.getModelById(t.hasManyProps.id),d=s.use(a),c=(yield d.getRecords({_eq:{[t.hasManyProps.field]:i.id}})).map((e=>e.id)),l=r.map((e=>e.id)).filter((e=>!!e)),p=c.filter((e=>!l.includes(e))),f=r.filter((e=>!e.id)).map((e=>Object.assign(Object.assign({},e),{[t.hasManyProps.field]:i.id}))),g=r.filter((e=>!!e.id));yield d.deleteMany({_in:{id:p}});const y=new CrudService(a);yield y.beforeCreating(e,f);const m=yield y.createMany({principal:e,body:{records:f},tx:s}),v=f.map(((e,t)=>Object.assign(Object.assign({},e),m.records[t])));i[t.name]=v.concat(g)}let p=["id"];return t.returning&&(p=[...p,...Object.keys(n.update).filter((e=>void 0!==n.update[e]))]),{modified:this.project(h,p)}}))}getMany({queries:e,tx:t}){var n;return r(this,void 0,void 0,(function*(){const r=[];if(e.fields&&r.push(...this.getRequestQueryConditionFromQuery(e.fields,this.modelMetadata)),e.ops&&r.push(e.ops),e.search){const t=this.modelMetadata.fields.filter((e=>e.searchable)).map((t=>({_iusub:{[t.name]:e.search}})));t.length&&r.push({_or:t})}const i=yield t.use(this.model).getMany(r.length?{_and:r}:{},{limit:e.limit,page:e.page,projection:e.projection,order:null===(n=e.order)||void 0===n?void 0:n.map((e=>{const t=Object.keys(e).find((t=>!!e[t]));return[t,e[t]]}))},this.getNestedQueries(e)),s=i.records.map((e=>e.id));for(const n of this.modelMetadata.fields){if(!n.hasManyProps||e.projection&&!e.projection.includes(n.name))continue;const r=o.getModelById(n.hasManyProps.id),a=new CrudService(r),d=yield a.getMany({queries:{fields:{[n.hasManyProps.field]:s}},tx:t});for(const e of i.records)e[n.name]=d.records.filter((t=>t[n.hasManyProps.field]===e.id))}return yield this.beforeReturning(i.records),{total:i.total,records:this.project(i.records,e.projection)}}))}deleteMany({queries:e,tx:t}){return r(this,void 0,void 0,(function*(){let n={};if(e.fields){const t=this.getRequestQueryConditionFromQuery(e.fields,this.modelMetadata);t.length&&(n={_and:[...t]})}const r=this.getNestedQueries(e);let o=[];if(r.length){const e=yield t.use(this.model).getRecords(n,{projection:["id"]},r);yield t.use(this.model).deleteMany({_in:{id:e.map((e=>e.id))}}),o=e.map((e=>e.id))}else o=yield t.use(this.model).deleteMany(n,e.returning);return{modified:o.map((e=>({id:e})))}}))}}t.CrudService=CrudService},function(e,t,n){"use strict";var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function fulfilled(e){try{step(r.next(e))}catch(e){i(e)}}function rejected(e){try{step(r.throw(e))}catch(e){i(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((r=r.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.ClaireServer=void 0;const o=n(0),i=n(7);class ClaireServer extends o.ClaireApp{constructor(){super(),this.injector=o.getServiceProvider().getInjector(),this.booted=!1,this.logger=this.injector.resolve(o.AbstractLogger)}init(){return r(this,void 0,void 0,(function*(){this.booted||(yield this.injector.initInstances(),this.logger.debug("Claire server initing"),this.logger.debug("Setting up exception handlers"),process.on("SIGTERM",(()=>(this.logger.warn("SIGTERM interrupt signal"),this.stop(i.ExitCode.SIGTERM_INTERUPTION)))),process.on("SIGINT",(()=>(this.logger.warn("SIGINT interrupt signal"),this.stop(i.ExitCode.SIGTERM_INTERUPTION)))),process.on("uncaughtException",(e=>(this.logger.error("uncaughtException",e.name,e.stack),this.stop(i.ExitCode.UNCAUGHT_EXCEPTION)))),process.on("unhandledRejection",(e=>(this.logger.error("unhandledRejection",e.name,e.stack),this.stop(i.ExitCode.UNHANDLED_REJECTION)))),this.booted=!0)}))}exit(){super.exit()}stop(e){this.logger.debug("Server is shutting down"),this.exit(),process.exit(e)}}t.ClaireServer=ClaireServer},function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var o,i=arguments.length,s=i<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(i<3?o(s):i>3?o(t,n,s):o(t,n))||s);return i>3&&s&&Object.defineProperty(t,n,s),s},o=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},i=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function fulfilled(e){try{step(r.next(e))}catch(e){i(e)}}function rejected(e){try{step(r.throw(e))}catch(e){i(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((r=r.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSqlDatabaseAdapter=void 0;const s=n(0),a=n(31),d=n(17),c=n(19),l=n(32),u=n(10),h=n(2),getModelId=e=>{const t=s.getObjectMetadata(e);if(!t)throw new s.ClaireError(s.Errors.SYSTEM_ERROR,`Metadata for ${e.name} not found, check @Model decorator`);return t.id},p=["_and","_or"];class ModelAdapter extends l.AbstractQuery{constructor(e){super(e.model),this.dbConnection=e.dbConnection,this.modelConnections=e.modelConnections,this.transaction=e.transaction,this.sqlProvider=e.sqlProvider}getCurrentConnection(){const e=s.getObjectMetadata(this.model).id;return this.modelConnections[e].connection}resolveNestedIncludes(e){return e&&e.map((e=>({model:this.modelConnections[e.modelId].connection,where:this.getQueryObjectFromQueryConditions(e.queries)})))}count(e,t,n){return i(this,void 0,void 0,(function*(){const r={where:this.getQueryObjectFromQueryConditions(e),transaction:this.transaction,include:this.resolveNestedIncludes(n)};return(null==t?void 0:t.distinct)&&Object.assign(r,{distinct:!0,col:t.distinct}),yield this.getCurrentConnection().count(r)}))}getOne(e){return i(this,void 0,void 0,(function*(){const t=yield this.getMany(e,{limit:1});return t.records.length?t.records[0]:void 0}))}getRecords(e,t,n){return i(this,void 0,void 0,(function*(){return(yield this.getMany(e,t,n)).records}))}getMany(e,t,n){return i(this,void 0,void 0,(function*(){if(!this.getCurrentConnection())throw new s.ClaireError(s.Errors.SYSTEM_ERROR,"No active connection");let r={where:this.getQueryObjectFromQueryConditions(e),transaction:this.transaction,include:this.resolveNestedIncludes(n)};(null==t?void 0:t.order)&&Object.assign(r,{order:t.order}),(null==t?void 0:t.projection)&&Object.assign(r,{attributes:t.projection}),(null==t?void 0:t.limit)&&(r=Object.assign(r,{limit:t.limit}),t.page&&(r=Object.assign(r,{offset:t.limit*(t.page-1)})));let{count:o,rows:i}=yield this.getCurrentConnection().findAndCountAll(r);return{total:o,records:this.convertToLogicObjects(i,null==t?void 0:t.projection)}}))}createOne(e){return i(this,void 0,void 0,(function*(){return(yield this.createMany([e]))[0]}))}createMany(e){return i(this,void 0,void 0,(function*(){if(!this.getCurrentConnection())throw new s.ClaireError(s.Errors.SYSTEM_ERROR,"No active connection");let t=yield this.getCurrentConnection().bulkCreate(this.convertToDataObjects(e),{transaction:this.transaction});return this.convertToLogicObjects(t)}))}updateOne(e){return i(this,void 0,void 0,(function*(){return yield this.getCurrentConnection().update(this.convertToDataObjects([e])[0],{where:this.getQueryObjectFromQueryConditions({_eq:{id:e.id}}),transaction:this.transaction}),e}))}updateMany(e,t,n){return i(this,void 0,void 0,(function*(){if(n){const n=yield this.getRecords(e,{projection:["id"]});if(!n.length)return[];const r=n.map((e=>e.id));return yield this.getCurrentConnection().update(this.convertToDataObjects([t])[0],{where:this.getQueryObjectFromQueryConditions({_in:{id:r}}),transaction:this.transaction}),r}return yield this.getCurrentConnection().update(this.convertToDataObjects([t])[0],{where:this.getQueryObjectFromQueryConditions(e),transaction:this.transaction}),[]}))}deleteOne(e){return i(this,void 0,void 0,(function*(){return yield this.deleteMany({_eq:{id:e.id}}),e}))}deleteMany(e,t){return i(this,void 0,void 0,(function*(){if(t){const t=yield this.getMany(e);if(!t.records.length)return[];const n=t.records.map((e=>e.id));return yield this.getCurrentConnection().destroy({where:this.getQueryObjectFromQueryConditions({_in:{id:n}}),transaction:this.transaction}),n}return yield this.getCurrentConnection().destroy({where:this.getQueryObjectFromQueryConditions(e),transaction:this.transaction}),[]}))}rawQuery(e){return i(this,void 0,void 0,(function*(){return this.dbConnection.query(e,{transaction:this.transaction})}))}convertOp(e){return[a.Op.and,a.Op.or,a.Op.eq,a.Op.ne,a.Op.gt,a.Op.lt,a.Op.gte,a.Op.lte,a.Op.regexp,a.Op.like,a.Op.in][["_and","_or","_eq","_neq","_gt","_lt","_gte","_lte","_regex","_sub","_in"].indexOf(e)]}mapToSequelizeOperator(e,t,n){switch(e){case"_isub":switch(this.sqlProvider){case u.SqlProvider.POSTGRES:return{[t]:{[a.Op.iLike]:`%${n}%`}};default:return a.Sequelize.where(a.Sequelize.fn("lower",a.Sequelize.col(t)),{[a.Op.like]:`%${n.toLowerCase()}%`})}case"_sub":return{[t]:{[this.convertOp(e)]:`%${n}%`}};case"_usub":return a.Sequelize.where(a.Sequelize.fn("unaccent",a.Sequelize.col(t)),{[a.Op.like]:`%${n}%`});case"_iusub":switch(this.sqlProvider){case u.SqlProvider.POSTGRES:return a.Sequelize.where(a.Sequelize.fn("unaccent",a.Sequelize.col(t)),{[a.Op.iLike]:`%${n}%`});default:return a.Sequelize.where(a.Sequelize.fn("unaccent",a.Sequelize.fn("lower",a.Sequelize.col(t))),{[a.Op.like]:`%${n.toLowerCase()}%`})}default:return{[t]:{[this.convertOp(e)]:n}}}}getQueryObjectFromQueryConditions(e){if(!e)return{};const t=Object.keys(e);if(!t.length)return{};const n=t.map((t=>p.includes(t)?{[this.convertOp(t)]:e[t].map((e=>this.getQueryObjectFromQueryConditions(e)))}:{[this.convertOp("_and")]:Object.keys(e[t]).map((n=>this.mapToSequelizeOperator(t,n,e[t][n])))}));return n.length>1?{[this.convertOp("_and")]:n}:n[0]}}class TransactionAdapter{constructor(e){this.modelAdapters={},this.transaction=e.transaction,this.dbConnection=e.dbConnection,this.logger=e.logger,this.modelConnections=e.modelConnections,this.sqlProvider=e.sqlProvider,this.transactionState=d.TransactionState.EXECUTING}use(e){const t=getModelId(e);let n=this.modelAdapters[t];return n||(this.modelAdapters,n=new ModelAdapter({model:e,dbConnection:this.dbConnection,modelConnections:this.modelConnections,logger:this.logger,transaction:this.transaction,sqlProvider:this.sqlProvider}),this.modelAdapters[t]=n),n}commit(){return i(this,void 0,void 0,(function*(){return this.transactionState=d.TransactionState.COMMITTED,this.transaction.commit()}))}rollback(){return i(this,void 0,void 0,(function*(){return this.transactionState=d.TransactionState.ROLLED_BACK,this.transaction.rollback()}))}getState(){return this.transactionState}}let f=class DefaultSqlDatabaseAdapter extends c.AbstractDatabaseAdapter{constructor(e,t,n){super(),this.logger=n,this.injector=s.getServiceProvider().getInjector(),this.modelAdapters={},this.sqlProvider=e,this.dbConnection=new a.Sequelize(`${e}://${t}`,{dialect:this.sqlProvider,logging:!1,define:{timestamps:!1}})}createTransaction(){return i(this,void 0,void 0,(function*(){let e=yield this.dbConnection.transaction();return new TransactionAdapter({transaction:e,dbConnection:this.dbConnection,logger:this.logger,modelConnections:this.modelConnections,sqlProvider:this.sqlProvider})}))}init(){const e=Object.create(null,{init:{get:()=>super.init}});var t,n,r;return i(this,void 0,void 0,(function*(){yield e.init.call(this),yield this.injector.initInstances(),null===(t=this.logger)||void 0===t||t.debug("Connecting to database");try{yield this.dbConnection.authenticate()}catch(e){throw new s.ClaireError(s.Errors.SYSTEM_ERROR,e.stack||String(e))}null===(n=this.logger)||void 0===n||n.debug("Generating in-memory schema");for(const e of this.modelMetadata){const t=this.generateSchemaObject(e);this.modelConnections[e.id].connection=t}for(const e of this.modelMetadata){const t=this.modelConnections[e.id].connection,n=e.fields.filter((e=>e.hasManyProps));for(const e of n)t.hasMany(this.modelConnections[e.hasManyProps.id].connection,{foreignKey:e.hasManyProps.field})}null===(r=this.logger)||void 0===r||r.debug("Database adapter init succeeded")}))}exit(){var e;return null===(e=this.logger)||void 0===e||e.debug("Closing connection to database"),this.dbConnection.close(),0}use(e){const t=getModelId(e);let n=this.modelAdapters[t];return n||(n=new ModelAdapter({model:e,dbConnection:this.dbConnection,modelConnections:this.modelConnections,logger:this.logger,sqlProvider:this.sqlProvider}),this.modelAdapters[t]=n),n}generateSchemaObject(e){let t={};for(const n of h.getDirectFields(e)){switch(t[n.name]={},n.dataType){case s.DataType.NUMBER:n.floating?t[n.name].type=a.DataTypes.FLOAT:n.isBigInt?t[n.name].type=a.DataTypes.BIGINT:t[n.name].type=a.DataTypes.INTEGER;break;case s.DataType.STRING:n.textLength?t[n.name].type=a.DataTypes.STRING(n.textLength):t[n.name].type=a.DataTypes.STRING;break;case s.DataType.BOOLEAN:t[n.name].type=a.DataTypes.BOOLEAN;break;case s.DataType.ARRAY:case s.DataType.OBJECT:t[n.name].type=a.DataTypes.TEXT}n.primaryKeyProps&&(t[n.name].primaryKey=!0,n.primaryKeyProps.isAutoIncrement&&(t[n.name].autoIncrement=!0)),void 0!==n.defaultValue&&(t[n.name].defaultValue=n.defaultValue),t[n.name].allowNull=!n.isRequired,n.isTimestamp&&n.serverValue&&(t[n.name].defaultValue=()=>Date.now())}return this.dbConnection.define(e.id,t,{tableName:e.id})}};f=r([s.Initable(),s.Injectable(),o("design:paramtypes",[String,String,s.AbstractLogger])],f),t.DefaultSqlDatabaseAdapter=f},function(e,t){e.exports=require("sequelize")},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractQuery=void 0;const r=n(0);t.AbstractQuery=class AbstractQuery{constructor(e){const t=r.getObjectMetadata(e);this.model=r.getModelById(t.id)||e,this.metadata=r.getObjectMetadata(this.model)}convertToLogicObjects(e,t){return e.map((e=>{let n=new this.model;return this.metadata.fields.filter((e=>!t||t.includes(e.name))).forEach((t=>{t.isBigInt?n[t.name]=Number(e[t.name]):t.vectorProps?n[t.name]=JSON.parse(e[t.name]):n[t.name]=e[t.name]})),n}))}convertToDataObjects(e){return e.map((e=>{var t;let n=new this.model;for(const r of this.metadata.fields){const o=e[r.name];(null===(t=r.serverModify)||void 0===t?void 0:t.fn)?n[r.name]=r.serverModify.fn(o):r.vectorProps?n[r.name]=JSON.stringify(o):n[r.name]=o}return n}))}}},function(e,t,n){"use strict";var r,o=this&&this.__decorate||function(e,t,n,r){var o,i=arguments.length,s=i<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(i<3?o(s):i>3?o(t,n,s):o(t,n))||s);return i>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)},s=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function fulfilled(e){try{step(r.next(e))}catch(e){i(e)}}function rejected(e){try{step(r.throw(e))}catch(e){i(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((r=r.apply(e,t||[])).next())}))},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSqlDatabaseMigrator=void 0;const d=a(n(13)),c=a(n(12)),l=n(34),u=n(0),h=(n(10),n(2)),p=n(20),uniqueGroupComparator=(e,t)=>!e.groupName&&!t.groupName&&e.fieldNames[0]===t.fieldNames[0]||!!e.groupName&&e.groupName===t.groupName;let f=r=class DefaultSqlDatabaseMigrator extends p.AbstractDatabaseMigrator{constructor(e,t,n,r){super(),this.logger=r,this.injector=u.getServiceProvider().getInjector(),this.cliPath=e,this.databaseURL=`${t}://${n}`,this.modelMetadata=(u.getGlobalStore().models||[]).map((e=>u.getObjectMetadata(e)))}init(){return s(this,void 0,void 0,(function*(){yield this.injector.initInstances()}))}exit(){}getUniqueConstraintGroups(e){const t=[],n=h.getDirectFields(e).filter((e=>!!e.uniqueProps));for(const e of n)if(e.uniqueProps.groupName){let n=t.find((t=>t.groupName===e.uniqueProps.groupName));n||(n={groupName:e.uniqueProps.groupName,fieldNames:[]},t.push(n)),n.fieldNames.push(e.name)}else t.push({fieldNames:[e.name]});return t}generateFieldPropertiesQuery(e){let t="{";if(e.primaryKeyProps&&(t+="primaryKey:true,",e.primaryKeyProps.isAutoIncrement&&(t+="autoIncrement:true,")),void 0!==e.defaultValue&&(t+=`defaultValue:${JSON.stringify(e.defaultValue)},`),t+=`allowNull:${e.isRequired?"false":"true"},`,void 0!==e.dataType)switch(e.dataType){case u.DataType.STRING:e.textLength?t+=`type:Sequelize.STRING(${e.textLength}),`:t+="type:Sequelize.TEXT,";break;case u.DataType.NUMBER:e.floating?t+="type:Sequelize.FLOAT,":e.isBigInt?t+="type:Sequelize.BIGINT,":t+="type:Sequelize.INTEGER,";break;case u.DataType.BOOLEAN:t+="type:Sequelize.BOOLEAN,";break;case u.DataType.ARRAY:case u.DataType.OBJECT:t+="type:Sequelize.TEXT,"}return t+="}",t}getUniqueConstraintUpDown(e,t){const n=`${e}_${t.groupName||t.fieldNames[0]}_un`;return[`queryInterface.addConstraint("${e}",{fields:${JSON.stringify(t.fieldNames)},type:"unique",name:"${n}","transaction":t})`,`queryInterface.removeConstraint("${e}","${n}",{"transaction":t})`]}getForeignKeyConstraintUpDown(e,t,n){var r;const o=`${t}_${n.name}_fk`;return[`queryInterface.addConstraint("${t}",{fields:["${n.name}"],type:"foreign key",name:"${o}",references:{table:"${e.id}",field:"id"}${(null===(r=n.foreignKeyProps)||void 0===r?void 0:r.cascade)?",onDelete:'CASCADE',onUpdate:'CASCADE'":""},"transaction":t})`,`queryInterface.removeConstraint("${t}","${o}",{"transaction":t})`]}getAddColumnUpDown(e,t){return[`queryInterface.addColumn('${e}','${t.name}',${this.generateFieldPropertiesQuery(t)},{"transaction":t})`,`queryInterface.removeColumn('${e}','${t.name}',{"transaction":t})`]}generateCreateTableQuery(e){let t={upTableAdd:[],downTableRemove:[],upConstraintAdd:[],downConstraintRemove:[],upTableRemove:[],downTableAdd:[],upConstraintRemove:[],downConstraintAdd:[]},n="",r="";n+="{\n";for(const t of h.getDirectFields(e)){let e=this.generateFieldPropertiesQuery(t);n+=`${t.name}:${e},\n`}n+="}\n",r+='{charset:"utf8",transaction:t}',t.upTableAdd.push(`queryInterface.createTable("${e.id}",${n},{charset:"utf8",transaction:t})`),t.downTableRemove.push(`queryInterface.dropTable("${e.id}",{"transaction":t})`);const o=this.getUniqueConstraintGroups(e);for(const n of o){const[r,o]=this.getUniqueConstraintUpDown(e.id,n);t.upConstraintAdd.push(r),t.downConstraintRemove.push(o)}for(const n of h.getDirectFields(e))if(n.foreignKeyProps){let r=this.modelMetadata.find((e=>{var t;return e.id===(null===(t=n.foreignKeyProps)||void 0===t?void 0:t.id)}));const[o,i]=this.getForeignKeyConstraintUpDown(r,e.id,n);t.upConstraintAdd.push(o),t.downConstraintRemove.push(i)}return t}isBooleanDiff(e,t){return!!e&&!t||!!t&&!e}runProcess(e){return s(this,void 0,void 0,(function*(){return new Promise(((t,n)=>{l.exec(e,{env:process.env},(e=>(e&&n(e),t())))}))}))}rollback(e){return s(this,void 0,void 0,(function*(){let t=d.default.join(e,"scripts");if(!c.default.existsSync)throw new u.ClaireError(u.Errors.MIGRATION_ERROR,"Migration directory not found");this.logger.debug("Rolling back last migration"),yield this.runProcess(`${this.cliPath} --url=${this.databaseURL} --migrations-path=${t} db:migrate:undo`),this.logger.debug("Rollback completed")}))}migrate(e){var t,n,o,i,a,l,p,f;return s(this,void 0,void 0,(function*(){let g=d.default.join(e,"metadata.json"),y=d.default.join(e,"scripts");c.default.existsSync(y)||(this.logger.debug("Migration directory not exists, creating empty folder"),c.default.mkdirSync(y,{recursive:!0})),c.default.existsSync(g)||(this.logger.debug("Migration metadata does not exist, creating one"),c.default.writeFileSync(g,JSON.stringify([]))),this.logger.debug("Parsing migration metadata file");let m=JSON.parse(String(c.default.readFileSync(g)));this.logger.debug("Calculating differences...");const v=this.modelMetadata.filter((e=>!m.find((t=>e.id===t.id)))),b=this.modelMetadata.filter((e=>m.find((t=>t.id===e.id)))).map((e=>e.id));let C=[];C.push(...v.map((e=>this.generateCreateTableQuery(e))));for(const e of b){const r=m.find((t=>t.id===e)),s=this.modelMetadata.find((t=>t.id===e));r.id!==s.id&&C.push({upTableAdd:[`queryInterface.query("ALTER TABLE ${r.id} RENAME TO ${s.id}",{"transaction":t})`],downTableRemove:[`queryInterface.query("ALTER TABLE ${s.id} RENAME TO ${r.id}",{"transaction":t})`],upConstraintAdd:[],downConstraintRemove:[],upTableRemove:[],downTableAdd:[],upConstraintRemove:[],downConstraintAdd:[]});let d={upTableAdd:[],downTableRemove:[],upConstraintAdd:[],downConstraintRemove:[],upTableRemove:[],downTableAdd:[],upConstraintRemove:[],downConstraintAdd:[]};const c=h.getDirectFields(r).filter((e=>!h.getDirectFields(s).find((t=>e.name===t.name))));for(const e of c){const[t,n]=this.getAddColumnUpDown(s.id,e);if(d.upTableRemove.push(n),d.downTableAdd.push(t),e.foreignKeyProps){let t=this.modelMetadata.find((t=>{var n;return t.id===(null===(n=e.foreignKeyProps)||void 0===n?void 0:n.id)}));const[n,r]=this.getForeignKeyConstraintUpDown(t,s.id,e);d.upConstraintRemove.push(r),d.downConstraintAdd.push(n)}}const u=h.getDirectFields(s).filter((e=>!h.getDirectFields(r).find((t=>e.name===t.name))));for(const e of u){const[t,n]=this.getAddColumnUpDown(s.id,e);if(d.upTableAdd.push(t),d.downTableRemove.push(n),e.foreignKeyProps){let t=this.modelMetadata.find((t=>{var n;return t.id===(null===(n=e.foreignKeyProps)||void 0===n?void 0:n.id)}));const[n,r]=this.getForeignKeyConstraintUpDown(t,s.id,e);d.upConstraintAdd.push(n),d.downConstraintRemove.push(r)}}const g=h.getDirectFields(s).filter((e=>h.getDirectFields(r).find((t=>e.name===t.name)))).map((e=>e.name));for(const e of g){const c=h.getFieldByName(r,e),u=h.getFieldByName(s,e);if((this.isBooleanDiff(c.isBigInt,u.isBigInt)||this.isBooleanDiff(c.isRequired,u.isRequired)||this.isBooleanDiff(null===(t=c.primaryKeyProps)||void 0===t?void 0:t.isAutoIncrement,null===(n=u.primaryKeyProps)||void 0===n?void 0:n.isAutoIncrement)||c.dataType!==u.dataType||c.textLength!==u.textLength||c.defaultValue!==u.defaultValue)&&(d.upTableAdd.push(`queryInterface.changeColumn("${s.id}","${u.name}",${this.generateFieldPropertiesQuery(u)},{"transaction":t})`),d.downTableRemove.push(`queryInterface.changeColumn("${s.id}","${c.name}",${this.generateFieldPropertiesQuery(c)},{"transaction":t})`)),(null===(o=c.foreignKeyProps)||void 0===o?void 0:o.id)!==(null===(i=u.foreignKeyProps)||void 0===i?void 0:i.id)||this.isBooleanDiff(null===(a=c.foreignKeyProps)||void 0===a?void 0:a.cascade,null===(l=u.foreignKeyProps)||void 0===l?void 0:l.cascade)){if(null===(p=c.foreignKeyProps)||void 0===p?void 0:p.id){const e=this.modelMetadata.find((e=>{var t;return e.id===(null===(t=c.foreignKeyProps)||void 0===t?void 0:t.id)})),[t,n]=this.getForeignKeyConstraintUpDown(e,s.id,c);d.upTableAdd.push(n),d.downTableRemove.push(t)}if(null===(f=u.foreignKeyProps)||void 0===f?void 0:f.id){const e=this.modelMetadata.find((e=>{var t;return e.id===(null===(t=u.foreignKeyProps)||void 0===t?void 0:t.id)})),[t,n]=this.getForeignKeyConstraintUpDown(e,s.id,u);d.upTableAdd.push(t),d.downTableRemove.push(n)}}}const y=this.getUniqueConstraintGroups(r),v=this.getUniqueConstraintGroups(s),b=y.filter((e=>!!v.find((t=>uniqueGroupComparator(e,t))))),M=y.filter((e=>!b.find((t=>uniqueGroupComparator(e,t)))));for(const e of M){const[t,n]=this.getUniqueConstraintUpDown(s.id,e);d.upConstraintRemove.push(n),d.downConstraintAdd.push(t)}const O=v.filter((e=>!b.find((t=>uniqueGroupComparator(e,t)))));for(const e of O){const[t,n]=this.getUniqueConstraintUpDown(s.id,e);d.upConstraintAdd.push(t),d.downConstraintRemove.push(n)}for(const e of b){const t=y.find((t=>uniqueGroupComparator(t,e))),n=v.find((t=>uniqueGroupComparator(t,e)));if(t.fieldNames.length!==n.fieldNames.length||t.fieldNames.some((e=>!n.fieldNames.includes(e)))){const[e,r]=this.getUniqueConstraintUpDown(s.id,t),[o,i]=this.getUniqueConstraintUpDown(s.id,n);d.upConstraintRemove.push(r),d.upConstraintAdd.push(o),d.downConstraintRemove.push(i),d.downConstraintAdd.push(e)}}(d.upTableAdd.length||d.downTableRemove.length||d.upConstraintAdd.length||d.downConstraintRemove.length||d.upConstraintRemove.length||d.downConstraintAdd.length||d.upTableRemove.length||d.downTableAdd.length)&&C.push(d)}if(C.length){let e=`${Date.now()}-auto-migration.js`;const getTransactionalScript=e=>`const t = await queryInterface.sequelize.transaction({autoCommit: false}); \n try {\n ${e.reduce(((e,t)=>e+`await ${t};`),"")}\n await t.commit();\n } catch(err){\n await t.rollback(); \n throw(err);\n }`,migrationFunction=(e,t)=>s(this,void 0,void 0,(function*(){if(!e.up.length&&!e.down.length)return;let n=d.default.join(y,t),o=r.MIGRATION_TEMPLATE,i=new RegExp(r.COMMENT_BLOCK_REGEX_PATTERN),s=getTransactionalScript(e.up),a=getTransactionalScript(e.down);o=o.replace(i,s),o=o.replace(i,a),this.logger.debug("Writing to file",n),c.default.writeFileSync(n,o)}));throw yield migrationFunction({up:[...C.reduce(((e,t)=>e.concat(t.upConstraintRemove)),[]),...C.reduce(((e,t)=>e.concat(t.upTableRemove)),[]),...C.reduce(((e,t)=>e.concat(t.upTableAdd)),[]),...C.reduce(((e,t)=>e.concat(t.upConstraintAdd)),[])],down:[...C.reduce(((e,t)=>e.concat(t.downConstraintRemove)),[]).reverse(),...C.reduce(((e,t)=>e.concat(t.downTableRemove)),[]).reverse(),...C.reduce(((e,t)=>e.concat(t.downTableAdd)),[]).reverse(),...C.reduce(((e,t)=>e.concat(t.downConstraintAdd)),[]).reverse()]},e),this.logger.debug("Updating metadata file"),c.default.writeFileSync(g,JSON.stringify(this.modelMetadata)),new u.ClaireError(u.Errors.MIGRATION_ERROR,e)}this.logger.debug("No difference, running migration"),this.logger.debug("Create database if not exist");try{yield this.runProcess(`${this.cliPath} --url=${this.databaseURL} db:create`)}catch(e){if(String(e).indexOf("already exists")<0)throw new u.ClaireError(u.Errors.MIGRATION_ERROR,e.stack||String(e))}this.logger.debug("Running migration"),yield this.runProcess(`${this.cliPath} --url=${this.databaseURL} --migrations-path=${y} db:migrate`),this.logger.debug("Migration finished")}))}};f.COMMENT_BLOCK_REGEX_PATTERN="/\\*(\\*(?!/)|[^*])*\\*\\/",f.MIGRATION_TEMPLATE="'use strict';\n module.exports = {\n up: async (queryInterface, Sequelize) => {\n /**\n */\n },\n \n down: async (queryInterface, Sequelize) => {\n /**\n */\n }\n };",f=r=o([u.Injectable(),i("design:paramtypes",[String,String,String,u.AbstractLogger])],f),t.DefaultSqlDatabaseMigrator=f},function(e,t){e.exports=require("child_process")},function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var o,i=arguments.length,s=i<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(i<3?o(s):i>3?o(t,n,s):o(t,n))||s);return i>3&&s&&Object.defineProperty(t,n,s),s},o=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},i=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function fulfilled(e){try{step(r.next(e))}catch(e){i(e)}}function rejected(e){try{step(r.throw(e))}catch(e){i(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((r=r.apply(e,t||[])).next())}))},s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultHttpRequestHandler=void 0;const a=n(0),d=s(n(36)),c=n(37),l=s(n(38)),u=n(11),h=n(5),p=n(3),f=n(1),g=n(21),y=n(22),m=n(6);let v=class DefaultHttpRequestHandler extends f.AbstractHttpRequestHandler{constructor(e,t){super(),this.logger=e,this.authorizationProvider=t,this.injector=a.getServiceProvider().getInjector(),this.mountPoint="",this.mountedEndpointInfo=[],this.middleware=this.injector.resolveMultiple(y.AbstractHttpMiddleware)}init(){var e,t,n,r;return i(this,void 0,void 0,(function*(){const o=[],s=this.injector.resolveMultiple(m.AbstractHttpController);yield this.injector.initInstances();for(const e of s){const t=a.getObjectMetadata(e.constructor),n=e.getEndpointMetadata();for(const r of n){const n=new g.HttpEndpoint;n.mount=this.resolverMountPoint(t,[this.mountPoint||"/",r.url]),n.httpMethod=r.httpMethod,n.handler=(t,o)=>i(this,void 0,void 0,(function*(){if(n.httpMethod!==a.SocketMethod.MESSAGE){const e=yield this.authorizationProvider.resolvePrincipal(t);t.setAuthInfo(e),r.openAccess||(yield this.authorizationProvider.authorize(e,t,{endpoint:n,endpointMetadata:r}))}return e[r.name](t,o)})),n.controller=e,n.handlerFunctionName=r.name,o.push({endpointMetadata:r,endpoint:n})}}this.mountedEndpointInfo=[];for(const i of o){const o=this.mountedEndpointInfo.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: ${o.endpoint.getEndpointId()} of ${null===(t=o.endpoint.controller)||void 0===t?void 0:t.constructor.name}:${o.endpoint.handlerFunctionName}`,`Ignore ${i.endpoint.getEndpointId()} of ${null===(n=i.endpoint.controller)||void 0===n?void 0:n.constructor.name}:${i.endpoint.handlerFunctionName}`):(null===(r=this.logger)||void 0===r||r.debug(`Mouting: ${i.endpoint.getEndpointId()}`),this.mountedEndpointInfo.push(i))}a.getGlobalStore().mountedEndpointInfo=this.mountedEndpointInfo}))}exit(){}handle(e){return i(this,void 0,void 0,(function*(){const t=e.method,n=d.default({url:e.rawPath});let r={};const o=this.mountedEndpointInfo.find((e=>{const o=e.endpointMetadata.httpMethod===t&&c.match(e.endpointMetadata.url,{decode:decodeURIComponent})(n.pathname);return!!o&&(r=o,!0)}));if(!o)throw this.logger.debug(e),new a.ClaireError(a.Errors.BAD_REQUEST,"Handler not found");const i=new h.HttpRequest({method:t,headers:e.headers,pathName:n.pathname||"",hash:n.hash||"",query:l.default.parse(n.search||""),params:r.params,body:e.body,socket:e.socket},o.endpointMetadata),s=new u.HttpResponse;if(t!==a.SocketMethod.MESSAGE)for(const e of this.getMiddleware())yield e.intercept(i,s);return{body:yield o.endpoint.handler&&o.endpoint.handler(i,s),code:s.getStatus(),cookies:s.getCookies(),headers:s.getHeaders()}}))}getMiddleware(){return this.middleware}};v=r([a.Initable(),o("design:paramtypes",[a.AbstractLogger,p.AbstractHttpAuthorizationProvider])],v),t.DefaultHttpRequestHandler=v},function(e,t){e.exports=require("parseurl")},function(e,t){e.exports=require("path-to-regexp")},function(e,t){e.exports=require("query-string")},function(e,t,n){"use strict";var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function fulfilled(e){try{step(r.next(e))}catch(e){i(e)}}function rejected(e){try{step(r.throw(e))}catch(e){i(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((r=r.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractService=void 0;const o=n(2);t.AbstractService=class AbstractService{getCurrentTransaction(){return r(this,void 0,void 0,(function*(){return o.getTransactionFromContext(this)}))}}},function(e,t,n){"use strict";var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function fulfilled(e){try{step(r.next(e))}catch(e){i(e)}}function rejected(e){try{step(r.throw(e))}catch(e){i(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((r=r.apply(e,t||[])).next())}))},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ExpressWrapper=void 0;const i=n(0),s=o(n(41)),a=o(n(42)),d=o(n(43)),c=o(n(44)),l=n(4),u=n(1);t.ExpressWrapper=class ExpressWrapper{constructor(e,t){this.injector=i.getServiceProvider().getInjector(),this.server=e,this.config=t,this.logger=this.injector.resolve(i.AbstractLogger),this.socketManager=this.injector.resolveOptional(l.AbstractServerSocketManager),this.httpRequestHandler=this.injector.resolve(u.AbstractHttpRequestHandler)}close(){var e;null===(e=this.httpServer)||void 0===e||e.close()}listen(e){var t,n;return r(this,void 0,void 0,(function*(){yield this.server.init(),yield this.injector.initInstances();const o=s.default(),i=a.default.createServer(o);return null===(t=this.socketManager)||void 0===t||t.configure(i),o.use(d.default()),o.use(s.default.raw({limit:1024*((null===(n=this.config)||void 0===n?void 0:n.maxBodySizeKB)||4096)})),o.use(c.default()),o.use(((e,t,n)=>{e.files&&(e.body||(e.body={}),Object.keys(e.files).forEach((t=>{e.body[t]=e.files[t]}))),n()})),o.use(s.default.urlencoded({extended:!1})),o.use(s.default.json()),o.all("*",((e,t)=>{(()=>r(this,void 0,void 0,(function*(){var n;const r=!!e.headers["x-amzn-apigateway-api-id"]?{method:e.body.type.toLowerCase(),rawPath:e.body.connectionId,body:e.body.data}:{rawPath:e.url,method:e.method.toLowerCase(),headers:e.headers,body:e.body};let o=yield null===(n=this.socketManager)||void 0===n?void 0:n.intercept(r);return o||(o=yield this.httpRequestHandler.handle(r)),o.headers&&Object.keys(o.headers).forEach((e=>{t.set(e,o.headers[e])})),t.status(o.code).send(o.body)})))().catch((e=>{this.logger.error(e),t.status(400).json(e)}))})),new Promise(((t,n)=>{this.httpServer=i.listen(e,t).on("error",n)}))}))}}},function(e,t){e.exports=require("express")},function(e,t){e.exports=require("http")},function(e,t){e.exports=require("cors")},function(e,t){e.exports=require("express-fileupload")},function(e,t,n){"use strict";var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function fulfilled(e){try{step(r.next(e))}catch(e){i(e)}}function rejected(e){try{step(r.throw(e))}catch(e){i(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((r=r.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.LambdaWrapper=void 0;const o=n(0),i=n(1),s=n(4),toApiGatewayFormat=(e,t)=>({statusCode:e,body:t&&JSON.stringify(t),headers:{"Access-Control-Allow-Headers":"*","Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"*","Content-Type":"application/json"}});t.LambdaWrapper=class LambdaWrapper{constructor(e,t){this.server=e,this.requestMapper=t,this.handler=this.handler.bind(this),this.injector=o.getServiceProvider().getInjector(),this.socketManager=this.injector.resolveOptional(s.AbstractServerSocketManager),this.httpRequestHandler=this.injector.resolve(i.AbstractHttpRequestHandler)}handler(e){var t,n;return r(this,void 0,void 0,(function*(){yield this.server.init(),yield this.injector.initInstances(),null===(t=this.socketManager)||void 0===t||t.configure();const r=this.requestMapper(e);if(!r)return toApiGatewayFormat(400,new o.ClaireError(o.Errors.BAD_REQUEST,"Cannot resolve event"));if(r.method===o.HttpMethod.OPTIONS)return toApiGatewayFormat(200);try{let e=yield null===(n=this.socketManager)||void 0===n?void 0:n.intercept(r);return e||(e=yield this.httpRequestHandler.handle(r)),toApiGatewayFormat(e.code,e.body)}catch(e){return toApiGatewayFormat(400,e)}}))}}},function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var o,i=arguments.length,s=i<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(i<3?o(s):i>3?o(t,n,s):o(t,n))||s);return i>3&&s&&Object.defineProperty(t,n,s),s},o=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},i=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function fulfilled(e){try{step(r.next(e))}catch(e){i(e)}}function rejected(e){try{step(r.throw(e))}catch(e){i(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((r=r.apply(e,t||[])).next())}))},s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.LocalSocketManager=void 0;const a=n(0),d=s(n(47)),c=n(1),l=n(3),u=n(4),h=n(24);class ExpressSocket extends h.AbstractServerSocket{constructor(e,t,n,r){super(e,t,n),this.logger=e,this.httpRequestHandler=t,this.authorizationProvider=n,this.socket=r;const o=Date.now();this.socketInfo={id:`${o.toString()}-${Math.trunc(1e6*Math.random())}`,isOpen:!0,authorized:!1,createdAt:o}}physicSend(e){return i(this,void 0,void 0,(function*(){this.socket.send(e)}))}setOpen(e){return i(this,void 0,void 0,(function*(){this.socketInfo.isOpen=e}))}physicDisconnect(){return i(this,void 0,void 0,(function*(){this.socket.close()}))}authorize(e){const t=Object.create(null,{authorize:{get:()=>super.authorize}});return i(this,void 0,void 0,(function*(){yield t.authorize.call(this,e)}))}}let p=class LocalSocketManager extends u.AbstractServerSocketManager{constructor(e,t,n){super(e),this.logger=e,this.httpRequestHandler=t,this.authorizationProvider=n,this.allSockets=[]}configure(e){if(this.logger.debug("Local socket manager configure"),!e)return;const t=this;new d.default.Server({server:e}).on("connection",(e=>{const n=t.create(e);this.logger.debug("Local socket manager socket connect",n.getId()),t.add(n).catch((e=>{this.logger.error(e)})),e.onmessage=e=>{this.logger.debug("Local socket manager socket message",n.getId(),e.data);const{message:t,channel:r}=JSON.parse(e.data);n.handleMessage(r,t).catch((e=>{this.logger.error(e)}))},e.onclose=()=>{this.logger.debug("Local socket manager socket close",n.getId()),n.isOpen()&&n.handleDisconnect().catch((e=>{this.logger.error(e)})),t.removeById(n.getId()).catch((e=>{this.logger.error(e)}))}}))}intercept(){return i(this,void 0,void 0,(function*(){}))}create(e){return new ExpressSocket(this.logger,this.httpRequestHandler,this.authorizationProvider,e)}getAllSockets(){return i(this,void 0,void 0,(function*(){return this.allSockets}))}add(e){return i(this,void 0,void 0,(function*(){this.allSockets.push(e)}))}removeById(e){return i(this,void 0,void 0,(function*(){const t=this.allSockets.findIndex((t=>t.getId()===e));t>=0&&this.allSockets.splice(t,1)}))}getById(e){return i(this,void 0,void 0,(function*(){return this.allSockets.find((t=>t.getId()===e))}))}};p=r([a.Injectable(),o("design:paramtypes",[a.AbstractLogger,c.AbstractHttpRequestHandler,l.AbstractHttpAuthorizationProvider])],p),t.LocalSocketManager=p},function(e,t){e.exports=require("ws")},function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var o,i=arguments.length,s=i<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(i<3?o(s):i>3?o(t,n,s):o(t,n))||s);return i>3&&s&&Object.defineProperty(t,n,s),s},o=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},i=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function fulfilled(e){try{step(r.next(e))}catch(e){i(e)}}function rejected(e){try{step(r.throw(e))}catch(e){i(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((r=r.apply(e,t||[])).next())}))},s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.AwsSocketManager=void 0;const a=n(0),d=s(n(49)),c=s(n(50)),l=n(1),u=n(4),h=n(24),p=n(3);class ApiGatewaySocket extends h.AbstractServerSocket{constructor(e,t,n,r,o,i,s,a){super(t,n,r),this.socketManager=e,this.socketInfo=Object.assign({},o),this.apiGateway=i,this.redisClient=a,this.socketNamespace=s}physicSend(e){return i(this,void 0,void 0,(function*(){try{this.logger.debug(`Socket ${this.getId()} sending`,e),yield this.apiGateway.postToConnection({ConnectionId:this.getId(),Data:e}).promise(),this.logger.debug(`Socket ${this.getId()} send OK`,e)}catch(e){throw this.logger.debug(`Socket ${this.getId()} post error`,e),410===e.statusCode&&(this.logger.debug(`Stale socket ${this.getId()}`,this.isOpen()),this.isOpen()&&(this.logger.debug(`Disconnecting ${this.getId()}`),yield this.handleDisconnect()),this.logger.debug(`Removing socket ${this.getId()}`),yield this.socketManager.removeById(this.getId()),this.logger.debug(`Socket removed ${this.getId()}`)),e}}))}updateSocketInfo(){return i(this,void 0,void 0,(function*(){return new Promise(((e,t)=>this.redisClient.hset(this.socketNamespace,this.socketInfo.id||"",JSON.stringify(this.socketInfo),(n=>n?t(n):e()))))}))}physicDisconnect(){return i(this,void 0,void 0,(function*(){this.apiGateway.deleteConnection({ConnectionId:this.getId()}).promise().catch((e=>this.logger.error(e))),this.socketManager.removeById(this.getId()).catch((e=>{console.log("socket remove error",e)}))}))}setOpen(e){return i(this,void 0,void 0,(function*(){this.socketInfo.isOpen=e,yield this.updateSocketInfo()}))}addChannels(e){const t=Object.create(null,{addChannels:{get:()=>super.addChannels}});return i(this,void 0,void 0,(function*(){yield t.addChannels.call(this,e),yield this.updateSocketInfo()}))}removeChannels(e){const t=Object.create(null,{removeChannels:{get:()=>super.removeChannels}});return i(this,void 0,void 0,(function*(){yield t.removeChannels.call(this,e),yield this.updateSocketInfo()}))}authorize(e){const t=Object.create(null,{authorize:{get:()=>super.authorize}});return i(this,void 0,void 0,(function*(){yield t.authorize.call(this,e),yield this.updateSocketInfo()}))}serialize(){return JSON.stringify(this.socketInfo)}}let f=class AwsSocketManager extends u.AbstractServerSocketManager{constructor(e,t,n,r,o,i,s){super(s),this.region=e,this.socketDomainUrl=t,this.redisServerUrl=n,this.socketNamespace=r,this.httpRequestHandler=o,this.authorizationProvider=i,this.logger=s,this.redisClient=d.default.createClient({url:n}),this.apiGatewayManagement=new c.default.ApiGatewayManagementApi({region:e,apiVersion:"2018-11-29",endpoint:t})}configure(){this.logger.debug("Aws socket manager configure")}intercept(e){return i(this,void 0,void 0,(function*(){switch(e.method){case a.SocketMethod.CONNECT:{this.logger.debug("Aws socket connect",e.rawPath);let t=this.create({id:e.rawPath,isOpen:!0,authorized:!1,createdAt:Date.now()});return yield this.add(t),{code:200}}case a.SocketMethod.DISCONNECT:{this.logger.debug("Aws socket disconnect",e.rawPath);let t=yield this.getById(e.rawPath);return(null==t?void 0:t.isOpen())&&(yield null==t?void 0:t.handleDisconnect()),yield this.removeById(e.rawPath),{code:200}}case a.SocketMethod.MESSAGE:{this.logger.debug("Aws socket message",e.rawPath,e.body);let t=yield this.getById(e.rawPath);const{channel:n,message:r}=e.body;return yield null==t?void 0:t.handleMessage(n,r),{code:200}}default:return}}))}init(){return i(this,void 0,void 0,(function*(){this.logger.debug("AwsSocketManager: connecting to redis server"),yield new Promise(((e,t)=>{if(this.redisClient.connected&&this.redisClient)return e();this.redisClient.on("ready",e),this.redisClient.on("error",(()=>t(new a.ClaireError(a.Errors.SYSTEM_ERROR,"AwsSocketManager: cannot establish connection to redis server"))))})),this.logger.debug("AwsSocketManager: redis connection established")}))}exit(){this.redisClient.end(!0)}create(e){return new ApiGatewaySocket(this,this.logger,this.httpRequestHandler,this.authorizationProvider,e,this.apiGatewayManagement,this.socketNamespace,this.redisClient)}add(e){return i(this,void 0,void 0,(function*(){return new Promise(((t,n)=>this.redisClient.hset(this.socketNamespace,e.getId(),e.serialize(),(e=>e?n(e):t()))))}))}removeById(e){return i(this,void 0,void 0,(function*(){return new Promise(((t,n)=>this.redisClient.hdel(this.socketNamespace,e,(e=>e?n(e):t()))))}))}getById(e){return i(this,void 0,void 0,(function*(){const t=yield new Promise(((t,n)=>this.redisClient.hget(this.socketNamespace,e,((e,r)=>e?n(e):t(r)))));if(t)return this.logger.debug("Serialized aws socket",t),this.create(JSON.parse(t))}))}getAllSockets(){return i(this,void 0,void 0,(function*(){this.logger.debug("get all sockets called");return yield new Promise(((e,t)=>this.redisClient.hgetall(this.socketNamespace,((n,r)=>n?t(n):e(Object.keys(r).map((e=>{const t=r[e];return this.logger.debug("parsing serialized sockets",t),this.create(JSON.parse(t))})))))))}))}};f=r([a.Initable(),o("design:paramtypes",[String,String,String,String,l.AbstractHttpRequestHandler,p.AbstractHttpAuthorizationProvider,a.AbstractLogger])],f),t.AwsSocketManager=f},function(e,t){e.exports=require("redis")},function(e,t){e.exports=require("aws-sdk")},function(e,t,n){"use strict";var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function fulfilled(e){try{step(r.next(e))}catch(e){i(e)}}function rejected(e){try{step(r.throw(e))}catch(e){i(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((r=r.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.OwnedResourceAccessCondition=void 0;const o=n(0),i=n(8);t.OwnedResourceAccessCondition=e=>{const t=class extends i.AbstractAccessCondition{resolveRequestedConditionValue(t,n){return r(this,void 0,void 0,(function*(){return e(t,n)}))}validate(e){return r(this,void 0,void 0,(function*(){return!!e}))}getConditionMetadata(){return{name:"owned_resource",valueType:o.AccessConditionValueType.BOOLEAN}}};return o.getServiceProvider().register(t,"singleton"),t}}])}));
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 r in n)("object"==typeof exports?exports:e)[r]=n[r]}}(global,(function(){return function(e){var t={};function __webpack_require__(n){if(t[n])return t[n].exports;var r=t[n]={i:n,l:!1,exports:{}};return e[n].call(r.exports,r,r.exports,__webpack_require__),r.l=!0,r.exports}return __webpack_require__.m=e,__webpack_require__.c=t,__webpack_require__.d=function(e,t,n){__webpack_require__.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},__webpack_require__.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},__webpack_require__.t=function(e,t){if(1&t&&(e=__webpack_require__(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(__webpack_require__.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var r in e)__webpack_require__.d(n,r,function(t){return e[t]}.bind(null,r));return n},__webpack_require__.n=function(e){var t=e&&e.__esModule?function getDefault(){return e.default}:function getModuleExports(){return e};return __webpack_require__.d(t,"a",t),t},__webpack_require__.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},__webpack_require__.p="",__webpack_require__(__webpack_require__.s=26)}([function(e,t){e.exports=require("@clairejs/core")},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractHttpRequestHandler=void 0;t.AbstractHttpRequestHandler=class AbstractHttpRequestHandler{resolverMountPoint(e,t){if(!e)return"";const n=[];return n.push(...t),n.reduce(((e,t)=>`${e}/${t}`),"").replace(/(\/)\/+/g,"$1")}}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getDirectFields=t.getFieldByName=t.getTransactionFromContext=void 0;const r=n(0),o=n(7);t.getTransactionFromContext=e=>{const t=e[o.INJECTED_TRANSACTION];if(!t)throw new r.ClaireError(r.Errors.SYSTEM_ERROR,"Cannot get transaction from current context");return t},t.getFieldByName=(e,t)=>e.fields.find((e=>e.name===t)),t.getDirectFields=e=>e.fields.filter((e=>!e.hasManyProps))},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractHttpAuthorizationProvider=void 0;t.AbstractHttpAuthorizationProvider=class AbstractHttpAuthorizationProvider{}},function(e,t,n){"use strict";var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function fulfilled(e){try{step(r.next(e))}catch(e){i(e)}}function rejected(e){try{step(r.throw(e))}catch(e){i(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((r=r.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractServerSocketManager=void 0;const o=n(24);t.AbstractServerSocketManager=class AbstractServerSocketManager{constructor(e){this.logger=e}getAllAliveSockets(){return r(this,void 0,void 0,(function*(){const e=yield this.getAllSockets(),t=Date.now();return e.filter((e=>!e.isAuthorized()&&t-e.createdTime()>12e4)).forEach((e=>e.disconnect().catch((e=>this.logger.error(e))))),e.filter((e=>e.isOpen()&&e.isAuthorized()))}))}getSocketsByChannel(e){return r(this,void 0,void 0,(function*(){return(yield this.getAllAliveSockets()).filter((t=>t.getChannels().includes(e))).map((t=>new o.ServerSocket(e,t)))}))}}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HttpRequest=void 0;const r=n(0);t.HttpRequest=class HttpRequest{constructor(e,t){this.valueHolder={},this.method=e.method,this.pathName=e.pathName,this.headers=e.headers||{},this.hash=e.hash||"",this.socket=e.socket,this.params=e.params||{},(null==t?void 0:t.paramsDto)&&(this.params=r.validateDTO(this.params,t.paramsDto)),this.query=e.query||{},(null==t?void 0:t.queryDto)&&(this.query=r.validateDTO(this.jsonParsing(this.query,t.queryDto),t.queryDto)),this.body=e.body||{},t&&(t.httpMethod===r.HttpMethod.POST||t.httpMethod===r.HttpMethod.PUT)&&t.bodyDto&&(this.body=r.validateDTO(this.body||{},t.bodyDto))}jsonParsing(e,t){const n=Object.assign({},e);for(const o of t.fields)try{(void 0!==e[o.name]||o.isRequired)&&(n[o.name]=JSON.parse(e[o.name]))}catch(e){throw new r.ClaireError(r.Errors.BAD_REQUEST,`JSON parsing failed for field ${o.name}`)}return n}getAuthInfo(){return this.authInfo}setAuthInfo(e){this.authInfo=e}getHeaders(){return this.headers}getMethod(){return this.method}getHash(){return this.hash}getPathName(){return this.pathName}getValue(e){return this.valueHolder[e]}setValue(e,t){this.valueHolder[e]=t}getParams(){return this.params}getQuery(){return this.query}getBody(){return this.body}getSocket(){if(!this.socket)throw new r.ClaireError(r.Errors.SYSTEM_ERROR,"Socket not found for current request");return this.socket}}},function(e,t,n){"use strict";var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function fulfilled(e){try{step(r.next(e))}catch(e){i(e)}}function rejected(e){try{step(r.throw(e))}catch(e){i(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((r=r.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractHttpController=void 0;const o=n(0),i=n(2);t.AbstractHttpController=class AbstractHttpController{isEndpoint(e){return!!(e.httpMethod||void 0!==e.openAccess||e.queryDto||e.bodyDto||e.paramsDto||e.accessConditions)}getCurrentTransaction(){return r(this,void 0,void 0,(function*(){return i.getTransactionFromContext(this)}))}getEndpointMetadata(){const e=o.getObjectMetadata(this.constructor);return e?e.fields.filter((e=>this.isEndpoint(e))).map((t=>Object.assign(Object.assign({},t),{permissionGroup:e.permissionGroup}))):[]}}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ExitCode=t.INJECTED_TRANSACTION=void 0,t.INJECTED_TRANSACTION="__INJECTED_TRANSACTION__",t.ExitCode={SIGTERM_INTERUPTION:-1,SIGINT_INTERUPTION:-2,UNCAUGHT_EXCEPTION:-3,UNHANDLED_REJECTION:-4}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractAccessCondition=void 0;t.AbstractAccessCondition=class AbstractAccessCondition{}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TransactionLink=void 0,function(e){e.CREATE_NEW="create_new",e.INHERIT_OR_CREATE="inherit_or_create",e.INHERIT_OR_THROW="inherit_or_throw"}(t.TransactionLink||(t.TransactionLink={}))},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SqlProvider=t.NoSqlProvider=void 0,function(e){e.MONGODB="mongodb",e.DYNAMODB="dynamodb"}(t.NoSqlProvider||(t.NoSqlProvider={})),function(e){e.MYSQL="mysql",e.POSTGRES="postgres"}(t.SqlProvider||(t.SqlProvider={}))},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HttpResponse=void 0;t.HttpResponse=class HttpResponse{constructor(){this.code=200,this.headers={},this.cookies={}}setStatus(e){this.code=e}getStatus(){return this.code}setHeaders(e,t){this.headers[e]=t}getHeaders(){return this.headers}setCookie(e,t){this.cookies[e]=t}getCookies(){return this.cookies}}},function(e,t){e.exports=require("fs")},function(e,t){e.exports=require("path")},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AccessCondition=t.OpenAccess=t.Validator=t.Get=t.Del=t.Put=t.Post=t.Socket=t.Endpoint=t.Controller=void 0;const r=n(0);t.Controller=e=>t=>{r.getServiceProvider().register(t,"singleton");r.initObjectMetadata(t.prototype).permissionGroup=null==e?void 0:e.permissionGroup},t.Endpoint=e=>(t,n)=>{const o=r.initFieldMetadata(t,n);o.httpMethod=e.method,o.url=e.url},t.Socket=e=>(n,o)=>{t.Endpoint({method:r.SocketMethod.MESSAGE,url:e})(n,o)},t.Post=e=>(n,o)=>{t.Endpoint({method:r.HttpMethod.POST,url:e})(n,o)},t.Put=e=>(n,o)=>{t.Endpoint({method:r.HttpMethod.PUT,url:e})(n,o)},t.Del=e=>(n,o)=>{t.Endpoint({method:r.HttpMethod.DEL,url:e})(n,o)},t.Get=e=>(n,o)=>{t.Endpoint({method:r.HttpMethod.GET,url:e})(n,o)},t.Validator=e=>(t,n)=>{const o=r.initFieldMetadata(t,n);e.params&&(o.paramsDto=r.getObjectMetadata(e.params)),e.query&&(o.queryDto=r.getObjectMetadata(e.query)),e.body&&(o.bodyDto=r.getObjectMetadata(e.body))},t.OpenAccess=()=>(e,t)=>{r.initFieldMetadata(e,t).openAccess=!0},t.AccessCondition=e=>(t,n)=>{r.initFieldMetadata(t,n).accessConditions=e}},function(e,t,n){"use strict";var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function fulfilled(e){try{step(r.next(e))}catch(e){i(e)}}function rejected(e){try{step(r.throw(e))}catch(e){i(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((r=r.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.FilterModelFieldAccessCondition=void 0;const o=n(0),i=n(8);t.FilterModelFieldAccessCondition=(e,t)=>{const n=class extends i.AbstractAccessCondition{resolveRequestedConditionValue(e){return r(this,void 0,void 0,(function*(){return t(e)}))}getConditionMetadata(){return{name:"filter_model_field",valueType:o.AccessConditionValueType.CHOICES,valueConstraint:o.getObjectMetadata(e).fields.map((e=>e.name))}}validate(e,t){return r(this,void 0,void 0,(function*(){return!!e&&e.every((e=>t.includes(e)))}))}};return o.getServiceProvider().register(n),n}},function(e,t,n){"use strict";var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function fulfilled(e){try{step(r.next(e))}catch(e){i(e)}}function rejected(e){try{step(r.throw(e))}catch(e){i(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((r=r.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.Transactional=void 0;const o=n(0),i=n(7),s=n(9),a=n(17),getInjectedDatabaseAdapter=()=>{const e=o.getGlobalStore().databaseAdapter;if(!e)throw new o.ClaireError(o.Errors.SYSTEM_ERROR,"Database adapter does not present in server store");return e};t.Transactional=e=>(t,n,d)=>{const c=o.initObjectMetadata(t);o.initFieldMetadata(t,n),c.transactional=!0;const l=d.value;d.value=function(...d){return r(this,void 0,void 0,(function*(){const r=this;let c,u,h;try{c=yield r.getCurrentTransaction()}catch(e){}switch(e){case s.TransactionLink.CREATE_NEW:u=!0,h=yield getInjectedDatabaseAdapter().createTransaction();break;case s.TransactionLink.INHERIT_OR_CREATE:u=!c,h=c||(yield getInjectedDatabaseAdapter().createTransaction());break;case s.TransactionLink.INHERIT_OR_THROW:if(u=!1,!c)throw new o.ClaireError(o.Errors.SYSTEM_ERROR,`No transaction to inherit when executing ${t.constructor.name}:${n}`);h=c}const p=Object.assign(Object.create(r),r),f=Object.keys(p).filter((e=>{var t;return null===(t=o.getObjectMetadata(p[e].constructor))||void 0===t?void 0:t.transactional}));for(const e of f){const t=p[e],n=Object.assign(Object.create(t),t,{[i.INJECTED_TRANSACTION]:h});p[e]=n}try{Object.assign(p,{[i.INJECTED_TRANSACTION]:h});let e=yield l.call(p,...d);return h.getState()===a.TransactionState.EXECUTING&&u&&(yield h.commit()),e}catch(e){throw h.getState()===a.TransactionState.EXECUTING&&u&&(yield h.rollback()),new o.ClaireError(e.name||o.Errors.TRANSACTION_ERROR,e.message)}}))},Object.defineProperty(d.value,"name",{value:n})}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TransactionState=void 0,function(e){e.EXECUTING="executing",e.COMMITTED="commited",e.ROLLED_BACK="rolled_back"}(t.TransactionState||(t.TransactionState={}))},function(e,t,n){"use strict";var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function fulfilled(e){try{step(r.next(e))}catch(e){i(e)}}function rejected(e){try{step(r.throw(e))}catch(e){i(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((r=r.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.CrudService=void 0;const o=n(0),i=n(2),s=n(19);class CrudService{constructor(e){this.model=e,this.modelMetadata=o.getObjectMetadata(this.model)}getNestedQueries(e){return this.modelMetadata.fields.filter((e=>e.hasManyProps)).filter((t=>e.fields&&e.fields[t.name])).map((t=>{const n=this.getRequestQueryConditionFromQuery(e.fields[t.name],o.getObjectMetadata(o.getModelById(t.hasManyProps.id)));return{modelId:t.hasManyProps.id,queries:n.length?{_and:n}:{}}}))}getUploadHandler(){return r(this,void 0,void 0,(function*(){if(void 0===this.fileUploadHandler){const e=o.getServiceProvider().getInjector();this.fileUploadHandler=e.resolveOptional(s.AbstractFileUploadHandler)||null,yield e.initInstances()}return this.fileUploadHandler}))}getRequestQueryConditionFromQuery(e,t){const n=[];for(const r of i.getDirectFields(t))if(e[r.name])if(r.primaryKeyProps||r.foreignKeyProps)n.push({_in:{[r.name]:e[r.name]}});else if(r.enum)n.push({_in:{[r.name]:e[r.name]}});else switch(r.dataType){case o.DataType.STRING:if(r.searchable){const t={[r.caseSensitive?r.accentSensitive?"_sub":"_usub":r.accentSensitive?"_isub":"_iusub"]:{[r.name]:e[r.name]}};n.push(t)}else n.push({_eq:{[r.name]:e[r.name]}});break;case o.DataType.NUMBER:const t=new o.RangeQueryDto;Object.assign(t,e[r.name]),t.min&&(t.minExclusive?n.push({_gt:{[r.name]:t.min}}):n.push({_gte:{[r.name]:t.min}})),t.max&&(t.maxExclusive?n.push({_lt:{[r.name]:t.max}}):n.push({_lte:{[r.name]:t.max}}))}return n}beforeCreating(e,t){return r(this,void 0,void 0,(function*(){for(const n of t)for(const t of this.modelMetadata.fields)t.currentUser&&(n[t.name]=null==e?void 0:e.id)}))}uriHandling(e,t){var n;return r(this,void 0,void 0,(function*(){const r=yield this.getUploadHandler();if(!r)return;const o=t.use(this.model);for(const t of this.modelMetadata.fields)if(null===(n=t.mimeProps)||void 0===n?void 0:n.uriMapper)for(const n of e){const e=n[t.name],i=t.mimeProps.uriMapper(n);e&&i&&(yield r.moveFile(e,i),n[t.name]=i,yield o.updateOne(n))}}))}beforeReturning(e){var t,n;return r(this,void 0,void 0,(function*(){const r=yield this.getUploadHandler();for(const o of e)for(const e of this.modelMetadata.fields)if((null===(t=e.mimeProps)||void 0===t?void 0:t.uriMapper)&&r){if(!o[e.name])continue;o[e.name]=(null===(n=e.mimeProps)||void 0===n?void 0:n.public)?yield r.resolvePublicUrl(o[e.name]):yield r.resolvePrivateUrl(o[e.name])}}))}project(e,t){return t?e.map((e=>t.reduce(((t,n)=>Object.assign(t,{[n]:e[n]})),{}))):e}createMany({principal:e,body:t,tx:n}){return r(this,void 0,void 0,(function*(){const r=i.getDirectFields(this.modelMetadata),s=this.modelMetadata.fields.filter((e=>!!e.hasManyProps)),a=t.records;t.records=a.map((e=>r.reduce(((t,n)=>Object.assign(t,void 0!==e[n.name]?{[n.name]:e[n.name]}:{})),{}))),yield this.beforeCreating(e,t.records);let d=t.records.length?yield n.use(this.model).createMany(t.records):[];yield this.uriHandling(d,n),yield this.beforeReturning(d);const c=this.modelMetadata.fields.filter((e=>e.primaryKeyProps||e.serverValue||e.serverModify||e.mimeProps)).map((e=>e.name));d=this.project(d,c);for(const r of s){const i=d.map(((e,t)=>(a[t][r.name]||[]).map((t=>Object.assign(Object.assign({},t),{[r.hasManyProps.field]:e.id}))))).reduce(((e,t)=>e.concat(t)),[]);if(i.length){const s=new CrudService(o.getModelById(r.hasManyProps.id));t.records=i;const a=yield s.createMany({principal:e,body:t,tx:n});for(let e=0;e<a.records.length;e++)i[e]=Object.assign(Object.assign({},i[e]),a.records[e]);for(let e=0;e<d.length;e++){const t=[];for(let n=0;n<i.length;n++)i[n][r.hasManyProps.field]===d[e].id&&t.push(a.records[e]);d[e]=Object.assign(Object.assign({},d[e]),{[r.name]:t})}}}return{records:d}}))}updateMany({principal:e,queries:t,body:n,tx:s}){return r(this,void 0,void 0,(function*(){let r={};const a=this.modelMetadata.fields.filter((e=>!!e.hasManyProps)),d=i.getDirectFields(this.modelMetadata).filter((e=>void 0!==n.update[e.name])),c=d.reduce(((e,t)=>Object.assign(e,{[t.name]:n.update[t.name]})),{});if(t.fields){const e=this.getRequestQueryConditionFromQuery(t.fields,this.modelMetadata);e.length&&(r={_and:[...e]})}const l=this.getNestedQueries(t);let u=[];if(l.length){const e=yield s.use(this.model).getMany(r,{projection:["id"]},l);u=e.records.map((e=>e.id)),u.length&&d.length&&(yield s.use(this.model).updateMany({_in:{id:u}},c,!1))}else if(d.length)u=yield s.use(this.model).updateMany(r,c,!0);else{const e=yield s.use(this.model).getMany(r,{projection:["id"]});u=e.records.map((e=>e.id))}let h=u.map((e=>Object.assign(Object.assign({},c),{id:e})));yield this.uriHandling(h,s),yield this.beforeReturning(h);for(const t of a){const r=n.update[t.name];if(void 0===r||!u.length)continue;if(u.length>1)throw new o.ClaireError(o.Errors.QUERY_ERROR,`Multiple records found while updating @HasMany field: ${t.name}`);const i=h.find((e=>e.id===u[0])),a=o.getModelById(t.hasManyProps.id),d=s.use(a),c=(yield d.getRecords({_eq:{[t.hasManyProps.field]:i.id}})).map((e=>e.id)),l=r.map((e=>e.id)).filter((e=>!!e)),p=c.filter((e=>!l.includes(e))),f=r.filter((e=>!e.id)).map((e=>Object.assign(Object.assign({},e),{[t.hasManyProps.field]:i.id}))),g=r.filter((e=>!!e.id));yield d.deleteMany({_in:{id:p}});const y=new CrudService(a);yield y.beforeCreating(e,f);const m=yield y.createMany({principal:e,body:{records:f},tx:s}),v=f.map(((e,t)=>Object.assign(Object.assign({},e),m.records[t])));i[t.name]=v.concat(g)}let p=["id"];return t.returning&&(p=[...p,...Object.keys(n.update).filter((e=>void 0!==n.update[e]))]),{modified:this.project(h,p)}}))}getMany({queries:e,tx:t}){var n;return r(this,void 0,void 0,(function*(){const r=[];if(e.fields&&r.push(...this.getRequestQueryConditionFromQuery(e.fields,this.modelMetadata)),e.ops&&r.push(e.ops),e.search){const t=this.modelMetadata.fields.filter((e=>e.searchable)).map((t=>({_iusub:{[t.name]:e.search}})));t.length&&r.push({_or:t})}const i=yield t.use(this.model).getMany(r.length?{_and:r}:{},{limit:e.limit,page:e.page,projection:e.projection,order:null===(n=e.order)||void 0===n?void 0:n.map((e=>{const t=Object.keys(e).find((t=>!!e[t]));return[t,e[t]]}))},this.getNestedQueries(e)),s=i.records.map((e=>e.id));for(const n of this.modelMetadata.fields){if(!n.hasManyProps||e.projection&&!e.projection.includes(n.name))continue;const r=o.getModelById(n.hasManyProps.id),a=new CrudService(r),d=yield a.getMany({queries:{fields:{[n.hasManyProps.field]:s}},tx:t});for(const e of i.records)e[n.name]=d.records.filter((t=>t[n.hasManyProps.field]===e.id))}return yield this.beforeReturning(i.records),{total:i.total,records:this.project(i.records,e.projection)}}))}deleteMany({queries:e,tx:t}){return r(this,void 0,void 0,(function*(){let n={};if(e.fields){const t=this.getRequestQueryConditionFromQuery(e.fields,this.modelMetadata);t.length&&(n={_and:[...t]})}const r=this.getNestedQueries(e);let o=[];if(r.length){const e=yield t.use(this.model).getRecords(n,{projection:["id"]},r);yield t.use(this.model).deleteMany({_in:{id:e.map((e=>e.id))}}),o=e.map((e=>e.id))}else o=yield t.use(this.model).deleteMany(n,e.returning);return{modified:o.map((e=>({id:e})))}}))}}t.CrudService=CrudService},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractFileUploadHandler=void 0;t.AbstractFileUploadHandler=class AbstractFileUploadHandler{}},function(e,t,n){"use strict";var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function fulfilled(e){try{step(r.next(e))}catch(e){i(e)}}function rejected(e){try{step(r.throw(e))}catch(e){i(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((r=r.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractDatabaseAdapter=void 0;const o=n(0);t.AbstractDatabaseAdapter=class AbstractDatabaseAdapter{constructor(){this.modelMetadata=[],this.models=[],this.modelConnections={}}init(){return r(this,void 0,void 0,(function*(){this.models=(o.getGlobalStore().models||[]).slice(),this.modelMetadata=this.models.map((e=>o.getObjectMetadata(e))),this.modelConnections=this.modelMetadata.reduce(((e,t)=>Object.assign(e,{[t.id]:{connection:void 0}})),{})}))}exit(){}}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractDatabaseMigrator=void 0;t.AbstractDatabaseMigrator=class AbstractDatabaseMigrator{}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HttpEndpoint=void 0;t.HttpEndpoint=class HttpEndpoint{getEndpointId(){return`${this.httpMethod}:${this.mount}`}}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractHttpMiddleware=void 0;t.AbstractHttpMiddleware=class AbstractHttpMiddleware{}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ServerSocket=void 0;t.ServerSocket=class ServerSocket{constructor(e,t){this.channel=e,this.socket=t}getId(){return this.socket.getId()}isAuthorized(){return this.socket.isAuthorized()}getAuthInfo(){return this.socket.getAuthInfo()}isOpen(){return this.socket.isOpen()}send(e){return this.socket.send({channel:this.channel,data:e})}disconnect(e){return this.socket.disconnect(e)}}},function(e,t,n){"use strict";var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function fulfilled(e){try{step(r.next(e))}catch(e){i(e)}}function rejected(e){try{step(r.throw(e))}catch(e){i(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((r=r.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractServerSocket=void 0;const o=n(0),i=n(5),s=n(11),a=n(22),d=n(24);t.AbstractServerSocket=class AbstractServerSocket{constructor(e,t,n){this.logger=e,this.requestHandler=t,this.authorizationProvider=n,this.socketInfo={}}addChannels(e){return r(this,void 0,void 0,(function*(){this.socketInfo.channels=(this.socketInfo.channels||[]).concat(e)}))}removeChannels(e){return r(this,void 0,void 0,(function*(){this.socketInfo.channels=(this.socketInfo.channels||[]).filter((t=>!e.includes(t)))}))}isOpen(){return!!this.socketInfo.isOpen}createdTime(){return this.socketInfo.createdAt||0}isAuthorized(){return!!this.socketInfo.authorized}getAuthInfo(){return this.socketInfo.authInfo}getId(){return this.socketInfo.id||""}getChannels(){var e;return(null===(e=this.socketInfo.channels)||void 0===e?void 0:e.slice())||[]}send(e){return r(this,void 0,void 0,(function*(){yield this.sendToSocket(o.SocketChannels.MESSAGE_CHANNEL,e)}))}disconnect(e){return r(this,void 0,void 0,(function*(){e&&this.sendToSocket(o.SocketChannels.DISCONNECTION_CHANNEL,e).catch((e=>this.logger.error(e))),this.physicDisconnect().catch((e=>this.logger.error(e)))}))}authorize(e){return r(this,void 0,void 0,(function*(){this.socketInfo.authorized=!0,this.socketInfo.authInfo=e,yield this.setOpen(!0),yield this.sendToSocket(o.SocketChannels.AUTHENTICATION_CHANNEL,{socketId:this.getId()})}))}sendToSocket(e,t){var n;return r(this,void 0,void 0,(function*(){null===(n=this.logger)||void 0===n||n.debug("Physic send",e,t),yield this.physicSend(JSON.stringify({channel:e,message:t}))}))}handleDisconnect(){return r(this,void 0,void 0,(function*(){if(yield this.setOpen(!1),this.isAuthorized())for(const e of this.getChannels())yield this.requestHandler.handle({method:o.SocketMethod.MESSAGE,rawPath:e,body:{},socket:this})}))}handleMessage(e,t){var n,c,l,u,h,p,f;return r(this,void 0,void 0,(function*(){switch(null===(n=this.logger)||void 0===n||n.debug("Handle message",e,t),e){case o.SocketChannels.PING_PONG_CHANNEL:yield this.sendToSocket(o.SocketChannels.PING_PONG_CHANNEL);break;case o.SocketChannels.AUTHENTICATION_CHANNEL:{const e=t,n=new i.HttpRequest({method:o.SocketMethod.MESSAGE,pathName:"",headers:{authorization:e.authorizationData}}),r=new s.HttpResponse;for(const e of this.requestHandler.getMiddleware())yield e.intercept(n,r);try{const e=yield this.authorizationProvider.resolvePrincipal(n);yield this.authorize(e)}catch(e){yield this.disconnect(e)}}break;case o.SocketChannels.CHANNEL_LEAVE_REQUEST:{const e=t;let n,r;try{yield this.removeChannels(e.channels),n=!0}catch(e){n=!1,r=e}yield this.sendToSocket(o.SocketChannels.CHANNEL_LEAVE_REQUEST,{success:n,channels:e.channels,error:r})}break;case o.SocketChannels.CHANNEL_JOIN_REQUEST:{const e=t;if(!this.isAuthorized())return;const n=e.channels.filter((e=>!this.getChannels().includes(e)));let r,s=!0;for(const e of n){const t=new a.HttpEndpoint;t.httpMethod=o.SocketMethod.MESSAGE,t.mount=`/${e}`;const n=(o.getGlobalStore().mountedEndpointInfo||[]).find((e=>e.endpoint.getEndpointId()===t.getEndpointId()));if(!n){r=new o.ClaireError(o.Errors.SOCKET_ERROR,`Channel not found: ${e}`),s=!1;break}const d=new i.HttpRequest({method:o.SocketMethod.MESSAGE,pathName:`/${e}`});try{yield this.authorizationProvider.authorize(this.socketInfo.authInfo,d,n)}catch(t){r=new o.ClaireError(o.Errors.SOCKET_ERROR,`Not permitted to join: ${e}`),s=!1;break}}if(null===(c=this.logger)||void 0===c||c.debug("Sending channel connection success message"),yield this.sendToSocket(o.SocketChannels.CHANNEL_JOIN_REQUEST,{success:s,channels:e.channels,error:r}),!s)return;null===(l=this.logger)||void 0===l||l.debug("Not authenticated channels",n,e.channels),yield this.addChannels(n),null===(u=this.logger)||void 0===u||u.debug("Invoking socket connection handler");for(const t of e.channels){const e=new d.ServerSocket(t,this);null===(h=this.logger)||void 0===h||h.debug("Invoking",t),null===(p=this.logger)||void 0===p||p.debug("Socket status",e.getId(),e.isOpen()),yield this.requestHandler.handle({method:o.SocketMethod.MESSAGE,rawPath:t,socket:e}),null===(f=this.logger)||void 0===f||f.debug("Invoke success",t)}}break;case o.SocketChannels.MESSAGE_CHANNEL:{if(!this.isAuthorized())return;const e=t;if(!this.getChannels().includes(e.channel))return;yield this.requestHandler.handle({method:o.SocketMethod.MESSAGE,rawPath:e.channel,socket:new d.ServerSocket(e.channel,this),body:e.data})}break;case o.SocketChannels.DISCONNECTION_CHANNEL:yield this.handleDisconnect(),yield this.disconnect()}}))}}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LambdaWrapper=t.ExpressWrapper=t.AbstractService=t.ClaireServer=t.AbstractFileUploadHandler=t.CrudService=t.SqlProvider=t.DefaultSqlDatabaseMigrator=t.DefaultSqlDatabaseAdapter=t.TransactionLink=t.AbstractDatabaseMigrator=t.AbstractDatabaseAdapter=t.OwnedResourceAccessCondition=t.FilterModelFieldAccessCondition=t.AbstractHttpAuthorizationProvider=t.AbstractAccessCondition=t.AccessCondition=t.OpenAccess=t.AwsSocketManager=t.LocalSocketManager=t.AbstractServerSocketManager=t.AbstractHttpMiddleware=t.DefaultHttpRequestHandler=t.CrudHttpController=t.AbstractHttpRequestHandler=t.AbstractHttpController=t.HttpResponse=t.HttpRequest=t.Transactional=t.Validator=t.Post=t.Put=t.Del=t.Get=t.Socket=t.Endpoint=t.Controller=t.FileLogMedium=void 0;const r=n(27);Object.defineProperty(t,"FileLogMedium",{enumerable:!0,get:function(){return r.FileLogMedium}});const o=n(14);Object.defineProperty(t,"Controller",{enumerable:!0,get:function(){return o.Controller}}),Object.defineProperty(t,"Endpoint",{enumerable:!0,get:function(){return o.Endpoint}}),Object.defineProperty(t,"Validator",{enumerable:!0,get:function(){return o.Validator}}),Object.defineProperty(t,"AccessCondition",{enumerable:!0,get:function(){return o.AccessCondition}}),Object.defineProperty(t,"OpenAccess",{enumerable:!0,get:function(){return o.OpenAccess}}),Object.defineProperty(t,"Get",{enumerable:!0,get:function(){return o.Get}}),Object.defineProperty(t,"Del",{enumerable:!0,get:function(){return o.Del}}),Object.defineProperty(t,"Put",{enumerable:!0,get:function(){return o.Put}}),Object.defineProperty(t,"Post",{enumerable:!0,get:function(){return o.Post}}),Object.defineProperty(t,"Socket",{enumerable:!0,get:function(){return o.Socket}});const i=n(5);Object.defineProperty(t,"HttpRequest",{enumerable:!0,get:function(){return i.HttpRequest}});const s=n(6);Object.defineProperty(t,"AbstractHttpController",{enumerable:!0,get:function(){return s.AbstractHttpController}});const a=n(28);Object.defineProperty(t,"CrudHttpController",{enumerable:!0,get:function(){return a.CrudHttpController}});const d=n(29);Object.defineProperty(t,"ClaireServer",{enumerable:!0,get:function(){return d.ClaireServer}});const c=n(16);Object.defineProperty(t,"Transactional",{enumerable:!0,get:function(){return c.Transactional}});const l=n(9);Object.defineProperty(t,"TransactionLink",{enumerable:!0,get:function(){return l.TransactionLink}});const u=n(30);Object.defineProperty(t,"DefaultSqlDatabaseAdapter",{enumerable:!0,get:function(){return u.DefaultSqlDatabaseAdapter}});const h=n(33);Object.defineProperty(t,"DefaultSqlDatabaseMigrator",{enumerable:!0,get:function(){return h.DefaultSqlDatabaseMigrator}});const p=n(10);Object.defineProperty(t,"SqlProvider",{enumerable:!0,get:function(){return p.SqlProvider}});const f=n(35);Object.defineProperty(t,"DefaultHttpRequestHandler",{enumerable:!0,get:function(){return f.DefaultHttpRequestHandler}});const g=n(20);Object.defineProperty(t,"AbstractDatabaseAdapter",{enumerable:!0,get:function(){return g.AbstractDatabaseAdapter}});const y=n(39);Object.defineProperty(t,"AbstractService",{enumerable:!0,get:function(){return y.AbstractService}});const m=n(8);Object.defineProperty(t,"AbstractAccessCondition",{enumerable:!0,get:function(){return m.AbstractAccessCondition}});const v=n(3);Object.defineProperty(t,"AbstractHttpAuthorizationProvider",{enumerable:!0,get:function(){return v.AbstractHttpAuthorizationProvider}});const b=n(15);Object.defineProperty(t,"FilterModelFieldAccessCondition",{enumerable:!0,get:function(){return b.FilterModelFieldAccessCondition}});const C=n(1);Object.defineProperty(t,"AbstractHttpRequestHandler",{enumerable:!0,get:function(){return C.AbstractHttpRequestHandler}});const M=n(23);Object.defineProperty(t,"AbstractHttpMiddleware",{enumerable:!0,get:function(){return M.AbstractHttpMiddleware}});const O=n(11);Object.defineProperty(t,"HttpResponse",{enumerable:!0,get:function(){return O.HttpResponse}});const S=n(40);Object.defineProperty(t,"ExpressWrapper",{enumerable:!0,get:function(){return S.ExpressWrapper}});const _=n(45);Object.defineProperty(t,"LambdaWrapper",{enumerable:!0,get:function(){return _.LambdaWrapper}});const A=n(21);Object.defineProperty(t,"AbstractDatabaseMigrator",{enumerable:!0,get:function(){return A.AbstractDatabaseMigrator}});const T=n(4);Object.defineProperty(t,"AbstractServerSocketManager",{enumerable:!0,get:function(){return T.AbstractServerSocketManager}});const w=n(46);Object.defineProperty(t,"LocalSocketManager",{enumerable:!0,get:function(){return w.LocalSocketManager}});const P=n(48);Object.defineProperty(t,"AwsSocketManager",{enumerable:!0,get:function(){return P.AwsSocketManager}});const j=n(51);Object.defineProperty(t,"OwnedResourceAccessCondition",{enumerable:!0,get:function(){return j.OwnedResourceAccessCondition}});const E=n(19);Object.defineProperty(t,"AbstractFileUploadHandler",{enumerable:!0,get:function(){return E.AbstractFileUploadHandler}});const R=n(18);Object.defineProperty(t,"CrudService",{enumerable:!0,get:function(){return R.CrudService}})},function(e,t,n){"use strict";var r,o=this&&this.__decorate||function(e,t,n,r){var o,i=arguments.length,s=i<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(i<3?o(s):i>3?o(t,n,s):o(t,n))||s);return i>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)},s=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function fulfilled(e){try{step(r.next(e))}catch(e){i(e)}}function rejected(e){try{step(r.throw(e))}catch(e){i(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((r=r.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(12)),c=a(n(13)),l=n(0);let u=r=class FileLogMedium{constructor(e){const t=e.separated?r.levels.map((t=>c.default.join(e.destination,t+".log"))):[e.destination];this.destination=t.map((e=>(d.default.existsSync(c.default.dirname(e))||d.default.mkdirSync(c.default.dirname(e),{recursive:!0}),d.default.openSync(e,"a")))),this.separated=!!e.separated}init(){return s(this,void 0,void 0,(function*(){}))}exit(){this.destination.forEach((e=>d.default.closeSync(e)))}write(e,t){const n=this.separated?this.destination[r.levels.indexOf(e)]:0;d.default.appendFileSync(n,t)}};u.levels=Object.values(l.LogLevel),u=r=o([l.Initable(),i("design:paramtypes",[Object])],u),t.FileLogMedium=u},function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var o,i=arguments.length,s=i<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(i<3?o(s):i>3?o(t,n,s):o(t,n))||s);return i>3&&s&&Object.defineProperty(t,n,s),s},o=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},i=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function fulfilled(e){try{step(r.next(e))}catch(e){i(e)}}function rejected(e){try{step(r.throw(e))}catch(e){i(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((r=r.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.CrudHttpController=void 0;const s=n(0),a=n(15),d=n(5),c=n(16),l=n(9),u=n(14),h=n(6),p=n(18),f=n(3);class CrudHttpController extends h.AbstractHttpController{constructor(e,t){super();const n=s.getObjectMetadata(e);this.model=s.getModelById(n.id),this.modelMetadata=s.getObjectMetadata(this.model),s.getGlobalStore().databaseAdapter=t}getMountedUrl(e){return`/${this.modelMetadata.id}${e?"/"+e:""}`}static queryFieldDto(e){class FieldsDto{}const t={fields:CrudHttpController.getRequestQueryFieldFromModel(e)},n={name:"fields"};return n.dataType=s.DataType.OBJECT,s.setObjectMetadata(FieldsDto,t),n.objectTypeConstructor=FieldsDto,n}static queryOpsDto(e){class OpsDto{}const t={name:"ops"};return t.dataType=s.DataType.OBJECT,s.setObjectMetadata(OpsDto,{fields:[]}),t.objectTypeConstructor=OpsDto,t}static projectionFieldDto(e){const t={name:"projection"};return t.dataType=s.DataType.ARRAY,t.vectorProps={superSet:e.fields.map((e=>e.name)),allowDuplicated:!1,minLength:1,elementDataType:s.DataType.STRING},t}static getBodyDtoRecordClass(e,t,n){class InstanceDto{}const r={fields:[],strict:!0},o=e.fields.filter((e=>!e.serverValue||e.serverValue&&e.primaryKeyProps&&!t&&!n)),i=e.fields.filter((e=>!!e.hasManyProps));return r.fields.push(...o.map((e=>Object.assign(Object.assign({},e),{isRequired:t?e.isRequired:t}))),...i.map((e=>({name:e.name,dataType:s.DataType.ARRAY,vectorProps:{elementDataType:s.DataType.OBJECT,minLength:0},objectTypeConstructor:CrudHttpController.getBodyDtoRecordClass(s.getObjectMetadata(s.getModelById(e.hasManyProps.id)),t,!1)})))),s.setObjectMetadata(InstanceDto,r),InstanceDto}static getRequestQueryFieldFromModel(e){return e.fields.map((e=>{const t={};if(t.name=e.name,t.isRequired=!1,e.primaryKeyProps||e.foreignKeyProps)t.dataType=s.DataType.ARRAY,t.vectorProps={elementDataType:e.dataType,allowDuplicated:!1,minLength:1};else if(e.enum)t.dataType=s.DataType.ARRAY,t.vectorProps={superSet:e.enum,allowDuplicated:!1,minLength:1,elementDataType:e.dataType};else switch(e.dataType){case s.DataType.STRING:t.dataType=s.DataType.STRING;break;case s.DataType.NUMBER:t.dataType=s.DataType.OBJECT,t.objectTypeConstructor=s.RangeQueryDto}return t}))}getAuthProvider(){return i(this,void 0,void 0,(function*(){if(void 0===this.authProvider){const e=s.getServiceProvider().getInjector();this.authProvider=e.resolveOptional(f.AbstractHttpAuthorizationProvider)||null,yield e.initInstances()}return this.authProvider}))}createManyEndpoinMetadata(){const e={};return e.httpMethod=s.HttpMethod.POST,e.url=this.getMountedUrl(),e.name=CrudHttpController.prototype.createMany.name,e.displayName="createMany"+this.model.name,e.bodyDto=CrudHttpController.getCreateManyBodyValidator(this.modelMetadata),e}getManyEndpointMetadata(){const e={};return e.httpMethod=s.HttpMethod.GET,e.url=this.getMountedUrl(),e.name=CrudHttpController.prototype.getMany.name,e.displayName="getAll"+this.model.name,e.queryDto=CrudHttpController.getGetManyQueryValidator(this.modelMetadata),e.accessConditions=[a.FilterModelFieldAccessCondition(this.model,(e=>e.getQuery().projection))],e}updateManyEndpoinMetadata(){const e={};return e.httpMethod=s.HttpMethod.PUT,e.url=this.getMountedUrl(),e.name=CrudHttpController.prototype.updateMany.name,e.displayName="update"+this.model.name,e.queryDto=CrudHttpController.getUpdateManyQueryValidator(this.modelMetadata),e.bodyDto=CrudHttpController.getUpdateManyBodyValidator(this.modelMetadata),e.accessConditions=[a.FilterModelFieldAccessCondition(this.model,(e=>Object.keys(e.getBody().update)))],e}deleteManyEndpoinMetadata(){const e={};return e.httpMethod=s.HttpMethod.DEL,e.url=this.getMountedUrl(),e.name=CrudHttpController.prototype.deleteMany.name,e.displayName="delete"+this.model.name,e.queryDto=CrudHttpController.getUpdateManyQueryValidator(this.modelMetadata),e}static getCreateManyBodyValidator(e){const t={fields:[],strict:!0},n={name:"records"};return n.dataType=s.DataType.ARRAY,n.isRequired=!0,n.vectorProps={elementDataType:s.DataType.OBJECT,minLength:0},n.objectTypeConstructor=CrudHttpController.getBodyDtoRecordClass(e,!0,!0),t.fields.push(n),t}static getGetManyQueryValidator(e){const t={fields:[CrudHttpController.queryFieldDto(e),CrudHttpController.queryOpsDto(e)]},n={name:"search"};n.dataType=s.DataType.STRING,t.fields.push(n),t.fields.push(CrudHttpController.projectionFieldDto(e));const r={name:"order"};r.dataType=s.DataType.ARRAY,r.vectorProps={elementDataType:s.DataType.OBJECT,minLength:1};class SortElementDto{}const o={fields:[],strict:!0};o.fields.push(...e.fields.map((e=>{const t={};return t.name=e.name,t.isRequired=!1,t.dataType=s.DataType.OBJECT,t.enum=Object.values(s.OrderDirection),t}))),s.setObjectMetadata(SortElementDto,o),r.objectTypeConstructor=SortElementDto,t.fields.push(r);const i={name:"limit"};i.dataType=s.DataType.NUMBER,i.rangeProps={min:1},t.fields.push(i);const a={name:"page"};return a.dataType=s.DataType.NUMBER,a.rangeProps={min:1},t.fields.push(a),t}static getUpdateManyQueryValidator(e){const t={name:"returning"};return t.dataType=s.DataType.BOOLEAN,t.isRequired=!1,{fields:[t,CrudHttpController.queryFieldDto(e),CrudHttpController.queryOpsDto(e)]}}static getUpdateManyBodyValidator(e){const t={fields:[],strict:!0},n={name:"update"};return n.dataType=s.DataType.OBJECT,n.objectTypeConstructor=CrudHttpController.getBodyDtoRecordClass(e,!1,!0),t.fields.push(n),t}static createManyBodyValidator(e){class Validator{}return s.setObjectMetadata(Validator,CrudHttpController.getCreateManyBodyValidator(s.getObjectMetadata(e))),Validator}static getManyQueryValidator(e){class Validator{}return s.setObjectMetadata(Validator,CrudHttpController.getGetManyQueryValidator(s.getObjectMetadata(e))),Validator}static updateManyQueryValidator(e){class Validator{}return s.setObjectMetadata(Validator,CrudHttpController.getUpdateManyQueryValidator(s.getObjectMetadata(e))),Validator}static updateManyBodyValidator(e){class Validator{}return s.setObjectMetadata(Validator,CrudHttpController.getUpdateManyBodyValidator(s.getObjectMetadata(e))),Validator}getEndpointMetadata(){var e,t,n,r;const o=super.getEndpointMetadata(),i=[];(null===(e=this.modelMetadata.ignoreCrud)||void 0===e?void 0:e.includes(s.HttpMethod.GET))?o.splice(o.findIndex((e=>e.name===CrudHttpController.prototype.getMany.name)),1):i.push(this.getManyEndpointMetadata()),(null===(t=this.modelMetadata.ignoreCrud)||void 0===t?void 0:t.includes(s.HttpMethod.POST))?o.splice(o.findIndex((e=>e.name===CrudHttpController.prototype.createMany.name)),1):i.push(this.createManyEndpoinMetadata()),(null===(n=this.modelMetadata.ignoreCrud)||void 0===n?void 0:n.includes(s.HttpMethod.PUT))?o.splice(o.findIndex((e=>e.name===CrudHttpController.prototype.updateMany.name)),1):i.push(this.updateManyEndpoinMetadata()),(null===(r=this.modelMetadata.ignoreCrud)||void 0===r?void 0:r.includes(s.HttpMethod.DEL))?o.splice(o.findIndex((e=>e.name===CrudHttpController.prototype.deleteMany.name)),1):i.push(this.deleteManyEndpoinMetadata());for(const e of i){const t=o.findIndex((t=>t.httpMethod===e.httpMethod&&t.url===e.url||t.name===e.name));t>=0?o[t]=Object.assign(Object.assign(Object.assign({},e),o[t]),{accessConditions:[...e.accessConditions||[],...o[t].accessConditions||[]]}):o.push(e)}return o}createMany(e){return i(this,void 0,void 0,(function*(){const t=yield this.getCurrentTransaction(),n=new p.CrudService(this.model),r=yield this.getAuthProvider(),o=r&&(yield r.resolvePrincipal(e));return n.createMany({principal:o,body:e.getBody(),tx:t})}))}getMany(e){return i(this,void 0,void 0,(function*(){const t=yield this.getCurrentTransaction();return new p.CrudService(this.model).getMany({queries:e.getQuery(),tx:t})}))}updateMany(e){return i(this,void 0,void 0,(function*(){const t=yield this.getCurrentTransaction(),n=yield this.getAuthProvider(),r=n&&(yield n.resolvePrincipal(e));return new p.CrudService(this.model).updateMany({principal:r,queries:e.getQuery(),body:e.getBody(),tx:t})}))}deleteMany(e){return i(this,void 0,void 0,(function*(){const t=yield this.getCurrentTransaction();return new p.CrudService(this.model).deleteMany({queries:e.getQuery(),tx:t})}))}}r([c.Transactional(l.TransactionLink.INHERIT_OR_CREATE),u.AccessCondition([]),o("design:type",Function),o("design:paramtypes",[d.HttpRequest]),o("design:returntype",Promise)],CrudHttpController.prototype,"createMany",null),r([c.Transactional(l.TransactionLink.INHERIT_OR_CREATE),u.AccessCondition([]),o("design:type",Function),o("design:paramtypes",[d.HttpRequest]),o("design:returntype",Promise)],CrudHttpController.prototype,"getMany",null),r([c.Transactional(l.TransactionLink.INHERIT_OR_CREATE),u.AccessCondition([]),o("design:type",Function),o("design:paramtypes",[d.HttpRequest]),o("design:returntype",Promise)],CrudHttpController.prototype,"updateMany",null),r([c.Transactional(l.TransactionLink.INHERIT_OR_CREATE),u.AccessCondition([]),o("design:type",Function),o("design:paramtypes",[d.HttpRequest]),o("design:returntype",Promise)],CrudHttpController.prototype,"deleteMany",null),t.CrudHttpController=CrudHttpController},function(e,t,n){"use strict";var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function fulfilled(e){try{step(r.next(e))}catch(e){i(e)}}function rejected(e){try{step(r.throw(e))}catch(e){i(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((r=r.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.ClaireServer=void 0;const o=n(0),i=n(7);class ClaireServer extends o.ClaireApp{constructor(){super(),this.injector=o.getServiceProvider().getInjector(),this.booted=!1,this.logger=this.injector.resolve(o.AbstractLogger)}init(){return r(this,void 0,void 0,(function*(){this.booted||(yield this.injector.initInstances(),this.logger.debug("Claire server initing"),this.logger.debug("Setting up exception handlers"),process.on("SIGTERM",(()=>(this.logger.warn("SIGTERM interrupt signal"),this.stop(i.ExitCode.SIGTERM_INTERUPTION)))),process.on("SIGINT",(()=>(this.logger.warn("SIGINT interrupt signal"),this.stop(i.ExitCode.SIGTERM_INTERUPTION)))),process.on("uncaughtException",(e=>(this.logger.error("uncaughtException",e.name,e.stack),this.stop(i.ExitCode.UNCAUGHT_EXCEPTION)))),process.on("unhandledRejection",(e=>(this.logger.error("unhandledRejection",e.name,e.stack),this.stop(i.ExitCode.UNHANDLED_REJECTION)))),this.booted=!0)}))}exit(){super.exit()}stop(e){this.logger.debug("Server is shutting down"),this.exit(),process.exit(e)}}t.ClaireServer=ClaireServer},function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var o,i=arguments.length,s=i<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(i<3?o(s):i>3?o(t,n,s):o(t,n))||s);return i>3&&s&&Object.defineProperty(t,n,s),s},o=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},i=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function fulfilled(e){try{step(r.next(e))}catch(e){i(e)}}function rejected(e){try{step(r.throw(e))}catch(e){i(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((r=r.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSqlDatabaseAdapter=void 0;const s=n(0),a=n(31),d=n(17),c=n(20),l=n(32),u=n(10),h=n(2),getModelId=e=>{const t=s.getObjectMetadata(e);if(!t)throw new s.ClaireError(s.Errors.SYSTEM_ERROR,`Metadata for ${e.name} not found, check @Model decorator`);return t.id},p=["_and","_or"];class ModelAdapter extends l.AbstractQuery{constructor(e){super(e.model),this.dbConnection=e.dbConnection,this.modelConnections=e.modelConnections,this.transaction=e.transaction,this.sqlProvider=e.sqlProvider}getCurrentConnection(){const e=s.getObjectMetadata(this.model).id;return this.modelConnections[e].connection}resolveNestedIncludes(e){return e&&e.map((e=>({model:this.modelConnections[e.modelId].connection,where:this.getQueryObjectFromQueryConditions(e.queries)})))}count(e,t,n){return i(this,void 0,void 0,(function*(){const r={where:this.getQueryObjectFromQueryConditions(e),transaction:this.transaction,include:this.resolveNestedIncludes(n)};return(null==t?void 0:t.distinct)&&Object.assign(r,{distinct:!0,col:t.distinct}),yield this.getCurrentConnection().count(r)}))}getOne(e){return i(this,void 0,void 0,(function*(){const t=yield this.getMany(e,{limit:1});return t.records.length?t.records[0]:void 0}))}getRecords(e,t,n){return i(this,void 0,void 0,(function*(){return(yield this.getMany(e,t,n)).records}))}getMany(e,t,n){return i(this,void 0,void 0,(function*(){if(!this.getCurrentConnection())throw new s.ClaireError(s.Errors.SYSTEM_ERROR,"No active connection");let r={where:this.getQueryObjectFromQueryConditions(e),transaction:this.transaction,include:this.resolveNestedIncludes(n)};(null==t?void 0:t.order)&&Object.assign(r,{order:t.order}),(null==t?void 0:t.projection)&&Object.assign(r,{attributes:t.projection}),(null==t?void 0:t.limit)&&(r=Object.assign(r,{limit:t.limit}),t.page&&(r=Object.assign(r,{offset:t.limit*(t.page-1)})));let{count:o,rows:i}=yield this.getCurrentConnection().findAndCountAll(r);return{total:o,records:this.convertToLogicObjects(i,null==t?void 0:t.projection)}}))}createOne(e){return i(this,void 0,void 0,(function*(){return(yield this.createMany([e]))[0]}))}createMany(e){return i(this,void 0,void 0,(function*(){if(!this.getCurrentConnection())throw new s.ClaireError(s.Errors.SYSTEM_ERROR,"No active connection");let t=yield this.getCurrentConnection().bulkCreate(this.convertToDataObjects(e),{transaction:this.transaction});return this.convertToLogicObjects(t)}))}updateOne(e){return i(this,void 0,void 0,(function*(){return yield this.getCurrentConnection().update(this.convertToDataObjects([e])[0],{where:this.getQueryObjectFromQueryConditions({_eq:{id:e.id}}),transaction:this.transaction}),e}))}updateMany(e,t,n){return i(this,void 0,void 0,(function*(){if(n){const n=yield this.getRecords(e,{projection:["id"]});if(!n.length)return[];const r=n.map((e=>e.id));return yield this.getCurrentConnection().update(this.convertToDataObjects([t])[0],{where:this.getQueryObjectFromQueryConditions({_in:{id:r}}),transaction:this.transaction}),r}return yield this.getCurrentConnection().update(this.convertToDataObjects([t])[0],{where:this.getQueryObjectFromQueryConditions(e),transaction:this.transaction}),[]}))}deleteOne(e){return i(this,void 0,void 0,(function*(){return yield this.deleteMany({_eq:{id:e.id}}),e}))}deleteMany(e,t){return i(this,void 0,void 0,(function*(){if(t){const t=yield this.getMany(e);if(!t.records.length)return[];const n=t.records.map((e=>e.id));return yield this.getCurrentConnection().destroy({where:this.getQueryObjectFromQueryConditions({_in:{id:n}}),transaction:this.transaction}),n}return yield this.getCurrentConnection().destroy({where:this.getQueryObjectFromQueryConditions(e),transaction:this.transaction}),[]}))}rawQuery(e){return i(this,void 0,void 0,(function*(){return this.dbConnection.query(e,{transaction:this.transaction})}))}convertOp(e){return[a.Op.and,a.Op.or,a.Op.eq,a.Op.ne,a.Op.gt,a.Op.lt,a.Op.gte,a.Op.lte,a.Op.regexp,a.Op.like,a.Op.in][["_and","_or","_eq","_neq","_gt","_lt","_gte","_lte","_regex","_sub","_in"].indexOf(e)]}mapToSequelizeOperator(e,t,n){switch(e){case"_isub":switch(this.sqlProvider){case u.SqlProvider.POSTGRES:return{[t]:{[a.Op.iLike]:`%${n}%`}};default:return a.Sequelize.where(a.Sequelize.fn("lower",a.Sequelize.col(t)),{[a.Op.like]:`%${n.toLowerCase()}%`})}case"_sub":return{[t]:{[this.convertOp(e)]:`%${n}%`}};case"_usub":return a.Sequelize.where(a.Sequelize.fn("unaccent",a.Sequelize.col(t)),{[a.Op.like]:`%${n}%`});case"_iusub":switch(this.sqlProvider){case u.SqlProvider.POSTGRES:return a.Sequelize.where(a.Sequelize.fn("unaccent",a.Sequelize.col(t)),{[a.Op.iLike]:`%${n}%`});default:return a.Sequelize.where(a.Sequelize.fn("unaccent",a.Sequelize.fn("lower",a.Sequelize.col(t))),{[a.Op.like]:`%${n.toLowerCase()}%`})}default:return{[t]:{[this.convertOp(e)]:n}}}}getQueryObjectFromQueryConditions(e){if(!e)return{};const t=Object.keys(e);if(!t.length)return{};const n=t.map((t=>p.includes(t)?{[this.convertOp(t)]:e[t].map((e=>this.getQueryObjectFromQueryConditions(e)))}:{[this.convertOp("_and")]:Object.keys(e[t]).map((n=>this.mapToSequelizeOperator(t,n,e[t][n])))}));return n.length>1?{[this.convertOp("_and")]:n}:n[0]}}class TransactionAdapter{constructor(e){this.modelAdapters={},this.transaction=e.transaction,this.dbConnection=e.dbConnection,this.logger=e.logger,this.modelConnections=e.modelConnections,this.sqlProvider=e.sqlProvider,this.transactionState=d.TransactionState.EXECUTING}use(e){const t=getModelId(e);let n=this.modelAdapters[t];return n||(this.modelAdapters,n=new ModelAdapter({model:e,dbConnection:this.dbConnection,modelConnections:this.modelConnections,logger:this.logger,transaction:this.transaction,sqlProvider:this.sqlProvider}),this.modelAdapters[t]=n),n}commit(){return i(this,void 0,void 0,(function*(){return this.transactionState=d.TransactionState.COMMITTED,this.transaction.commit()}))}rollback(){return i(this,void 0,void 0,(function*(){return this.transactionState=d.TransactionState.ROLLED_BACK,this.transaction.rollback()}))}getState(){return this.transactionState}}let f=class DefaultSqlDatabaseAdapter extends c.AbstractDatabaseAdapter{constructor(e,t,n){super(),this.logger=n,this.injector=s.getServiceProvider().getInjector(),this.modelAdapters={},this.sqlProvider=e,this.dbConnection=new a.Sequelize(`${e}://${t}`,{dialect:this.sqlProvider,logging:!1,define:{timestamps:!1}})}createTransaction(){return i(this,void 0,void 0,(function*(){let e=yield this.dbConnection.transaction();return new TransactionAdapter({transaction:e,dbConnection:this.dbConnection,logger:this.logger,modelConnections:this.modelConnections,sqlProvider:this.sqlProvider})}))}init(){const e=Object.create(null,{init:{get:()=>super.init}});var t,n,r;return i(this,void 0,void 0,(function*(){yield e.init.call(this),yield this.injector.initInstances(),null===(t=this.logger)||void 0===t||t.debug("Connecting to database");try{yield this.dbConnection.authenticate()}catch(e){throw new s.ClaireError(s.Errors.SYSTEM_ERROR,e.stack||String(e))}null===(n=this.logger)||void 0===n||n.debug("Generating in-memory schema");for(const e of this.modelMetadata){const t=this.generateSchemaObject(e);this.modelConnections[e.id].connection=t}for(const e of this.modelMetadata){const t=this.modelConnections[e.id].connection,n=e.fields.filter((e=>e.hasManyProps));for(const e of n)t.hasMany(this.modelConnections[e.hasManyProps.id].connection,{foreignKey:e.hasManyProps.field})}null===(r=this.logger)||void 0===r||r.debug("Database adapter init succeeded")}))}exit(){var e;return null===(e=this.logger)||void 0===e||e.debug("Closing connection to database"),this.dbConnection.close(),0}use(e){const t=getModelId(e);let n=this.modelAdapters[t];return n||(n=new ModelAdapter({model:e,dbConnection:this.dbConnection,modelConnections:this.modelConnections,logger:this.logger,sqlProvider:this.sqlProvider}),this.modelAdapters[t]=n),n}generateSchemaObject(e){let t={};for(const n of h.getDirectFields(e)){switch(t[n.name]={},n.dataType){case s.DataType.NUMBER:n.floating?t[n.name].type=a.DataTypes.FLOAT:n.isBigInt?t[n.name].type=a.DataTypes.BIGINT:t[n.name].type=a.DataTypes.INTEGER;break;case s.DataType.STRING:n.textLength?t[n.name].type=a.DataTypes.STRING(n.textLength):t[n.name].type=a.DataTypes.STRING;break;case s.DataType.BOOLEAN:t[n.name].type=a.DataTypes.BOOLEAN;break;case s.DataType.ARRAY:case s.DataType.OBJECT:t[n.name].type=a.DataTypes.TEXT}n.primaryKeyProps&&(t[n.name].primaryKey=!0,n.primaryKeyProps.isAutoIncrement&&(t[n.name].autoIncrement=!0)),void 0!==n.defaultValue&&(t[n.name].defaultValue=n.defaultValue),t[n.name].allowNull=!n.isRequired,n.isTimestamp&&n.serverValue&&(t[n.name].defaultValue=()=>Date.now())}return this.dbConnection.define(e.id,t,{tableName:e.id})}};f=r([s.Initable(),s.Injectable(),o("design:paramtypes",[String,String,s.AbstractLogger])],f),t.DefaultSqlDatabaseAdapter=f},function(e,t){e.exports=require("sequelize")},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractQuery=void 0;const r=n(0);t.AbstractQuery=class AbstractQuery{constructor(e){const t=r.getObjectMetadata(e);this.model=r.getModelById(t.id)||e,this.metadata=r.getObjectMetadata(this.model)}convertToLogicObjects(e,t){return e.map((e=>{let n=new this.model;return this.metadata.fields.filter((e=>!t||t.includes(e.name))).forEach((t=>{t.isBigInt?n[t.name]=Number(e[t.name]):t.vectorProps?n[t.name]=JSON.parse(e[t.name]):n[t.name]=e[t.name]})),n}))}convertToDataObjects(e){return e.map((e=>{var t;let n=new this.model;for(const r of this.metadata.fields){const o=e[r.name];(null===(t=r.serverModify)||void 0===t?void 0:t.fn)?n[r.name]=r.serverModify.fn(o):r.vectorProps?n[r.name]=JSON.stringify(o):n[r.name]=o}return n}))}}},function(e,t,n){"use strict";var r,o=this&&this.__decorate||function(e,t,n,r){var o,i=arguments.length,s=i<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(i<3?o(s):i>3?o(t,n,s):o(t,n))||s);return i>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)},s=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function fulfilled(e){try{step(r.next(e))}catch(e){i(e)}}function rejected(e){try{step(r.throw(e))}catch(e){i(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((r=r.apply(e,t||[])).next())}))},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSqlDatabaseMigrator=void 0;const d=a(n(13)),c=a(n(12)),l=n(34),u=n(0),h=(n(10),n(2)),p=n(21),uniqueGroupComparator=(e,t)=>!e.groupName&&!t.groupName&&e.fieldNames[0]===t.fieldNames[0]||!!e.groupName&&e.groupName===t.groupName;let f=r=class DefaultSqlDatabaseMigrator extends p.AbstractDatabaseMigrator{constructor(e,t,n,r){super(),this.logger=r,this.injector=u.getServiceProvider().getInjector(),this.cliPath=e,this.databaseURL=`${t}://${n}`,this.modelMetadata=(u.getGlobalStore().models||[]).map((e=>u.getObjectMetadata(e)))}init(){return s(this,void 0,void 0,(function*(){yield this.injector.initInstances()}))}exit(){}getUniqueConstraintGroups(e){const t=[],n=h.getDirectFields(e).filter((e=>!!e.uniqueProps));for(const e of n)if(e.uniqueProps.groupName){let n=t.find((t=>t.groupName===e.uniqueProps.groupName));n||(n={groupName:e.uniqueProps.groupName,fieldNames:[]},t.push(n)),n.fieldNames.push(e.name)}else t.push({fieldNames:[e.name]});return t}generateFieldPropertiesQuery(e){let t="{";if(e.primaryKeyProps&&(t+="primaryKey:true,",e.primaryKeyProps.isAutoIncrement&&(t+="autoIncrement:true,")),void 0!==e.defaultValue&&(t+=`defaultValue:${JSON.stringify(e.defaultValue)},`),t+=`allowNull:${e.isRequired?"false":"true"},`,void 0!==e.dataType)switch(e.dataType){case u.DataType.STRING:e.textLength?t+=`type:Sequelize.STRING(${e.textLength}),`:t+="type:Sequelize.TEXT,";break;case u.DataType.NUMBER:e.floating?t+="type:Sequelize.FLOAT,":e.isBigInt?t+="type:Sequelize.BIGINT,":t+="type:Sequelize.INTEGER,";break;case u.DataType.BOOLEAN:t+="type:Sequelize.BOOLEAN,";break;case u.DataType.ARRAY:case u.DataType.OBJECT:t+="type:Sequelize.TEXT,"}return t+="}",t}getUniqueConstraintUpDown(e,t){const n=`${e}_${t.groupName||t.fieldNames[0]}_un`;return[`queryInterface.addConstraint("${e}",{fields:${JSON.stringify(t.fieldNames)},type:"unique",name:"${n}","transaction":t})`,`queryInterface.removeConstraint("${e}","${n}",{"transaction":t})`]}getForeignKeyConstraintUpDown(e,t,n){var r;const o=`${t}_${n.name}_fk`;return[`queryInterface.addConstraint("${t}",{fields:["${n.name}"],type:"foreign key",name:"${o}",references:{table:"${e.id}",field:"id"}${(null===(r=n.foreignKeyProps)||void 0===r?void 0:r.cascade)?",onDelete:'CASCADE',onUpdate:'CASCADE'":""},"transaction":t})`,`queryInterface.removeConstraint("${t}","${o}",{"transaction":t})`]}getAddColumnUpDown(e,t){return[`queryInterface.addColumn('${e}','${t.name}',${this.generateFieldPropertiesQuery(t)},{"transaction":t})`,`queryInterface.removeColumn('${e}','${t.name}',{"transaction":t})`]}generateCreateTableQuery(e){let t={upTableAdd:[],downTableRemove:[],upConstraintAdd:[],downConstraintRemove:[],upTableRemove:[],downTableAdd:[],upConstraintRemove:[],downConstraintAdd:[]},n="",r="";n+="{\n";for(const t of h.getDirectFields(e)){let e=this.generateFieldPropertiesQuery(t);n+=`${t.name}:${e},\n`}n+="}\n",r+='{charset:"utf8",transaction:t}',t.upTableAdd.push(`queryInterface.createTable("${e.id}",${n},{charset:"utf8",transaction:t})`),t.downTableRemove.push(`queryInterface.dropTable("${e.id}",{"transaction":t})`);const o=this.getUniqueConstraintGroups(e);for(const n of o){const[r,o]=this.getUniqueConstraintUpDown(e.id,n);t.upConstraintAdd.push(r),t.downConstraintRemove.push(o)}for(const n of h.getDirectFields(e))if(n.foreignKeyProps){let r=this.modelMetadata.find((e=>{var t;return e.id===(null===(t=n.foreignKeyProps)||void 0===t?void 0:t.id)}));const[o,i]=this.getForeignKeyConstraintUpDown(r,e.id,n);t.upConstraintAdd.push(o),t.downConstraintRemove.push(i)}return t}isBooleanDiff(e,t){return!!e&&!t||!!t&&!e}runProcess(e){return s(this,void 0,void 0,(function*(){return new Promise(((t,n)=>{l.exec(e,{env:process.env},(e=>(e&&n(e),t())))}))}))}rollback(e){return s(this,void 0,void 0,(function*(){let t=d.default.join(e,"scripts");if(!c.default.existsSync)throw new u.ClaireError(u.Errors.MIGRATION_ERROR,"Migration directory not found");this.logger.debug("Rolling back last migration"),yield this.runProcess(`${this.cliPath} --url=${this.databaseURL} --migrations-path=${t} db:migrate:undo`),this.logger.debug("Rollback completed")}))}migrate(e){var t,n,o,i,a,l,p,f;return s(this,void 0,void 0,(function*(){let g=d.default.join(e,"metadata.json"),y=d.default.join(e,"scripts");c.default.existsSync(y)||(this.logger.debug("Migration directory not exists, creating empty folder"),c.default.mkdirSync(y,{recursive:!0})),c.default.existsSync(g)||(this.logger.debug("Migration metadata does not exist, creating one"),c.default.writeFileSync(g,JSON.stringify([]))),this.logger.debug("Parsing migration metadata file");let m=JSON.parse(String(c.default.readFileSync(g)));this.logger.debug("Calculating differences...");const v=this.modelMetadata.filter((e=>!m.find((t=>e.id===t.id)))),b=this.modelMetadata.filter((e=>m.find((t=>t.id===e.id)))).map((e=>e.id));let C=[];C.push(...v.map((e=>this.generateCreateTableQuery(e))));for(const e of b){const r=m.find((t=>t.id===e)),s=this.modelMetadata.find((t=>t.id===e));r.id!==s.id&&C.push({upTableAdd:[`queryInterface.query("ALTER TABLE ${r.id} RENAME TO ${s.id}",{"transaction":t})`],downTableRemove:[`queryInterface.query("ALTER TABLE ${s.id} RENAME TO ${r.id}",{"transaction":t})`],upConstraintAdd:[],downConstraintRemove:[],upTableRemove:[],downTableAdd:[],upConstraintRemove:[],downConstraintAdd:[]});let d={upTableAdd:[],downTableRemove:[],upConstraintAdd:[],downConstraintRemove:[],upTableRemove:[],downTableAdd:[],upConstraintRemove:[],downConstraintAdd:[]};const c=h.getDirectFields(r).filter((e=>!h.getDirectFields(s).find((t=>e.name===t.name))));for(const e of c){const[t,n]=this.getAddColumnUpDown(s.id,e);if(d.upTableRemove.push(n),d.downTableAdd.push(t),e.foreignKeyProps){let t=this.modelMetadata.find((t=>{var n;return t.id===(null===(n=e.foreignKeyProps)||void 0===n?void 0:n.id)}));const[n,r]=this.getForeignKeyConstraintUpDown(t,s.id,e);d.upConstraintRemove.push(r),d.downConstraintAdd.push(n)}}const u=h.getDirectFields(s).filter((e=>!h.getDirectFields(r).find((t=>e.name===t.name))));for(const e of u){const[t,n]=this.getAddColumnUpDown(s.id,e);if(d.upTableAdd.push(t),d.downTableRemove.push(n),e.foreignKeyProps){let t=this.modelMetadata.find((t=>{var n;return t.id===(null===(n=e.foreignKeyProps)||void 0===n?void 0:n.id)}));const[n,r]=this.getForeignKeyConstraintUpDown(t,s.id,e);d.upConstraintAdd.push(n),d.downConstraintRemove.push(r)}}const g=h.getDirectFields(s).filter((e=>h.getDirectFields(r).find((t=>e.name===t.name)))).map((e=>e.name));for(const e of g){const c=h.getFieldByName(r,e),u=h.getFieldByName(s,e);if((this.isBooleanDiff(c.isBigInt,u.isBigInt)||this.isBooleanDiff(c.isRequired,u.isRequired)||this.isBooleanDiff(null===(t=c.primaryKeyProps)||void 0===t?void 0:t.isAutoIncrement,null===(n=u.primaryKeyProps)||void 0===n?void 0:n.isAutoIncrement)||c.dataType!==u.dataType||c.textLength!==u.textLength||c.defaultValue!==u.defaultValue)&&(d.upTableAdd.push(`queryInterface.changeColumn("${s.id}","${u.name}",${this.generateFieldPropertiesQuery(u)},{"transaction":t})`),d.downTableRemove.push(`queryInterface.changeColumn("${s.id}","${c.name}",${this.generateFieldPropertiesQuery(c)},{"transaction":t})`)),(null===(o=c.foreignKeyProps)||void 0===o?void 0:o.id)!==(null===(i=u.foreignKeyProps)||void 0===i?void 0:i.id)||this.isBooleanDiff(null===(a=c.foreignKeyProps)||void 0===a?void 0:a.cascade,null===(l=u.foreignKeyProps)||void 0===l?void 0:l.cascade)){if(null===(p=c.foreignKeyProps)||void 0===p?void 0:p.id){const e=this.modelMetadata.find((e=>{var t;return e.id===(null===(t=c.foreignKeyProps)||void 0===t?void 0:t.id)})),[t,n]=this.getForeignKeyConstraintUpDown(e,s.id,c);d.upTableAdd.push(n),d.downTableRemove.push(t)}if(null===(f=u.foreignKeyProps)||void 0===f?void 0:f.id){const e=this.modelMetadata.find((e=>{var t;return e.id===(null===(t=u.foreignKeyProps)||void 0===t?void 0:t.id)})),[t,n]=this.getForeignKeyConstraintUpDown(e,s.id,u);d.upTableAdd.push(t),d.downTableRemove.push(n)}}}const y=this.getUniqueConstraintGroups(r),v=this.getUniqueConstraintGroups(s),b=y.filter((e=>!!v.find((t=>uniqueGroupComparator(e,t))))),M=y.filter((e=>!b.find((t=>uniqueGroupComparator(e,t)))));for(const e of M){const[t,n]=this.getUniqueConstraintUpDown(s.id,e);d.upConstraintRemove.push(n),d.downConstraintAdd.push(t)}const O=v.filter((e=>!b.find((t=>uniqueGroupComparator(e,t)))));for(const e of O){const[t,n]=this.getUniqueConstraintUpDown(s.id,e);d.upConstraintAdd.push(t),d.downConstraintRemove.push(n)}for(const e of b){const t=y.find((t=>uniqueGroupComparator(t,e))),n=v.find((t=>uniqueGroupComparator(t,e)));if(t.fieldNames.length!==n.fieldNames.length||t.fieldNames.some((e=>!n.fieldNames.includes(e)))){const[e,r]=this.getUniqueConstraintUpDown(s.id,t),[o,i]=this.getUniqueConstraintUpDown(s.id,n);d.upConstraintRemove.push(r),d.upConstraintAdd.push(o),d.downConstraintRemove.push(i),d.downConstraintAdd.push(e)}}(d.upTableAdd.length||d.downTableRemove.length||d.upConstraintAdd.length||d.downConstraintRemove.length||d.upConstraintRemove.length||d.downConstraintAdd.length||d.upTableRemove.length||d.downTableAdd.length)&&C.push(d)}if(C.length){let e=`${Date.now()}-auto-migration.js`;const getTransactionalScript=e=>`const t = await queryInterface.sequelize.transaction({autoCommit: false}); \n try {\n ${e.reduce(((e,t)=>e+`await ${t};`),"")}\n await t.commit();\n } catch(err){\n await t.rollback(); \n throw(err);\n }`,migrationFunction=(e,t)=>s(this,void 0,void 0,(function*(){if(!e.up.length&&!e.down.length)return;let n=d.default.join(y,t),o=r.MIGRATION_TEMPLATE,i=new RegExp(r.COMMENT_BLOCK_REGEX_PATTERN),s=getTransactionalScript(e.up),a=getTransactionalScript(e.down);o=o.replace(i,s),o=o.replace(i,a),this.logger.debug("Writing to file",n),c.default.writeFileSync(n,o)}));throw yield migrationFunction({up:[...C.reduce(((e,t)=>e.concat(t.upConstraintRemove)),[]),...C.reduce(((e,t)=>e.concat(t.upTableRemove)),[]),...C.reduce(((e,t)=>e.concat(t.upTableAdd)),[]),...C.reduce(((e,t)=>e.concat(t.upConstraintAdd)),[])],down:[...C.reduce(((e,t)=>e.concat(t.downConstraintRemove)),[]).reverse(),...C.reduce(((e,t)=>e.concat(t.downTableRemove)),[]).reverse(),...C.reduce(((e,t)=>e.concat(t.downTableAdd)),[]).reverse(),...C.reduce(((e,t)=>e.concat(t.downConstraintAdd)),[]).reverse()]},e),this.logger.debug("Updating metadata file"),c.default.writeFileSync(g,JSON.stringify(this.modelMetadata)),new u.ClaireError(u.Errors.MIGRATION_ERROR,e)}this.logger.debug("No difference, running migration"),this.logger.debug("Create database if not exist");try{yield this.runProcess(`${this.cliPath} --url=${this.databaseURL} db:create`)}catch(e){if(String(e).indexOf("already exists")<0)throw new u.ClaireError(u.Errors.MIGRATION_ERROR,e.stack||String(e))}this.logger.debug("Running migration"),yield this.runProcess(`${this.cliPath} --url=${this.databaseURL} --migrations-path=${y} db:migrate`),this.logger.debug("Migration finished")}))}};f.COMMENT_BLOCK_REGEX_PATTERN="/\\*(\\*(?!/)|[^*])*\\*\\/",f.MIGRATION_TEMPLATE="'use strict';\n module.exports = {\n up: async (queryInterface, Sequelize) => {\n /**\n */\n },\n \n down: async (queryInterface, Sequelize) => {\n /**\n */\n }\n };",f=r=o([u.Injectable(),i("design:paramtypes",[String,String,String,u.AbstractLogger])],f),t.DefaultSqlDatabaseMigrator=f},function(e,t){e.exports=require("child_process")},function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var o,i=arguments.length,s=i<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(i<3?o(s):i>3?o(t,n,s):o(t,n))||s);return i>3&&s&&Object.defineProperty(t,n,s),s},o=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},i=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function fulfilled(e){try{step(r.next(e))}catch(e){i(e)}}function rejected(e){try{step(r.throw(e))}catch(e){i(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((r=r.apply(e,t||[])).next())}))},s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultHttpRequestHandler=void 0;const a=n(0),d=s(n(36)),c=n(37),l=s(n(38)),u=n(11),h=n(5),p=n(3),f=n(1),g=n(22),y=n(23),m=n(6);let v=class DefaultHttpRequestHandler extends f.AbstractHttpRequestHandler{constructor(e,t){super(),this.logger=e,this.authorizationProvider=t,this.injector=a.getServiceProvider().getInjector(),this.mountPoint="",this.mountedEndpointInfo=[],this.middleware=this.injector.resolveMultiple(y.AbstractHttpMiddleware)}init(){var e,t,n,r;return i(this,void 0,void 0,(function*(){const o=[],s=this.injector.resolveMultiple(m.AbstractHttpController);yield this.injector.initInstances();for(const e of s){const t=a.getObjectMetadata(e.constructor),n=e.getEndpointMetadata();for(const r of n){const n=new g.HttpEndpoint;n.mount=this.resolverMountPoint(t,[this.mountPoint||"/",r.url]),n.httpMethod=r.httpMethod,n.handler=(t,o)=>i(this,void 0,void 0,(function*(){if(n.httpMethod!==a.SocketMethod.MESSAGE){const e=yield this.authorizationProvider.resolvePrincipal(t);t.setAuthInfo(e),r.openAccess||(yield this.authorizationProvider.authorize(e,t,{endpoint:n,endpointMetadata:r}))}return e[r.name](t,o)})),n.controller=e,n.handlerFunctionName=r.name,o.push({endpointMetadata:r,endpoint:n})}}this.mountedEndpointInfo=[];for(const i of o){const o=this.mountedEndpointInfo.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: ${o.endpoint.getEndpointId()} of ${null===(t=o.endpoint.controller)||void 0===t?void 0:t.constructor.name}:${o.endpoint.handlerFunctionName}`,`Ignore ${i.endpoint.getEndpointId()} of ${null===(n=i.endpoint.controller)||void 0===n?void 0:n.constructor.name}:${i.endpoint.handlerFunctionName}`):(null===(r=this.logger)||void 0===r||r.debug(`Mouting: ${i.endpoint.getEndpointId()}`),this.mountedEndpointInfo.push(i))}a.getGlobalStore().mountedEndpointInfo=this.mountedEndpointInfo}))}exit(){}handle(e){return i(this,void 0,void 0,(function*(){const t=e.method,n=d.default({url:e.rawPath});let r={};const o=this.mountedEndpointInfo.find((e=>{const o=e.endpointMetadata.httpMethod===t&&c.match(e.endpointMetadata.url,{decode:decodeURIComponent})(n.pathname);return!!o&&(r=o,!0)}));if(!o)throw this.logger.debug(e),new a.ClaireError(a.Errors.BAD_REQUEST,"Handler not found");const i=new h.HttpRequest({method:t,headers:e.headers,pathName:n.pathname||"",hash:n.hash||"",query:l.default.parse(n.search||""),params:r.params,body:e.body,socket:e.socket},o.endpointMetadata),s=new u.HttpResponse;if(t!==a.SocketMethod.MESSAGE)for(const e of this.getMiddleware())yield e.intercept(i,s);return{body:yield o.endpoint.handler&&o.endpoint.handler(i,s),code:s.getStatus(),cookies:s.getCookies(),headers:s.getHeaders()}}))}getMiddleware(){return this.middleware}};v=r([a.Initable(),o("design:paramtypes",[a.AbstractLogger,p.AbstractHttpAuthorizationProvider])],v),t.DefaultHttpRequestHandler=v},function(e,t){e.exports=require("parseurl")},function(e,t){e.exports=require("path-to-regexp")},function(e,t){e.exports=require("query-string")},function(e,t,n){"use strict";var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function fulfilled(e){try{step(r.next(e))}catch(e){i(e)}}function rejected(e){try{step(r.throw(e))}catch(e){i(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((r=r.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractService=void 0;const o=n(2);t.AbstractService=class AbstractService{getCurrentTransaction(){return r(this,void 0,void 0,(function*(){return o.getTransactionFromContext(this)}))}}},function(e,t,n){"use strict";var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function fulfilled(e){try{step(r.next(e))}catch(e){i(e)}}function rejected(e){try{step(r.throw(e))}catch(e){i(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((r=r.apply(e,t||[])).next())}))},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ExpressWrapper=void 0;const i=n(0),s=o(n(41)),a=o(n(42)),d=o(n(43)),c=o(n(44)),l=n(4),u=n(1);t.ExpressWrapper=class ExpressWrapper{constructor(e,t){this.injector=i.getServiceProvider().getInjector(),this.server=e,this.config=t,this.logger=this.injector.resolve(i.AbstractLogger),this.socketManager=this.injector.resolveOptional(l.AbstractServerSocketManager),this.httpRequestHandler=this.injector.resolve(u.AbstractHttpRequestHandler)}close(){var e;null===(e=this.httpServer)||void 0===e||e.close()}listen(e){var t,n;return r(this,void 0,void 0,(function*(){yield this.server.init(),yield this.injector.initInstances();const o=s.default(),i=a.default.createServer(o);return null===(t=this.socketManager)||void 0===t||t.configure(i),o.use(d.default()),o.use(s.default.raw({limit:1024*((null===(n=this.config)||void 0===n?void 0:n.maxBodySizeKB)||4096)})),o.use(c.default()),o.use(((e,t,n)=>{e.files&&(e.body||(e.body={}),Object.keys(e.files).forEach((t=>{e.body[t]=e.files[t]}))),n()})),o.use(s.default.urlencoded({extended:!1})),o.use(s.default.json()),o.all("*",((e,t)=>{(()=>r(this,void 0,void 0,(function*(){var n;const r=!!e.headers["x-amzn-apigateway-api-id"]?{method:e.body.type.toLowerCase(),rawPath:e.body.connectionId,body:e.body.data}:{rawPath:e.url,method:e.method.toLowerCase(),headers:e.headers,body:e.body};let o=yield null===(n=this.socketManager)||void 0===n?void 0:n.intercept(r);return o||(o=yield this.httpRequestHandler.handle(r)),o.headers&&Object.keys(o.headers).forEach((e=>{t.set(e,o.headers[e])})),t.status(o.code).send(o.body)})))().catch((e=>{this.logger.error(e),t.status(400).json(e)}))})),new Promise(((t,n)=>{this.httpServer=i.listen(e,t).on("error",n)}))}))}}},function(e,t){e.exports=require("express")},function(e,t){e.exports=require("http")},function(e,t){e.exports=require("cors")},function(e,t){e.exports=require("express-fileupload")},function(e,t,n){"use strict";var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function fulfilled(e){try{step(r.next(e))}catch(e){i(e)}}function rejected(e){try{step(r.throw(e))}catch(e){i(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((r=r.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.LambdaWrapper=void 0;const o=n(0),i=n(1),s=n(4),toApiGatewayFormat=(e,t)=>({statusCode:e,body:t&&JSON.stringify(t),headers:{"Access-Control-Allow-Headers":"*","Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"*","Content-Type":"application/json"}});t.LambdaWrapper=class LambdaWrapper{constructor(e,t){this.server=e,this.requestMapper=t,this.handler=this.handler.bind(this),this.injector=o.getServiceProvider().getInjector(),this.socketManager=this.injector.resolveOptional(s.AbstractServerSocketManager),this.httpRequestHandler=this.injector.resolve(i.AbstractHttpRequestHandler)}handler(e){var t,n;return r(this,void 0,void 0,(function*(){yield this.server.init(),yield this.injector.initInstances(),null===(t=this.socketManager)||void 0===t||t.configure();const r=this.requestMapper(e);if(!r)return toApiGatewayFormat(400,new o.ClaireError(o.Errors.BAD_REQUEST,"Cannot resolve event"));if(r.method===o.HttpMethod.OPTIONS)return toApiGatewayFormat(200);try{let e=yield null===(n=this.socketManager)||void 0===n?void 0:n.intercept(r);return e||(e=yield this.httpRequestHandler.handle(r)),toApiGatewayFormat(e.code,e.body)}catch(e){return toApiGatewayFormat(400,e)}}))}}},function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var o,i=arguments.length,s=i<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(i<3?o(s):i>3?o(t,n,s):o(t,n))||s);return i>3&&s&&Object.defineProperty(t,n,s),s},o=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},i=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function fulfilled(e){try{step(r.next(e))}catch(e){i(e)}}function rejected(e){try{step(r.throw(e))}catch(e){i(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((r=r.apply(e,t||[])).next())}))},s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.LocalSocketManager=void 0;const a=n(0),d=s(n(47)),c=n(1),l=n(3),u=n(4),h=n(25);class ExpressSocket extends h.AbstractServerSocket{constructor(e,t,n,r){super(e,t,n),this.logger=e,this.httpRequestHandler=t,this.authorizationProvider=n,this.socket=r;const o=Date.now();this.socketInfo={id:`${o.toString()}-${Math.trunc(1e6*Math.random())}`,isOpen:!0,authorized:!1,createdAt:o}}physicSend(e){return i(this,void 0,void 0,(function*(){this.socket.send(e)}))}setOpen(e){return i(this,void 0,void 0,(function*(){this.socketInfo.isOpen=e}))}physicDisconnect(){return i(this,void 0,void 0,(function*(){this.socket.close()}))}authorize(e){const t=Object.create(null,{authorize:{get:()=>super.authorize}});return i(this,void 0,void 0,(function*(){yield t.authorize.call(this,e)}))}}let p=class LocalSocketManager extends u.AbstractServerSocketManager{constructor(e,t,n){super(e),this.logger=e,this.httpRequestHandler=t,this.authorizationProvider=n,this.allSockets=[]}configure(e){if(this.logger.debug("Local socket manager configure"),!e)return;const t=this;new d.default.Server({server:e}).on("connection",(e=>{const n=t.create(e);this.logger.debug("Local socket manager socket connect",n.getId()),t.add(n).catch((e=>{this.logger.error(e)})),e.onmessage=e=>{this.logger.debug("Local socket manager socket message",n.getId(),e.data);const{message:t,channel:r}=JSON.parse(e.data);n.handleMessage(r,t).catch((e=>{this.logger.error(e)}))},e.onclose=()=>{this.logger.debug("Local socket manager socket close",n.getId()),n.isOpen()&&n.handleDisconnect().catch((e=>{this.logger.error(e)})),t.removeById(n.getId()).catch((e=>{this.logger.error(e)}))}}))}intercept(){return i(this,void 0,void 0,(function*(){}))}create(e){return new ExpressSocket(this.logger,this.httpRequestHandler,this.authorizationProvider,e)}getAllSockets(){return i(this,void 0,void 0,(function*(){return this.allSockets}))}add(e){return i(this,void 0,void 0,(function*(){this.allSockets.push(e)}))}removeById(e){return i(this,void 0,void 0,(function*(){const t=this.allSockets.findIndex((t=>t.getId()===e));t>=0&&this.allSockets.splice(t,1)}))}getById(e){return i(this,void 0,void 0,(function*(){return this.allSockets.find((t=>t.getId()===e))}))}};p=r([a.Injectable(),o("design:paramtypes",[a.AbstractLogger,c.AbstractHttpRequestHandler,l.AbstractHttpAuthorizationProvider])],p),t.LocalSocketManager=p},function(e,t){e.exports=require("ws")},function(e,t,n){"use strict";var r=this&&this.__decorate||function(e,t,n,r){var o,i=arguments.length,s=i<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(i<3?o(s):i>3?o(t,n,s):o(t,n))||s);return i>3&&s&&Object.defineProperty(t,n,s),s},o=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},i=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function fulfilled(e){try{step(r.next(e))}catch(e){i(e)}}function rejected(e){try{step(r.throw(e))}catch(e){i(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((r=r.apply(e,t||[])).next())}))},s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.AwsSocketManager=void 0;const a=n(0),d=s(n(49)),c=s(n(50)),l=n(1),u=n(4),h=n(25),p=n(3);class ApiGatewaySocket extends h.AbstractServerSocket{constructor(e,t,n,r,o,i,s,a){super(t,n,r),this.socketManager=e,this.socketInfo=Object.assign({},o),this.apiGateway=i,this.redisClient=a,this.socketNamespace=s}physicSend(e){return i(this,void 0,void 0,(function*(){try{this.logger.debug(`Socket ${this.getId()} sending`,e),yield this.apiGateway.postToConnection({ConnectionId:this.getId(),Data:e}).promise(),this.logger.debug(`Socket ${this.getId()} send OK`,e)}catch(e){throw this.logger.debug(`Socket ${this.getId()} post error`,e),410===e.statusCode&&(this.logger.debug(`Stale socket ${this.getId()}`,this.isOpen()),this.isOpen()&&(this.logger.debug(`Disconnecting ${this.getId()}`),yield this.handleDisconnect()),this.logger.debug(`Removing socket ${this.getId()}`),yield this.socketManager.removeById(this.getId()),this.logger.debug(`Socket removed ${this.getId()}`)),e}}))}updateSocketInfo(){return i(this,void 0,void 0,(function*(){return new Promise(((e,t)=>this.redisClient.hset(this.socketNamespace,this.socketInfo.id||"",JSON.stringify(this.socketInfo),(n=>n?t(n):e()))))}))}physicDisconnect(){return i(this,void 0,void 0,(function*(){this.apiGateway.deleteConnection({ConnectionId:this.getId()}).promise().catch((e=>this.logger.error(e))),this.socketManager.removeById(this.getId()).catch((e=>{console.log("socket remove error",e)}))}))}setOpen(e){return i(this,void 0,void 0,(function*(){this.socketInfo.isOpen=e,yield this.updateSocketInfo()}))}addChannels(e){const t=Object.create(null,{addChannels:{get:()=>super.addChannels}});return i(this,void 0,void 0,(function*(){yield t.addChannels.call(this,e),yield this.updateSocketInfo()}))}removeChannels(e){const t=Object.create(null,{removeChannels:{get:()=>super.removeChannels}});return i(this,void 0,void 0,(function*(){yield t.removeChannels.call(this,e),yield this.updateSocketInfo()}))}authorize(e){const t=Object.create(null,{authorize:{get:()=>super.authorize}});return i(this,void 0,void 0,(function*(){yield t.authorize.call(this,e),yield this.updateSocketInfo()}))}serialize(){return JSON.stringify(this.socketInfo)}}let f=class AwsSocketManager extends u.AbstractServerSocketManager{constructor(e,t,n,r,o,i,s){super(s),this.region=e,this.socketDomainUrl=t,this.redisServerUrl=n,this.socketNamespace=r,this.httpRequestHandler=o,this.authorizationProvider=i,this.logger=s,this.redisClient=d.default.createClient({url:n}),this.apiGatewayManagement=new c.default.ApiGatewayManagementApi({region:e,apiVersion:"2018-11-29",endpoint:t})}configure(){this.logger.debug("Aws socket manager configure")}intercept(e){return i(this,void 0,void 0,(function*(){switch(e.method){case a.SocketMethod.CONNECT:{this.logger.debug("Aws socket connect",e.rawPath);let t=this.create({id:e.rawPath,isOpen:!0,authorized:!1,createdAt:Date.now()});return yield this.add(t),{code:200}}case a.SocketMethod.DISCONNECT:{this.logger.debug("Aws socket disconnect",e.rawPath);let t=yield this.getById(e.rawPath);return(null==t?void 0:t.isOpen())&&(yield null==t?void 0:t.handleDisconnect()),yield this.removeById(e.rawPath),{code:200}}case a.SocketMethod.MESSAGE:{this.logger.debug("Aws socket message",e.rawPath,e.body);let t=yield this.getById(e.rawPath);const{channel:n,message:r}=e.body;return yield null==t?void 0:t.handleMessage(n,r),{code:200}}default:return}}))}init(){return i(this,void 0,void 0,(function*(){this.logger.debug("AwsSocketManager: connecting to redis server"),yield new Promise(((e,t)=>{if(this.redisClient.connected&&this.redisClient)return e();this.redisClient.on("ready",e),this.redisClient.on("error",(()=>t(new a.ClaireError(a.Errors.SYSTEM_ERROR,"AwsSocketManager: cannot establish connection to redis server"))))})),this.logger.debug("AwsSocketManager: redis connection established")}))}exit(){this.redisClient.end(!0)}create(e){return new ApiGatewaySocket(this,this.logger,this.httpRequestHandler,this.authorizationProvider,e,this.apiGatewayManagement,this.socketNamespace,this.redisClient)}add(e){return i(this,void 0,void 0,(function*(){return new Promise(((t,n)=>this.redisClient.hset(this.socketNamespace,e.getId(),e.serialize(),(e=>e?n(e):t()))))}))}removeById(e){return i(this,void 0,void 0,(function*(){return new Promise(((t,n)=>this.redisClient.hdel(this.socketNamespace,e,(e=>e?n(e):t()))))}))}getById(e){return i(this,void 0,void 0,(function*(){const t=yield new Promise(((t,n)=>this.redisClient.hget(this.socketNamespace,e,((e,r)=>e?n(e):t(r)))));if(t)return this.logger.debug("Serialized aws socket",t),this.create(JSON.parse(t))}))}getAllSockets(){return i(this,void 0,void 0,(function*(){this.logger.debug("get all sockets called");return yield new Promise(((e,t)=>this.redisClient.hgetall(this.socketNamespace,((n,r)=>n?t(n):e(Object.keys(r).map((e=>{const t=r[e];return this.logger.debug("parsing serialized sockets",t),this.create(JSON.parse(t))})))))))}))}};f=r([a.Initable(),o("design:paramtypes",[String,String,String,String,l.AbstractHttpRequestHandler,p.AbstractHttpAuthorizationProvider,a.AbstractLogger])],f),t.AwsSocketManager=f},function(e,t){e.exports=require("redis")},function(e,t){e.exports=require("aws-sdk")},function(e,t,n){"use strict";var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function fulfilled(e){try{step(r.next(e))}catch(e){i(e)}}function rejected(e){try{step(r.throw(e))}catch(e){i(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((r=r.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.OwnedResourceAccessCondition=void 0;const o=n(0),i=n(8);t.OwnedResourceAccessCondition=e=>{const t=class extends i.AbstractAccessCondition{resolveRequestedConditionValue(t,n){return r(this,void 0,void 0,(function*(){return e(t,n)}))}validate(e){return r(this,void 0,void 0,(function*(){return!!e}))}getConditionMetadata(){return{name:"owned_resource",valueType:o.AccessConditionValueType.BOOLEAN}}};return o.getServiceProvider().register(t,"singleton"),t}}])}));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@clairejs/server",
3
- "version": "2.3.10",
3
+ "version": "2.3.11",
4
4
  "description": "Claire server NodeJs framework written in Typescript.",
5
5
  "types": "dist/index.d.ts",
6
6
  "main": "dist/index.js",