@clairejs/server 3.0.25 → 3.0.26
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 +4 -0
- package/dist/index.js +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
!function webpackUniversalModuleDefinition(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var n=t();for(var i in n)("object"==typeof exports?exports:e)[i]=n[i]}}(global,(function(){return function(e){var t={};function __webpack_require__(n){if(t[n])return t[n].exports;var i=t[n]={i:n,l:!1,exports:{}};return e[n].call(i.exports,i,i.exports,__webpack_require__),i.l=!0,i.exports}return __webpack_require__.m=e,__webpack_require__.c=t,__webpack_require__.d=function(e,t,n){__webpack_require__.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},__webpack_require__.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},__webpack_require__.t=function(e,t){if(1&t&&(e=__webpack_require__(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(__webpack_require__.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var i in e)__webpack_require__.d(n,i,function(t){return e[t]}.bind(null,i));return n},__webpack_require__.n=function(e){var t=e&&e.__esModule?function getDefault(){return e.default}:function getModuleExports(){return e};return __webpack_require__.d(t,"a",t),t},__webpack_require__.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},__webpack_require__.p="",__webpack_require__(__webpack_require__.s=27)}([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.AbstractHttpAuthorizationProvider=void 0;t.AbstractHttpAuthorizationProvider=class AbstractHttpAuthorizationProvider{}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getDirectFields=t.getFieldByName=t.getTransactionFromContext=void 0;const i=n(0),o=n(8);t.getTransactionFromContext=e=>{const t=e[o.INJECTED_TRANSACTION];if(!t)throw i.ErrorBuilder.systemError("Cannot get transaction from current context");return t};t.getFieldByName=(e,t)=>e.fields.find((e=>e.name===t));t.getDirectFields=e=>e.fields.filter((e=>!e.hasMany))},function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractServerSocketManager=void 0;const o=n(24);t.AbstractServerSocketManager=class AbstractServerSocketManager{constructor(e){this.logger=e}getAllAliveSockets(){return i(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 i(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 i=n(0);t.HttpRequest=class HttpRequest{constructor(e,t){this.valueHolder={},this.method=e.method,this.pathName=e.pathName,this.headers=e.headers||{},this.hash=e.hash||"",this.socket=e.socket,this.params=e.params||{},(null==t?void 0:t.paramsValidationDto)&&(this.params=(0,i.validateData)(this.params,null==t?void 0:t.paramsValidationDto)),this.query=e.query||{},(null==t?void 0:t.queriesValidationDto)&&(this.query=(0,i.validateData)(this.jsonParsing(this.query,t.queriesValidationDto),t.queriesValidationDto)),this.body=e.body||{},t&&(t.httpMethod===i.HttpMethod.POST||t.httpMethod===i.HttpMethod.PUT)&&(null==t?void 0:t.bodyValidationDto)&&(this.body=(0,i.validateData)(this.body||{},t.bodyValidationDto))}jsonParsing(e,t){const n=Object.assign({},e);for(const o of t.fields)try{(void 0!==e[o.name]||o.isRequired)&&(n[o.name]=JSON.parse(e[o.name]))}catch(e){throw i.ErrorBuilder.error(i.Errors.VALIDATION_ERROR,`JSON parsing failed for field ${o.name}`)}return n}getAuthInfo(){return this.authInfo}setAuthInfo(e){this.authInfo=e}getHeaders(){return this.headers}getMethod(){return this.method}getHash(){return this.hash}getPathName(){return this.pathName}getValue(e){return this.valueHolder[e]}setValue(e,t){this.valueHolder[e]=t}getParams(){return this.params}getQuery(){return this.query}getBody(){return this.body}getSocket(){if(!this.socket)throw i.ErrorBuilder.systemError("Socket not found for current request");return this.socket}}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ResponseBuilder=t.HttpResponse=void 0;class HttpResponse{constructor(){this.code=200,this.headers={},this.cookies={}}}t.HttpResponse=HttpResponse;class ResponseBuilder{constructor(){this.response=new HttpResponse}status(e){return this.response.code=e,this}header(e,t){return this.response.headers[e]=t,this}cookie(e,t){return this.response.headers[e]=t,this}get(){return this.response}static json(e){const t=new ResponseBuilder;return t.response.value=e,t.response.headers["Content-Type"]="application/json",t}static html(e){const t=new ResponseBuilder;return t.response.value=e,t.response.headers["Content-Type"]="text/html; charset=UTF-8",t}static binary(e){const t=new ResponseBuilder;return t.response.value=e,t.response.headers["Content-Type"]="application/octet-stream",t}static success(){const e=new ResponseBuilder;return e.response.code=200,e.response}static notFound(e){const t=new ResponseBuilder;return t.response.code=404,t.response.value=e,t.response}static accessDenied(e){const t=new ResponseBuilder;return t.response.code=400,t.response.value=e,t.response}}t.ResponseBuilder=ResponseBuilder},function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractHttpController=void 0;const o=n(0),r=n(3);t.AbstractHttpController=class AbstractHttpController{constructor(e){this.databaseAdapter=e}isEndpoint(e){return!!e.httpMethod||void 0!==e.openAccess||!!e.accessConditions}getCurrentDatabaseAdapter(){return i(this,void 0,void 0,(function*(){return this.databaseAdapter}))}getCurrentTransaction(){return i(this,void 0,void 0,(function*(){return(0,r.getTransactionFromContext)(this)}))}getEndpointMetadata(){const e=(0,o.getObjectMetadata)(this.constructor);return e?e.fields.filter((e=>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";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractDatabaseAdapter=void 0;const o=n(0);t.AbstractDatabaseAdapter=class AbstractDatabaseAdapter{constructor(){this.modelMetadata=[],this.models=[],this.modelConnections={}}init(){return i(this,void 0,void 0,(function*(){this.models=((0,o.getGlobalStore)().models||[]).slice(),this.modelMetadata=this.models.map((e=>(0,o.getObjectMetadata)(e))),this.modelConnections=this.modelMetadata.reduce(((e,t)=>Object.assign(e,{[t.id]:{connection:void 0}})),{})}))}exit(){}}},function(e,t){e.exports=require("sequelize")},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.Raw=t.Headers=t.Queries=t.Params=t.Body=t.AccessCondition=t.OpenAccess=t.ApiResponse=t.Get=t.Del=t.Put=t.Post=t.Socket=t.Endpoint=t.Controller=void 0;const i=n(0);t.Controller=e=>t=>{(0,i.getServiceProvider)().register(t,"singleton");(0,i.initObjectMetadata)(t.prototype).permissionGroup=null==e?void 0:e.permissionGroup};t.Endpoint=e=>(t,n)=>{const o=(0,i.initFieldMetadata)(t,n);o.httpMethod=e.method,o.url=e.url};t.Socket=e=>(n,o,r)=>(0,t.Endpoint)({method:i.SocketMethod.MESSAGE,url:e})(n,o);t.Post=e=>(n,o,r)=>(0,t.Endpoint)({method:i.HttpMethod.POST,url:e})(n,o);t.Put=e=>(n,o,r)=>(0,t.Endpoint)({method:i.HttpMethod.PUT,url:e})(n,o);t.Del=e=>(n,o,r)=>(0,t.Endpoint)({method:i.HttpMethod.DEL,url:e})(n,o);t.Get=e=>(n,o,r)=>(0,t.Endpoint)({method:i.HttpMethod.GET,url:e})(n,o);t.ApiResponse=e=>(t,n,o)=>{(0,i.initFieldMetadata)(t,n).responseValidationDto=(0,i.getObjectMetadata)(e)};t.OpenAccess=()=>(e,t)=>{(0,i.initFieldMetadata)(e,t).openAccess=!0};t.AccessCondition=e=>(t,n)=>{(0,i.initFieldMetadata)(t,n).accessConditions=e};const RequestDeco=e=>(t,n,o)=>{const r=(0,i.initFieldMetadata)(t,n),s=Reflect.getMetadata("design:paramtypes",t,n)||[];switch(e){case"body":r.bodyValidationDto=(0,i.getObjectMetadata)(s[o]);break;case"params":r.paramsValidationDto=(0,i.getObjectMetadata)(s[o]);break;case"queries":r.queriesValidationDto=(0,i.getObjectMetadata)(s[o])}r.params||(r.params={}),r.params[o]={source:e,diClass:s[o]}};t.Body=()=>RequestDeco("body");t.Params=()=>RequestDeco("params");t.Queries=()=>RequestDeco("queries");t.Headers=()=>RequestDeco("headers");t.Raw=()=>RequestDeco("raw")},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";var i=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},o=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.FilterModelFieldAccessCondition=void 0;const r=n(0),s=n(9);t.FilterModelFieldAccessCondition=(e,t)=>{let n=class _ extends s.AbstractAccessCondition{resolveConditionValue(e){return o(this,void 0,void 0,(function*(){return t(e)}))}getConditionMetadata(){return{name:"filter_model_field",valueType:r.AccessConditionValueType.CHOICES,valueConstraint:(0,r.getObjectMetadata)(e).fields.map((e=>e.name))}}validate(e,t){return o(this,void 0,void 0,(function*(){return!!e&&e.every((e=>t.includes(e)))}))}};return n=i([(0,r.Register)({mode:"transient"})],n),n}},function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.Transactional=void 0;const o=n(0),r=n(8),s=n(10),a=n(19);t.Transactional=e=>(t,n,d)=>{const c=(0,o.initObjectMetadata)(t);(0,o.initFieldMetadata)(t,n),c.transactional=!0;const l=d.value;d.value=function(...d){return i(this,void 0,void 0,(function*(){const i=this;let c,u,h;try{c=yield i.getCurrentTransaction()}catch(e){}switch(e){case s.TransactionLink.CREATE_NEW:u=!0,h=yield(yield i.getCurrentDatabaseAdapter()).createTransaction();break;case s.TransactionLink.INHERIT_OR_CREATE:u=!c,h=c||(yield(yield i.getCurrentDatabaseAdapter()).createTransaction());break;case s.TransactionLink.INHERIT_OR_THROW:if(u=!1,!c)throw o.ErrorBuilder.systemError(`No transaction to inherit when executing ${t.constructor.name}:${n}`);h=c}const p=Object.assign(Object.create(i),i),f=Object.keys(p).filter((e=>{var t,n;return(null===(t=p[e])||void 0===t?void 0:t.constructor)&&(null===(n=(0,o.getObjectMetadata)(p[e].constructor))||void 0===n?void 0:n.transactional)}));for(const e of f){const t=p[e],n=Object.assign(Object.create(t),t,{[r.INJECTED_TRANSACTION]:h});p[e]=n}try{Object.assign(p,{[r.INJECTED_TRANSACTION]:h});let e=yield l.call(p,...d);return h.getState()===a.TransactionState.EXECUTING&&u&&(yield h.commit()),e}catch(e){throw h.getState()===a.TransactionState.EXECUTING&&u&&(yield h.rollback()),e}}))},Object.defineProperty(d.value,"name",{value:n})}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TransactionState=void 0,function(e){e.EXECUTING="executing",e.COMMITTED="commited",e.ROLLED_BACK="rolled_back"}(t.TransactionState||(t.TransactionState={}))},function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.ModelRepository=void 0;const o=n(0),r=n(3),s=n(21);class ModelRepository{constructor(e){this.model=e,this.modelMetadata=(0,o.getObjectMetadata)(this.model)}getNestedQueries(e){return this.modelMetadata.fields.filter((e=>e.hasMany)).filter((t=>e.fields&&e.fields[t.name])).map((t=>{const n=this.getRequestQueryConditionFromQuery(e.fields[t.name],(0,o.getObjectMetadata)((0,o.getModelById)(t.hasMany.id)));return{modelId:t.hasMany.id,queries:n.length?{_and:n}:{}}}))}getUploadHandler(){return i(this,void 0,void 0,(function*(){if(void 0===this.fileUploadHandler){const e=(0,o.getServiceProvider)().getInjector();this.fileUploadHandler=e.resolveOptional(s.AbstractFileUploadHandler)||null,yield e.initInstances()}return this.fileUploadHandler}))}getRequestQueryConditionFromQuery(e,t){var n;const i=[];for(const s of(0,r.getDirectFields)(t))if(e[s.name])if(s.pk||s.fk||s.isSymbol)i.push({_in:{[s.name]:e[s.name]}});else if(s.enum)i.push({_in:{[s.name]:e[s.name]}});else switch(s.dataType){case o.DataType.STRING:if(s.searchable){const t={[(null==s?void 0:s.searchable.caseSensitive)?(null==s?void 0:s.searchable.accentSensitive)?"_sub":"_usub":(null===(n=null==s?void 0:s.searchable)||void 0===n?void 0:n.accentSensitive)?"_isub":"_iusub"]:{[s.name]:e[s.name]}};i.push(t)}else i.push({_eq:{[s.name]:e[s.name]}});break;case o.DataType.NUMBER:const t=new o.RangeQueryDto;Object.assign(t,e[s.name]),t.min&&(t.minExclusive?i.push({_gt:{[s.name]:t.min}}):i.push({_gte:{[s.name]:t.min}})),t.max&&(t.maxExclusive?i.push({_lt:{[s.name]:t.max}}):i.push({_lte:{[s.name]:t.max}}))}return i}beforeCreating(e,t){return i(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 i(this,void 0,void 0,(function*(){const i=yield this.getUploadHandler();if(!i)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],r=t.mimeProps.uriMapper(n);e&&r&&(yield i.moveFile(e,r),n[t.name]=r,yield o.updateOne(n))}}))}beforeReturning(e){var t,n;return i(this,void 0,void 0,(function*(){const i=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)&&i){if(!o[e.name])continue;o[e.name]=(null===(n=e.mimeProps)||void 0===n?void 0:n.public)?yield i.resolvePublicUrl(o[e.name]):yield i.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 i(this,void 0,void 0,(function*(){const i=(0,r.getDirectFields)(this.modelMetadata),s=this.modelMetadata.fields.filter((e=>!!e.hasMany)),a=t.records;t.records=a.map((e=>i.reduce(((t,n)=>Object.assign(t,void 0!==e[n.name]?{[n.name]:e[n.name]}:{})),{}))),yield this.beforeCreating(e,t.records);let d=t.records.length?yield n.use(this.model).createMany(t.records):[];yield this.uriHandling(d,n),yield this.beforeReturning(d);const c=this.modelMetadata.fields.filter((e=>e.pk||e.serverValue||e.mimeProps)).map((e=>e.name));d=this.project(d,c);for(const i of s){const r=d.map(((e,t)=>(a[t][i.name]||[]).map((t=>Object.assign(Object.assign({},t),{[i.hasMany.column]:e.id}))))).reduce(((e,t)=>e.concat(t)),[]);if(r.length){const s=new ModelRepository((0,o.getModelById)(i.hasMany.id));t.records=r;const a=yield s.createMany({principal:e,body:t,tx:n});for(let e=0;e<a.records.length;e++)r[e]=Object.assign(Object.assign({},r[e]),a.records[e]);for(let e=0;e<d.length;e++){const t=[];for(let n=0;n<r.length;n++)r[n][i.hasMany.column]===d[e].id&&t.push(a.records[e]);d[e]=Object.assign(Object.assign({},d[e]),{[i.name]:t})}}}return{records:d}}))}updateMany({principal:e,queries:t,body:n,tx:s}){return i(this,void 0,void 0,(function*(){let i={};const a=this.modelMetadata.fields.filter((e=>!!e.hasMany)),d=(0,r.getDirectFields)(this.modelMetadata).filter((e=>void 0!==n.update[e.name])),c=d.reduce(((e,t)=>Object.assign(e,{[t.name]:n.update[t.name]})),{});if(t.fields){const e=this.getRequestQueryConditionFromQuery(t.fields,this.modelMetadata);e.length&&(i={_and:[...e]})}const l=this.getNestedQueries(t);let u=[];if(l.length){const e=yield s.use(this.model).getMany(i,{projection:["id"]},l);u=e.records.map((e=>e.id)),u.length&&d.length&&(yield s.use(this.model).updateMany({_in:{id:u}},c,!1))}else if(d.length)u=yield s.use(this.model).updateMany(i,c,!0);else{const e=yield s.use(this.model).getMany(i,{projection:["id"]});u=e.records.map((e=>e.id))}let h=u.map((e=>Object.assign(Object.assign({},c),{id:e})));yield this.uriHandling(h,s),yield this.beforeReturning(h);for(const t of a){const i=n.update[t.name];if(void 0===i||!u.length)continue;if(u.length>1)throw o.ErrorBuilder.systemError(`Multiple records found while updating @HasMany field: ${t.name}`);const r=h.find((e=>e.id===u[0])),a=(0,o.getModelById)(t.hasMany.id),d=s.use(a),c=(yield d.getRecords({_eq:{[t.hasMany.column]:r.id}})).map((e=>e.id)),l=i.map((e=>e.id)).filter((e=>!!e)),p=c.filter((e=>!l.includes(e))),f=i.filter((e=>!e.id)).map((e=>Object.assign(Object.assign({},e),{[t.hasMany.column]:r.id}))),g=i.filter((e=>!!e.id));yield d.deleteMany({_in:{id:p}});const y=new ModelRepository(a),m=yield y.createMany({principal:e,body:{records:f},tx:s}),v=f.map(((e,t)=>Object.assign(Object.assign({},e),m.records[t])));r[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,queryProvider:t}){var n;return i(this,void 0,void 0,(function*(){const i=[];if(e.fields&&i.push(...this.getRequestQueryConditionFromQuery(e.fields,this.modelMetadata)),e.search){const t=this.modelMetadata.fields.filter((e=>e.searchable)).map((t=>({_iusub:{[t.name]:e.search}})));t.length&&i.push({_or:t})}const r=yield t.use(this.model).getMany(i.length?{_and:i}:{},{limit:e.limit,page:e.page,projection:e.projection,order:null===(n=e.order)||void 0===n?void 0:n.map((e=>{const t=Object.keys(e).find((t=>!!e[t]));return[t,e[t]]}))},this.getNestedQueries(e)),s=r.records.map((e=>e.id));for(const n of this.modelMetadata.fields){if(!n.hasMany||e.projection&&!e.projection.includes(n.name))continue;const i=(0,o.getModelById)(n.hasMany.id),a=new ModelRepository(i),d=s.length?yield a.getMany({queries:{fields:{[n.hasMany.column]:s}},queryProvider:t}):{records:[]};for(const e of r.records)e[n.name]=d.records.filter((t=>t[n.hasMany.column]===e.id))}return yield this.beforeReturning(r.records),{total:r.total,records:this.project(r.records,e.projection)}}))}deleteMany({queries:e,tx:t}){return i(this,void 0,void 0,(function*(){let n={};if(e.fields){const t=this.getRequestQueryConditionFromQuery(e.fields,this.modelMetadata);t.length&&(n={_and:[...t]})}const i=this.getNestedQueries(e);let o=[];if(i.length){const e=yield t.use(this.model).getRecords(n,{},i);yield t.use(this.model).deleteMany({_in:{id:e.map((e=>e.id))}}),o=e}else o=yield t.use(this.model).deleteMany(n,e.returning);return{modified:o}}))}}t.ModelRepository=ModelRepository},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractFileUploadHandler=void 0;t.AbstractFileUploadHandler=class AbstractFileUploadHandler{}},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.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";Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractDatabaseMigrator=void 0;t.AbstractDatabaseMigrator=class AbstractDatabaseMigrator{}},function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractServerSocket=void 0;const o=n(0),r=n(5),s=n(15),a=n(24);t.AbstractServerSocket=class AbstractServerSocket{constructor(e,t,n){this.logger=e,this.requestHandler=t,this.authorizationProvider=n,this.socketInfo={}}addChannels(e){return i(this,void 0,void 0,(function*(){this.socketInfo.channels=(this.socketInfo.channels||[]).concat(e)}))}removeChannels(e){return i(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 i(this,void 0,void 0,(function*(){yield this.sendToSocket(o.SocketChannels.MESSAGE_CHANNEL,e)}))}disconnect(e){return i(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 i(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 i(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 i(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;return i(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 r.HttpRequest({method:o.SocketMethod.MESSAGE,pathName:"",headers:{authorization:e.authorizationData}});let i;for(const e of this.requestHandler.getMiddleware())if(i=yield e.intercept(n),i)break;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,i;try{yield this.removeChannels(e.channels),n=!0}catch(e){n=!1,i=e}yield this.sendToSocket(o.SocketChannels.CHANNEL_LEAVE_REQUEST,{success:n,channels:e.channels,error:i})}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 i,d=!0;for(const e of n){const t=new s.HttpEndpoint;t.httpMethod=o.SocketMethod.MESSAGE,t.mount=`/${e}`;const n=((0,o.getGlobalStore)().mountedEndpointInfo||[]).find((e=>e.endpoint.getEndpointId()===t.getEndpointId()));if(!n){i=`Channel not found: ${e}`,d=!1;break}const a=new r.HttpRequest({method:o.SocketMethod.MESSAGE,pathName:`/${e}`});try{yield this.authorizationProvider.authorize(this.socketInfo.authInfo,a,n)}catch(t){i=`Not permitted to join: ${e}`,d=!1;break}}if(yield this.sendToSocket(o.SocketChannels.CHANNEL_JOIN_REQUEST,{success:d,channels:e.channels,error:i}),!d)return;yield this.addChannels(n);for(const t of e.channels){const e=new a.ServerSocket(t,this);yield this.requestHandler.handle({method:o.SocketMethod.MESSAGE,rawPath:t,socket:e})}}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 a.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";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var o=Object.getOwnPropertyDescriptor(t,n);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,o)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),o=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||i(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),t.QueryTypes=void 0,o(n(14),t),o(n(5),t),o(n(28),t),o(n(29),t),o(n(30),t),o(n(6),t),o(n(31),t),o(n(7),t),o(n(35),t),o(n(36),t),o(n(37),t),o(n(1),t),o(n(16),t),o(n(2),t),o(n(9),t),o(n(17),t),o(n(38),t),o(n(39),t),o(n(40),t),o(n(41),t),o(n(46),t),o(n(47),t),o(n(21),t),o(n(48),t),o(n(11),t),o(n(10),t),o(n(49),t),o(n(51),t),o(n(13),t),o(n(18),t),o(n(25),t),o(n(4),t),o(n(53),t),o(n(55),t),o(n(58),t),o(n(59),t),o(n(20),t);var r=n(12);Object.defineProperty(t,"QueryTypes",{enumerable:!0,get:function(){return r.QueryTypes}})},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},function(e,t,n){"use strict";var i=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},o=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},r=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))},s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultHttpRequestHandler=void 0;const a=n(0),d=s(n(32)),c=n(33),l=s(n(34)),u=n(6),h=n(5),p=n(2),f=n(1),g=n(15),y=n(16),m=n(7);let v=class DefaultHttpRequestHandler extends f.AbstractHttpRequestHandler{constructor(e,t){super(),this.logger=e,this.authorizationProvider=t,this.injector=(0,a.getServiceProvider)().getInjector(),this.mountPoint="",this.mountedEndpointInfo=[],this.middleware=this.injector.resolveMultiple(y.AbstractHttpMiddleware)}init(){var e,t,n,i;return r(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=(0,a.getObjectMetadata)(e.constructor),n=e.getEndpointMetadata();for(const i of n){const n=new g.HttpEndpoint;n.mount=this.resolverMountPoint(t,[this.mountPoint||"/",i.url]),n.httpMethod=i.httpMethod,n.handler=t=>r(this,void 0,void 0,(function*(){if(n.httpMethod!==a.SocketMethod.MESSAGE){const e=yield this.authorizationProvider.resolvePrincipal(t);t.setAuthInfo(e),i.openAccess||(yield this.authorizationProvider.authorize(e,t,{endpoint:n,endpointMetadata:i}))}const o=Object.values(i.params||{}).map((e=>{switch(e.source){case"body":return t.getBody();case"params":return t.getParams();case"queries":return t.getQuery();case"headers":return t.getHeaders();case"raw":return t}}));return yield e[i.name](...o)})),n.controller=e,n.handlerFunctionName=i.name,o.push({endpointMetadata:i,endpoint:n})}}this.mountedEndpointInfo=[];for(const r of o){const o=this.mountedEndpointInfo.find((e=>e.endpoint.mount===r.endpoint.mount&&e.endpoint.httpMethod===r.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 ${r.endpoint.getEndpointId()} of ${null===(n=r.endpoint.controller)||void 0===n?void 0:n.constructor.name}:${r.endpoint.handlerFunctionName}`):(null===(i=this.logger)||void 0===i||i.debug(`Mouting: ${r.endpoint.getEndpointId()}`),this.mountedEndpointInfo.push(r))}(0,a.getGlobalStore)().mountedEndpointInfo=this.mountedEndpointInfo}))}exit(){}handle(e){return r(this,void 0,void 0,(function*(){const t=e.method,n=(0,d.default)({url:e.rawPath});let i={};const o=this.mountedEndpointInfo.find((e=>{const o=e.endpointMetadata.httpMethod===t&&(0,c.match)(e.endpointMetadata.url,{decode:decodeURIComponent})(n.pathname);return!!o&&(i=o,!0)}));if(!o)throw this.logger.debug(e),a.ErrorBuilder.error(a.Errors.NOT_FOUND,"Handler not found");const r=new h.HttpRequest({method:t,headers:e.headers,pathName:n.pathname||"",hash:n.hash||"",query:l.default.parse(n.search||""),params:i.params,body:e.body,socket:e.socket},o.endpointMetadata);let s;try{if(t!==a.SocketMethod.MESSAGE)for(const e of this.getMiddleware())if(s=yield e.intercept(r),s)break;s||(s=yield o.endpoint.handler&&o.endpoint.handler(r))}catch(e){s=u.ResponseBuilder.json({name:e.name,message:e.message}).status(400).get()}if(!(s&&s instanceof u.HttpResponse))throw a.ErrorBuilder.systemError(`Invalid response value returned ${o.endpoint.httpMethod}:${o.endpoint.mount}, required instance of ${u.HttpResponse.name}, found ${s?s.constructor.name:s}`);return{body:null==s?void 0:s.value,code:(null==s?void 0:s.code)||400,cookies:(null==s?void 0:s.cookies)||{},headers:(null==s?void 0:s.headers)||{}}}))}getMiddleware(){return this.middleware}};v=i([(0,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 i=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},o=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},r=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}},s=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.CrudHttpController=void 0;const a=n(0),d=n(17),c=n(5),l=n(18),u=n(10),h=n(14),p=n(7),f=n(20),g=n(2),y=n(6);class CrudHttpController extends p.AbstractHttpController{constructor(e,t){super(t),this.model=e,this.databaseAdapter=t;const n=(0,a.getObjectMetadata)(e);this.model=(0,a.getModelById)(n.id),this.modelMetadata=(0,a.getObjectMetadata)(this.model)}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=a.DataType.OBJECT,(0,a.setObjectMetadata)(FieldsDto,t),n.objectTypeConstructor=FieldsDto,n}static projectionFieldDto(e){const t={name:"projection"};return t.dataType=a.DataType.ARRAY,t.vectorProps={superSet:e.fields.map((e=>e.name)),allowDuplicated:!1,minLength:1,elementDataType:a.DataType.STRING},t}static getBodyDtoRecordClass(e,t,n){class InstanceDto{}const i={fields:[],strict:!0},o=e.fields.filter((e=>!e.serverValue||e.serverValue&&e.pk&&!t&&!n)),r=e.fields.filter((e=>!!e.hasMany));return i.fields.push(...o.map((e=>Object.assign(Object.assign({},e),{isRequired:null===t?e.isRequired:t}))),...r.map((e=>({description:e.description,name:e.name,dataType:a.DataType.ARRAY,vectorProps:{elementDataType:a.DataType.OBJECT,minLength:0},objectTypeConstructor:CrudHttpController.getBodyDtoRecordClass((0,a.getObjectMetadata)((0,a.getModelById)(e.hasMany.id)),t,!1)})))),(0,a.setObjectMetadata)(InstanceDto,i),InstanceDto}static getRequestQueryFieldFromModel(e){return e.fields.map((e=>{const t={};if(t.name=e.name,t.isRequired=!1,e.pk||e.fk||e.isSymbol)t.dataType=a.DataType.ARRAY,t.vectorProps={elementDataType:e.dataType,allowDuplicated:!1,allowNull:e.allowNull,minLength:1};else if(e.enum)t.dataType=a.DataType.ARRAY,t.vectorProps={superSet:e.enum,allowDuplicated:!1,minLength:1,elementDataType:e.dataType,allowNull:e.allowNull};else switch(e.dataType){case a.DataType.STRING:t.dataType=a.DataType.STRING;break;case a.DataType.NUMBER:t.dataType=a.DataType.OBJECT,t.objectTypeConstructor=a.RangeQueryDto}return t}))}getAuthProvider(){return s(this,void 0,void 0,(function*(){if(void 0===this.authProvider){const e=(0,a.getServiceProvider)().getInjector();this.authProvider=e.resolveOptional(g.AbstractHttpAuthorizationProvider)||null,yield e.initInstances()}return this.authProvider}))}createManyEndpoinMetadata(){const e={};return e.httpMethod=a.HttpMethod.POST,e.url=this.getMountedUrl(),e.name=CrudHttpController.prototype.createMany.name,e.displayName="createMany"+this.model.name,e.bodyValidationDto=CrudHttpController.getCreateManyBodyValidator(this.modelMetadata),e.responseValidationDto=CrudHttpController.getCreateManyResponseValidator(this.modelMetadata),e}getManyEndpointMetadata(){const e={};return e.httpMethod=a.HttpMethod.GET,e.url=this.getMountedUrl(),e.name=CrudHttpController.prototype.getMany.name,e.displayName="getAll"+this.model.name,e.queriesValidationDto=CrudHttpController.getGetManyQueryValidator(this.modelMetadata),e.responseValidationDto=CrudHttpController.getGetManyResponseValidator(this.modelMetadata),e.accessConditions=[(0,d.FilterModelFieldAccessCondition)(this.model,(e=>e.getQuery().projection))],e}updateManyEndpoinMetadata(){const e={};return e.httpMethod=a.HttpMethod.PUT,e.url=this.getMountedUrl(),e.name=CrudHttpController.prototype.updateMany.name,e.displayName="update"+this.model.name,e.queriesValidationDto=CrudHttpController.getUpdateManyQueryValidator(this.modelMetadata),e.bodyValidationDto=CrudHttpController.getUpdateManyBodyValidator(this.modelMetadata),e.responseValidationDto=CrudHttpController.getUpdateManyResponseValidator(this.modelMetadata),e.accessConditions=[(0,d.FilterModelFieldAccessCondition)(this.model,(e=>Object.keys(e.getBody().update)))],e}deleteManyEndpoinMetadata(){const e={};return e.httpMethod=a.HttpMethod.DEL,e.url=this.getMountedUrl(),e.name=CrudHttpController.prototype.deleteMany.name,e.displayName="delete"+this.model.name,e.queriesValidationDto=CrudHttpController.getUpdateManyQueryValidator(this.modelMetadata),e}static getCreateManyBodyValidator(e){const t={fields:[],strict:!0},n={name:"records"};return n.dataType=a.DataType.ARRAY,n.isRequired=!0,n.vectorProps={elementDataType:a.DataType.OBJECT,minLength:0},n.objectTypeConstructor=CrudHttpController.getBodyDtoRecordClass(e,null,!0),t.fields.push(n),t}static getCreateManyResponseValidator(e){const t={fields:[]},n={name:"records"};return n.dataType=a.DataType.OBJECT,n.isRequired=!0,n.vectorProps={elementDataType:a.DataType.OBJECT,minLength:0},n.objectTypeConstructor=CrudHttpController.getBodyDtoRecordClass(e,null,!0),t.fields.push(n),t}static getGetManyResponseValidator(e){const t={fields:[]},n={name:"total"};n.dataType=a.DataType.NUMBER,n.isRequired=!0,t.fields.push(n);const i={name:"records"};return i.dataType=a.DataType.ARRAY,i.isRequired=!0,i.vectorProps={elementDataType:a.DataType.OBJECT,minLength:0},i.objectTypeConstructor=CrudHttpController.getBodyDtoRecordClass(e,!1,!0),t.fields.push(i),t}static getGetManyQueryValidator(e){const t={fields:[CrudHttpController.queryFieldDto(e)]},n={name:"search"};n.dataType=a.DataType.STRING,t.fields.push(n),t.fields.push(CrudHttpController.projectionFieldDto(e));const i={name:"order"};i.dataType=a.DataType.ARRAY,i.vectorProps={elementDataType:a.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=a.DataType.OBJECT,t.enum=["asc","desc"],t}))),(0,a.setObjectMetadata)(SortElementDto,o),i.objectTypeConstructor=SortElementDto,t.fields.push(i);const r={name:"limit"};r.dataType=a.DataType.NUMBER,r.rangeProps={min:1},t.fields.push(r);const s={name:"page"};return s.dataType=a.DataType.NUMBER,s.rangeProps={min:1},t.fields.push(s),t}static getUpdateManyQueryValidator(e){const t={name:"returning"};return t.dataType=a.DataType.BOOLEAN,t.isRequired=!1,{fields:[t,CrudHttpController.queryFieldDto(e)]}}static getUpdateManyBodyValidator(e){const t={fields:[],strict:!0},n={name:"update"};return n.dataType=a.DataType.OBJECT,n.objectTypeConstructor=CrudHttpController.getBodyDtoRecordClass(e,!1,!0),t.fields.push(n),t}static getUpdateManyResponseValidator(e){const t={fields:[],strict:!0},n={name:"modified"};return n.dataType=a.DataType.ARRAY,n.vectorProps={minLength:0,elementDataType:a.DataType.OBJECT},n.objectTypeConstructor=CrudHttpController.getBodyDtoRecordClass(e,!1,!0),t.fields.push(n),t}static createManyBodyValidator(e){class Validator{}return(0,a.setObjectMetadata)(Validator,CrudHttpController.getCreateManyBodyValidator((0,a.getObjectMetadata)(e))),Validator}static getManyQueryValidator(e){class Validator{}return(0,a.setObjectMetadata)(Validator,CrudHttpController.getGetManyQueryValidator((0,a.getObjectMetadata)(e))),Validator}static updateManyQueryValidator(e){class Validator{}return(0,a.setObjectMetadata)(Validator,CrudHttpController.getUpdateManyQueryValidator((0,a.getObjectMetadata)(e))),Validator}static updateManyBodyValidator(e){class Validator{}return(0,a.setObjectMetadata)(Validator,CrudHttpController.getUpdateManyBodyValidator((0,a.getObjectMetadata)(e))),Validator}getEndpointMetadata(){var e,t,n,i;const o=super.getEndpointMetadata(),r=[];(null===(e=this.modelMetadata.ignoreCrud)||void 0===e?void 0:e.includes(a.HttpMethod.GET))?o.splice(o.findIndex((e=>e.name===CrudHttpController.prototype.getMany.name)),1):r.push(this.getManyEndpointMetadata()),(null===(t=this.modelMetadata.ignoreCrud)||void 0===t?void 0:t.includes(a.HttpMethod.POST))?o.splice(o.findIndex((e=>e.name===CrudHttpController.prototype.createMany.name)),1):r.push(this.createManyEndpoinMetadata()),(null===(n=this.modelMetadata.ignoreCrud)||void 0===n?void 0:n.includes(a.HttpMethod.PUT))?o.splice(o.findIndex((e=>e.name===CrudHttpController.prototype.updateMany.name)),1):r.push(this.updateManyEndpoinMetadata()),(null===(i=this.modelMetadata.ignoreCrud)||void 0===i?void 0:i.includes(a.HttpMethod.DEL))?o.splice(o.findIndex((e=>e.name===CrudHttpController.prototype.deleteMany.name)),1):r.push(this.deleteManyEndpoinMetadata());for(const e of r){const t=o.findIndex((t=>t.httpMethod===e.httpMethod&&t.url===e.url||t.name===e.name));t>=0?o[t]=Object.assign(Object.assign(Object.assign({},e),o[t]),{accessConditions:[...e.accessConditions||[],...o[t].accessConditions||[]]}):o.push(e)}return o}createMany(e){return s(this,void 0,void 0,(function*(){const t=yield this.getCurrentTransaction(),n=new f.ModelRepository(this.model),i=yield this.getAuthProvider(),o=i&&(yield i.resolvePrincipal(e)),r=yield n.createMany({principal:o,body:e.getBody(),tx:t});return y.ResponseBuilder.json(r).get()}))}getMany(e){return s(this,void 0,void 0,(function*(){const t=new f.ModelRepository(this.model),n=yield t.getMany({queries:e.getQuery(),queryProvider:this.databaseAdapter});return y.ResponseBuilder.json(n).get()}))}updateMany(e){return s(this,void 0,void 0,(function*(){const t=yield this.getCurrentTransaction(),n=yield this.getAuthProvider(),i=n&&(yield n.resolvePrincipal(e)),o=new f.ModelRepository(this.model),r=yield o.updateMany({principal:i,queries:e.getQuery(),body:e.getBody(),tx:t});return y.ResponseBuilder.json(r).get()}))}deleteMany(e){return s(this,void 0,void 0,(function*(){const t=yield this.getCurrentTransaction(),n=new f.ModelRepository(this.model),i=yield n.deleteMany({queries:e.getQuery(),tx:t});return y.ResponseBuilder.json({modified:i.modified.map((e=>e.id)).map((e=>({id:e})))}).get()}))}}i([(0,l.Transactional)(u.TransactionLink.INHERIT_OR_CREATE),(0,h.AccessCondition)([]),r(0,(0,h.Raw)()),o("design:type",Function),o("design:paramtypes",[c.HttpRequest]),o("design:returntype",Promise)],CrudHttpController.prototype,"createMany",null),i([(0,h.AccessCondition)([]),r(0,(0,h.Raw)()),o("design:type",Function),o("design:paramtypes",[c.HttpRequest]),o("design:returntype",Promise)],CrudHttpController.prototype,"getMany",null),i([(0,l.Transactional)(u.TransactionLink.INHERIT_OR_CREATE),(0,h.AccessCondition)([]),r(0,(0,h.Raw)()),o("design:type",Function),o("design:paramtypes",[c.HttpRequest]),o("design:returntype",Promise)],CrudHttpController.prototype,"updateMany",null),i([(0,l.Transactional)(u.TransactionLink.INHERIT_OR_CREATE),(0,h.AccessCondition)([]),r(0,(0,h.Raw)()),o("design:type",Function),o("design:paramtypes",[c.HttpRequest]),o("design:returntype",Promise)],CrudHttpController.prototype,"deleteMany",null),t.CrudHttpController=CrudHttpController},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},function(e,t,n){"use strict";var i=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},o=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},r=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.OwnedResourceAccessCondition=void 0;const s=n(0),a=n(11),d=n(9);t.OwnedResourceAccessCondition=e=>{let t=class _ extends d.AbstractAccessCondition{constructor(e){super(),this.db=e}resolveConditionValue(t){return r(this,void 0,void 0,(function*(){return e(t,this.db)}))}validate(e){return r(this,void 0,void 0,(function*(){return!!e}))}getConditionMetadata(){return{name:"owned_resource",valueType:s.AccessConditionValueType.BOOLEAN}}};return t=i([(0,s.Register)({mode:"transient"}),o("design:paramtypes",[a.AbstractDatabaseAdapter])],t),t}},function(e,t,n){"use strict";var i,o=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},r=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},s=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.FileLogMedium=void 0;const d=a(n(22)),c=a(n(23)),l=n(0);let u=i=class FileLogMedium{constructor(e){const t=e.separated?i.levels.map((t=>c.default.join(e.destination,t+".log"))):[e.destination];this.destination=t.map((e=>(d.default.existsSync(c.default.dirname(e))||d.default.mkdirSync(c.default.dirname(e),{recursive:!0}),d.default.openSync(e,"a")))),this.separated=!!e.separated}init(){return s(this,void 0,void 0,(function*(){}))}exit(){this.destination.forEach((e=>d.default.closeSync(e)))}write(e,t){const n=this.separated?this.destination[i.levels.indexOf(e)]:0;d.default.appendFileSync(n,t)}};u.levels=Object.values(l.LogLevel),u=i=o([(0,l.Initable)(),r("design:paramtypes",[Object])],u),t.FileLogMedium=u},function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.ClaireServer=void 0;const o=n(0),r=n(8);class ClaireServer extends o.ClaireApp{constructor(){super(),this.injector=(0,o.getServiceProvider)().getInjector(),this.booted=!1,this.logger=this.injector.resolve(o.AbstractLogger)}init(){return i(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(r.ExitCode.SIGTERM_INTERUPTION)))),process.on("SIGINT",(()=>(this.logger.warn("SIGINT interrupt signal"),this.stop(r.ExitCode.SIGTERM_INTERUPTION)))),process.on("uncaughtException",(e=>(this.logger.error("uncaughtException",e.name,e.stack),this.stop(r.ExitCode.UNCAUGHT_EXCEPTION)))),process.on("unhandledRejection",(e=>(this.logger.error("unhandledRejection",e.name,e.stack),this.stop(r.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 i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ExpressWrapper=void 0;const r=n(0),s=o(n(42)),a=o(n(43)),d=o(n(44)),c=o(n(45)),l=n(4),u=n(1);t.ExpressWrapper=class ExpressWrapper{constructor(e,t){this.injector=(0,r.getServiceProvider)().getInjector(),this.server=e,this.config=t,this.logger=this.injector.resolve(r.AbstractLogger),this.socketManager=this.injector.resolveOptional(l.AbstractServerSocketManager),this.httpRequestHandler=this.injector.resolve(u.AbstractHttpRequestHandler)}close(){var e;null===(e=this.httpServer)||void 0===e||e.close()}listen(e){var t,n;return i(this,void 0,void 0,(function*(){yield this.server.init(),yield this.injector.initInstances();const o=(0,s.default)(),r=a.default.createServer(o);return null===(t=this.socketManager)||void 0===t||t.configure(r),o.use((0,d.default)()),o.use(s.default.raw({limit:1024*((null===(n=this.config)||void 0===n?void 0:n.maxBodySizeKB)||4096)})),o.use((0,c.default)()),o.use(((e,t,n)=>{e.files&&(e.body||(e.body={}),Object.keys(e.files).forEach((t=>{e.body[t]=e.files[t]}))),n()})),o.use(s.default.urlencoded({extended:!1})),o.use(s.default.json()),o.all("*",((e,t)=>{(()=>i(this,void 0,void 0,(function*(){var n;const i=!!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(i);return o||(o=yield this.httpRequestHandler.handle(i)),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({name:e.name,message:e.message})}))})),new Promise(((t,n)=>{this.httpServer=r.listen(e,t).on("error",n)}))}))}}},function(e,t){e.exports=require("express")},function(e,t){e.exports=require("http")},function(e,t){e.exports=require("cors")},function(e,t){e.exports=require("express-fileupload")},function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.LambdaWrapper=void 0;const o=n(0),r=n(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=(0,o.getServiceProvider)().getInjector(),this.socketManager=this.injector.resolveOptional(s.AbstractServerSocketManager),this.httpRequestHandler=this.injector.resolve(r.AbstractHttpRequestHandler)}handler(e){var t,n;return i(this,void 0,void 0,(function*(){yield this.server.init(),yield this.injector.initInstances(),null===(t=this.socketManager)||void 0===t||t.configure();const i=this.requestMapper(e);if(!i)return toApiGatewayFormat(400,"Cannot resolve event");if(i.method===o.HttpMethod.OPTIONS)return toApiGatewayFormat(200);try{let e=yield null===(n=this.socketManager)||void 0===n?void 0:n.intercept(i);return e||(e=yield this.httpRequestHandler.handle(i)),toApiGatewayFormat(e.code,e.body)}catch(e){return toApiGatewayFormat(400,{name:e.name,message:e.message})}}))}}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractService=void 0;const o=n(3);t.AbstractService=class AbstractService{constructor(e){this.databaseAdapter=e}getCurrentDatabaseAdapter(){return i(this,void 0,void 0,(function*(){return this.databaseAdapter}))}getCurrentTransaction(){return i(this,void 0,void 0,(function*(){return(0,o.getTransactionFromContext)(this)}))}}},function(e,t,n){"use strict";var i=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},o=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},r=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSqlDatabaseAdapter=void 0;const s=n(0),a=n(12),d=n(19),c=n(11),l=n(50),u=n(13),h=n(3),getModelId=e=>{const t=(0,s.getObjectMetadata)(e);if(!t)throw s.ErrorBuilder.systemError(`Metadata for ${e.name} not found, check @Model decorator`);return t.id},p=["_and","_or"],convertOp=e=>[a.Op.and,a.Op.or,a.Op.eq,a.Op.ne,a.Op.gt,a.Op.lt,a.Op.gte,a.Op.lte,a.Op.regexp,a.Op.like,a.Op.in][["_and","_or","_eq","_neq","_gt","_lt","_gte","_lte","_regex","_sub","_in"].indexOf(e)],safetifyColumn=(e,t)=>{const n=t===u.SqlProvider.MYSQL?"`":'"';return e.split(".").map((e=>`${n}${e}${n}`)).join(".")},getAggregatorColumn=(e,t)=>{const n=safetifyColumn(e.field,t);switch(e.fn){case"count":return`${!0===e.args?`COUNT(DISTINCT(${n}))`:`COUNT(${n})`}${t===u.SqlProvider.POSTGRES?"::int":""}`;case"sum":return`SUM(${n})`;case"avg":return`AVG(${n})`;case"min":return`MIN(${n})`;case"max":return`MAX(${n})`;case"join":return t===u.SqlProvider.POSTGRES?`string_agg(${n}, '${e.args}')`:`GROUP_CONCAT(${n} SEPARATOR '${e.args}')`;case"is":return n;default:throw s.ErrorBuilder.systemError(`Not supported agg function: ${e.fn}`)}};class Joiner{constructor(e){this.adapter=e,this.joinInfo=[],this.columnId=0}join(e,t,n,i){return this.joinInfo.push({rightModel:e,leftField:t,rightField:n,joinMode:i||"inner"}),this}where(e){return this.queryCondition=e,this}groupBy(e){return this.groupByFields=e,this}having(e){return this.havingCondition=e,this}getExecuteCondition(){const e=[],t=this.convertHavingCondition(this.havingCondition||{},e);return{conditions:{where:this.adapter.getQueryObjectFromQueryConditions(this.queryCondition,!0),transaction:this.adapter.transaction,include:this.joinInfo.map((e=>{const t=(0,s.getTableName)(e.rightModel);return{attributes:[],model:this.adapter.modelConnections[t].connection,duplicating:!1,required:"inner"===e.joinMode,on:{[`$${e.leftField}$`]:{[convertOp("_eq")]:a.Sequelize.col(e.rightField)}}}})),group:this.groupByFields,attributes:this.adapter.sqlProvider===u.SqlProvider.POSTGRES?[]:e.map((e=>[a.Sequelize.literal(e.sequelizeColumn),e.columnId])),having:t,raw:!0},collector:e}}countWithCondition(e){var t;return r(this,void 0,void 0,(function*(){e.offset=0,e.limit=this.adapter.sqlProvider===u.SqlProvider.POSTGRES?1:0,e.attributes=[...this.adapter.sqlProvider===u.SqlProvider.MYSQL&&e.attributes||[],[this.adapter.sqlProvider===u.SqlProvider.POSTGRES?a.Sequelize.literal("(COUNT(*) OVER ())::int"):a.Sequelize.literal("COUNT(*)"),"count"]];const n=this.adapter.sqlProvider===u.SqlProvider.POSTGRES?yield this.adapter.getCurrentConnection().findAll(e):yield this.adapter.getCurrentConnection().count(e);return(null===(t=n[0])||void 0===t?void 0:t.count)||0}))}count(){return r(this,void 0,void 0,(function*(){const{conditions:e}=this.getExecuteCondition();return this.countWithCondition(e)}))}rows(e,t){return r(this,void 0,void 0,(function*(){const{conditions:n,collector:i}=this.getExecuteCondition();n.attributes=[...n.attributes||[],...Object.keys(e).map((t=>[a.Sequelize.literal(getAggregatorColumn(e[t],this.adapter.sqlProvider)),t]))],n.limit=null==t?void 0:t.limit,n.offset=(null==t?void 0:t.limit)&&t.limit*((t.page||1)-1);const o=yield this.adapter.getCurrentConnection().findAll(n);return{total:yield this.countWithCondition(Object.assign(Object.assign({},n),{attributes:i.map((e=>[a.Sequelize.literal(e.sequelizeColumn),e.columnId]))})),records:o}}))}convertHavingOperation(e,t){const n=getAggregatorColumn(t[0],this.adapter.sqlProvider);return{columnId:"col__"+this.columnId++,sequelizeColumn:n,sequelizeOps:{[convertOp(e)]:t[1]}}}convertHavingCondition(e,t){if(!e)return{};const n=Object.keys(e);if(!n.length)return{};const i=n.map((n=>{if(p.includes(n))return{[convertOp(n)]:e[n].map((e=>this.convertHavingCondition(e,t)))};{const i=this.convertHavingOperation(n,e[n]);return t.push(i),this.adapter.sqlProvider===u.SqlProvider.POSTGRES?a.Sequelize.where(a.Sequelize.literal(i.sequelizeColumn),i.sequelizeOps):{[i.columnId]:i.sequelizeOps}}}));return i.length>1?{[convertOp("_and")]:i}:i[0]}}class ModelAdapter extends l.AbstractQuery{constructor(e){super(e.model),this.dbConnection=e.dbConnection,this.modelConnections=e.modelConnections,this.transaction=e.transaction,this.sqlProvider=e.sqlProvider,this.logger=null==e?void 0:e.logger}getCurrentConnection(){const e=(0,s.getObjectMetadata)(this.model).id;return this.modelConnections[e].connection}resolveNestedIncludes(e){return e&&e.map((e=>({model:this.modelConnections[e.modelId].connection,where:this.getQueryObjectFromQueryConditions(e.queries)})))}join(e,t,n,i){const o=new Joiner(this);return o.join(e,t,n,i),o}count(e,t,n){return r(this,void 0,void 0,(function*(){const i={where:this.getQueryObjectFromQueryConditions(e),transaction:this.transaction,include:this.resolveNestedIncludes(n)};return(null==t?void 0:t.distinct)&&Object.assign(i,{distinct:!0,col:t.distinct}),yield this.getCurrentConnection().count(i)}))}getById(e,t){return this.getOne({_eq:{id:e}},t)}getByIds(e,t){return this.getRecords({_in:{id:e}},t)}getOne(e,t){return r(this,void 0,void 0,(function*(){const n=yield this.getMany(e,{limit:1});return n.records.length?this.convertToLogicObjects(n.records,null==t?void 0:t.projection)[0]:void 0}))}getRecords(e,t,n){return r(this,void 0,void 0,(function*(){return(yield this.getMany(e,t,n)).records}))}getMany(e,t,n){return r(this,void 0,void 0,(function*(){let i={where:this.getQueryObjectFromQueryConditions(e),transaction:this.transaction,include:this.resolveNestedIncludes(n)};if((null==t?void 0:t.order)&&Object.assign(i,{order:t.order}),(null==t?void 0:t.projection)&&Object.assign(i,{attributes:t.projection}),(null==t?void 0:t.limit)&&(i=Object.assign(i,{limit:t.limit}),t.page&&(i=Object.assign(i,{offset:t.limit*(t.page-1)}))),1!==(null==t?void 0:t.limit)||t.page){if(null==t?void 0:t.limit){const{count:e,rows:n}=yield this.getCurrentConnection().findAndCountAll(i);return{total:e,records:this.convertToLogicObjects(n,null==t?void 0:t.projection)}}{const e=yield this.getCurrentConnection().findAll(i);return{total:0,records:this.convertToLogicObjects(e,null==t?void 0:t.projection)}}}{const e=yield this.getCurrentConnection().findOne(i);return{total:0,records:e?this.convertToLogicObjects([e],t.projection):[]}}}))}createOne(e){return r(this,void 0,void 0,(function*(){return(yield this.createMany([e]))[0]}))}createMany(e){return r(this,void 0,void 0,(function*(){let t=yield this.getCurrentConnection().bulkCreate(this.convertToDataObjects(e),{transaction:this.transaction});return this.convertToLogicObjects(t)}))}updateOne(e){return r(this,void 0,void 0,(function*(){return yield this.getCurrentConnection().update(this.convertToDataObjects([e],!0)[0],{where:this.getQueryObjectFromQueryConditions({_eq:{id:e.id}}),transaction:this.transaction}),e}))}updateMany(e,t,n){return r(this,void 0,void 0,(function*(){if(n){const n=yield this.getRecords(e,{projection:["id"]});if(!n.length)return[];const i=n.map((e=>e.id));return yield this.getCurrentConnection().update(this.convertToDataObjects([t],!0)[0],{where:this.getQueryObjectFromQueryConditions({_in:{id:i}}),transaction:this.transaction}),i}return yield this.getCurrentConnection().update(this.convertToDataObjects([t],!0)[0],{where:this.getQueryObjectFromQueryConditions(e),transaction:this.transaction}),[]}))}deleteOne(e){return r(this,void 0,void 0,(function*(){return yield this.deleteMany({_eq:{id:e.id}}),e}))}deleteMany(e,t){return r(this,void 0,void 0,(function*(){if(t){const t=yield this.getMany(e);if(!t.records.length)return[];const n=t.records.map((e=>e.id));return yield this.getCurrentConnection().destroy({where:this.getQueryObjectFromQueryConditions({_in:{id:n}}),transaction:this.transaction}),t.records}return yield this.getCurrentConnection().destroy({where:this.getQueryObjectFromQueryConditions(e),transaction:this.transaction}),[]}))}rawQuery(...e){return r(this,void 0,void 0,(function*(){const t=e[0],n=e[1]||{};if("string"!=typeof t)throw s.ErrorBuilder.error(s.Errors.QUERY_ERROR,"First argument of raw sql expected to be string");return this.dbConnection.query(t,Object.assign({transaction:this.transaction,raw:!0},n))}))}mapToSequelizeOperator(e,t,n,i,o){const r=o?a.Sequelize.literal(safetifyColumn(n,e)):a.Sequelize.col(n);switch(t){case"_sub":switch(this.sqlProvider){case u.SqlProvider.MYSQL:return a.Sequelize.where(r,{[a.Op.like]:a.Sequelize.literal(`${this.dbConnection.escape(`%${i}%`)} COLLATE utf8mb4_0900_as_cs`)});default:return a.Sequelize.where(r,{[a.Op.like]:`%${i}%`})}case"_isub":switch(this.sqlProvider){case u.SqlProvider.POSTGRES:return a.Sequelize.where(r,{[a.Op.iLike]:`%${i}%`});case u.SqlProvider.MYSQL:return a.Sequelize.where(r,{[a.Op.like]:a.Sequelize.literal(`${this.dbConnection.escape(`%${i}%`)} COLLATE utf8mb4_0900_as_ci`)})}case"_usub":switch(this.sqlProvider){case u.SqlProvider.POSTGRES:return a.Sequelize.where(a.Sequelize.fn("unaccent",r),{[a.Op.like]:a.Sequelize.literal(`unaccent(${this.dbConnection.escape(`%${i}%`)})`)});case u.SqlProvider.MYSQL:return a.Sequelize.where(a.Sequelize.fn("unaccent",r),{[a.Op.like]:a.Sequelize.literal(`unaccent(${this.dbConnection.escape(`%${i}%`)}) COLLATE utf8mb4_0900_as_cs`)})}case"_iusub":switch(this.sqlProvider){case u.SqlProvider.POSTGRES:return a.Sequelize.where(a.Sequelize.fn("unaccent",r),{[a.Op.iLike]:a.Sequelize.literal(`unaccent(${this.dbConnection.escape(`%${i}%`)})`)});case u.SqlProvider.MYSQL:return a.Sequelize.where(r,{[a.Op.like]:a.Sequelize.literal(`${this.dbConnection.escape(`%${i}%`)} COLLATE utf8mb4_0900_ai_ci`)})}case"_in":const e=i.filter((e=>null!==e));return e.length<i.length?a.Sequelize.or(a.Sequelize.where(r,{[a.Op.eq]:null}),...e.length?[a.Sequelize.where(r,{[a.Op.in]:e})]:[]):a.Sequelize.where(r,{[a.Op.in]:i});default:return a.Sequelize.where(r,{[convertOp(t)]:i})}}getQueryObjectFromQueryConditions(e,t){if(!e)return{};const n=Object.keys(e);if(!n.length)return{};const i=n.map((n=>p.includes(n)?{[convertOp(n)]:e[n].map((e=>this.getQueryObjectFromQueryConditions(e)))}:{[convertOp("_and")]:Object.keys(e[n]).map((i=>this.mapToSequelizeOperator(this.sqlProvider,n,i,e[n][i],t)))}));return i.length>1?{[convertOp("_and")]:i}:i[0]}}class TransactionAdapter{constructor(e){this.modelAdapters={},this.transaction=e.transaction,this.dbConnection=e.dbConnection,this.logger=e.logger,this.modelConnections=e.modelConnections,this.sqlProvider=e.sqlProvider,this.transactionState=d.TransactionState.EXECUTING}use(e){const t=getModelId(e);let n=this.modelAdapters[t];return n||(this.modelAdapters,n=new ModelAdapter({model:e,dbConnection:this.dbConnection,modelConnections:this.modelConnections,logger:this.logger,transaction:this.transaction,sqlProvider:this.sqlProvider}),this.modelAdapters[t]=n),n}commit(){return r(this,void 0,void 0,(function*(){return this.transactionState=d.TransactionState.COMMITTED,this.transaction.commit()}))}rollback(){return r(this,void 0,void 0,(function*(){return this.transactionState=d.TransactionState.ROLLED_BACK,this.transaction.rollback()}))}getState(){return this.transactionState}}let f=class DefaultSqlDatabaseAdapter extends c.AbstractDatabaseAdapter{constructor(e,t,n){super(),this.logger=n,this.injector=(0,s.getServiceProvider)().getInjector(),this.modelAdapters={},this.sqlProvider=e,this.dbConnection=new a.Sequelize(`${e}://${t}`,{dialect:this.sqlProvider,logging:e=>this.logger.debug(e),define:{timestamps:!1}})}createTransaction(){return r(this,void 0,void 0,(function*(){let e=yield this.dbConnection.transaction();return new TransactionAdapter({transaction:e,dbConnection:this.dbConnection,logger:this.logger,modelConnections:this.modelConnections,sqlProvider:this.sqlProvider})}))}init(){const e=Object.create(null,{init:{get:()=>super.init}});var t,n,i,o;return r(this,void 0,void 0,(function*(){yield e.init.call(this),yield this.injector.initInstances(),null===(t=this.logger)||void 0===t||t.debug("Connecting to database"),yield this.dbConnection.authenticate(),null===(n=this.logger)||void 0===n||n.debug("Generating in-memory schema");for(const e of this.modelMetadata){const t=this.generateSchemaObject(e);this.modelConnections[e.id].connection=t}for(const e of this.modelMetadata){const t=this.modelConnections[e.id].connection,n=e.fields.filter((e=>e.fk));for(const o of n){const n=null===(i=o.fk)||void 0===i?void 0:i.id;if(!n)throw s.ErrorBuilder.systemError(`FK model id not resolved for ${e.id}:${o.name}`);const r=this.modelConnections[n].connection;t.belongsTo(r,{foreignKey:o.name}),r.hasMany(t,{foreignKey:o.name})}}null===(o=this.logger)||void 0===o||o.debug("Database adapter init succeeded")}))}exit(){var e;return null===(e=this.logger)||void 0===e||e.debug("Closing connection to database"),this.dbConnection.close(),0}use(e){const t=getModelId(e);let n=this.modelAdapters[t];return n||(n=new ModelAdapter({model:e,dbConnection:this.dbConnection,modelConnections:this.modelConnections,logger:this.logger,sqlProvider:this.sqlProvider}),this.modelAdapters[t]=n),n}generateSchemaObject(e){let t={};const n=(0,h.getDirectFields)(e);for(const e of n){switch(t[e.name]={},e.dataType){case s.DataType.NUMBER:e.floating?t[e.name].type=a.DataTypes.FLOAT:e.isBigInt?t[e.name].type=a.DataTypes.BIGINT:t[e.name].type=a.DataTypes.INTEGER;break;case s.DataType.STRING:e.textLength?t[e.name].type=a.DataTypes.STRING(e.textLength):t[e.name].type=a.DataTypes.STRING;break;case s.DataType.BOOLEAN:t[e.name].type=a.DataTypes.BOOLEAN;break;case s.DataType.ARRAY:case s.DataType.OBJECT:t[e.name].type=a.DataTypes.TEXT}e.pk&&(t[e.name].primaryKey=!0,e.pk.isAutoIncrement&&(t[e.name].autoIncrement=!0)),void 0!==e.defaultValue&&(t[e.name].defaultValue=e.defaultValue),t[e.name].allowNull=!e.isRequired}return this.dbConnection.define(e.id,t,{tableName:e.id,freezeTableName:!0,name:{singular:e.id,plural:e.id}})}};f=i([(0,s.Initable)(),(0,s.Injectable)(),o("design:paramtypes",[String,String,s.AbstractLogger])],f),t.DefaultSqlDatabaseAdapter=f},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractQuery=void 0;const i=n(0);t.AbstractQuery=class AbstractQuery{constructor(e){const t=(0,i.getObjectMetadata)(e);this.model=(0,i.getModelById)(t.id)||e,this.metadata=(0,i.getObjectMetadata)(this.model)}convertToLogicObjects(e,t){return e.map((e=>{let n=new this.model;return this.metadata.fields.filter((e=>!t||t.includes(e.name))).forEach((t=>{const i=e[t.name];void 0!==i&&(t.isBigInt?n[t.name]=Number(i):t.vectorProps?n[t.name]=JSON.parse(i):n[t.name]=i)})),n}))}convertToDataObjects(e,t){const n=Date.now();return e.map((e=>{let i=new this.model;for(const o of this.metadata.fields){let r=e[o.name];o.vectorProps?r=JSON.stringify(r):(o.modificationTimestamp||o.creationTimestamp&&!t)&&(r=n),i[o.name]=r}return i}))}}},function(e,t,n){"use strict";var i,o=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},r=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},s=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSqlDatabaseMigrator=void 0;const d=a(n(23)),c=a(n(22)),l=n(52),u=n(0),h=n(12),p=n(13),f=n(3),g=n(25),uniqueGroupComparator=(e,t)=>!e.groupName&&!t.groupName&&e.fieldNames[0]===t.fieldNames[0]||!!e.groupName&&e.groupName===t.groupName;let y=i=class DefaultSqlDatabaseMigrator extends g.AbstractDatabaseMigrator{constructor(e,t,n,i){super(),this.cliPath=e,this.sqlProvider=t,this.connectionString=n,this.logger=i,this.injector=(0,u.getServiceProvider)().getInjector(),this.cliPath=e,this.databaseURL=`${t}://${n}`,this.modelMetadata=((0,u.getGlobalStore)().models||[]).map((e=>(0,u.getObjectMetadata)(e)))}init(){return s(this,void 0,void 0,(function*(){yield this.injector.initInstances()}))}exit(){}getUniqueConstraintGroups(e){const t=[],n=(0,f.getDirectFields)(e).filter((e=>!!e.unique));for(const e of n)if(e.unique.groupName){let n=t.find((t=>t.groupName===e.unique.groupName));n||(n={groupName:e.unique.groupName,fieldNames:[]},t.push(n)),n.fieldNames.push(e.name)}else t.push({fieldNames:[e.name]});return t}generateFieldPropertiesQuery(e){let t="{";if(e.pk&&(t+="primaryKey:true,",e.pk.isAutoIncrement&&(t+="autoIncrement:true,")),void 0!==e.defaultValue&&(t+=`defaultValue:${JSON.stringify(e.defaultValue)},`),t+=`allowNull:${e.isRequired?"false":"true"},`,void 0!==e.dataType)switch(e.dataType){case u.DataType.STRING:e.textLength?t+=`type:Sequelize.STRING(${e.textLength}),`:t+="type:Sequelize.TEXT,";break;case u.DataType.NUMBER:e.floating?t+="type:Sequelize.FLOAT,":e.isBigInt?t+="type:Sequelize.BIGINT,":t+="type:Sequelize.INTEGER,";break;case u.DataType.BOOLEAN:t+="type:Sequelize.BOOLEAN,";break;case u.DataType.ARRAY:case u.DataType.OBJECT:t+="type:Sequelize.TEXT,"}return t+="}",t}getUniqueConstraintUpDown(e,t){const n=`${e}_${t.groupName||t.fieldNames[0]}_un`;return[`queryInterface.addConstraint("${e}",{fields:${JSON.stringify(t.fieldNames)},type:"unique",name:"${n}","transaction":t})`,`queryInterface.removeConstraint("${e}","${n}",{"transaction":t})`]}getSqlCascadeAction(e){switch(e){case"delete":return"CASCADE";case"restrict":return"RESTRICT";case"nullify":return"SET NULL";default:return"RESTRICT"}}getForeignKeyConstraintUpDown(e,t,n){var i,o;const r=`${t}_${n.name}_fk`;return[`queryInterface.addConstraint("${t}",{fields:["${n.name}"],type:"foreign key",name:"${r}",references:{table:"${e.id}",field:"id"},onDelete:'${this.getSqlCascadeAction(null===(i=n.fk)||void 0===i?void 0:i.cascade)}',onUpdate:'${this.getSqlCascadeAction(null===(o=n.fk)||void 0===o?void 0:o.cascade)}',"transaction":t})`,`queryInterface.removeConstraint("${t}","${r}",{"transaction":t})`]}getAddColumnUpDown(e,t){return[`queryInterface.addColumn('${e}','${t.name}',${this.generateFieldPropertiesQuery(t)},{"transaction":t})`,`queryInterface.removeColumn('${e}','${t.name}',{"transaction":t})`]}generateCreateTableQuery(e){let t={upTableAdd:[],downTableRemove:[],upConstraintAdd:[],downConstraintRemove:[],upTableRemove:[],downTableAdd:[],upConstraintRemove:[],downConstraintAdd:[]},n="",i="";n+="{\n";for(const t of(0,f.getDirectFields)(e)){let e=this.generateFieldPropertiesQuery(t);n+=`${t.name}:${e},\n`}n+="}\n",i+='{charset:"utf8",transaction:t}',t.upTableAdd.push(`queryInterface.createTable("${e.id}",${n},{charset:"utf8",transaction:t})`),t.downTableRemove.push(`queryInterface.dropTable("${e.id}",{"transaction":t})`);const o=this.getUniqueConstraintGroups(e);for(const n of o){const[i,o]=this.getUniqueConstraintUpDown(e.id,n);t.upConstraintAdd.push(i),t.downConstraintRemove.push(o)}for(const n of(0,f.getDirectFields)(e))if(n.fk){let i=this.modelMetadata.find((e=>{var t;return e.id===(null===(t=n.fk)||void 0===t?void 0:t.id)}));const[o,r]=this.getForeignKeyConstraintUpDown(i,e.id,n);t.upConstraintAdd.push(o),t.downConstraintRemove.push(r)}return t}isBooleanDiff(e,t){return!!e&&!t||!!t&&!e}runProcess(e){return s(this,void 0,void 0,(function*(){return new Promise(((t,n)=>{(0,l.exec)(e,{env:process.env},(e=>(e&&n(e),t())))}))}))}rollback(e){return s(this,void 0,void 0,(function*(){let t=d.default.join(e,"scripts");if(!c.default.existsSync)throw u.ErrorBuilder.systemError("Migration directory not found");this.logger.debug("Rolling back last migration"),yield this.runProcess(`${this.cliPath} --url=${this.databaseURL} --migrations-path=${t} db:migrate:undo`),this.logger.debug("Rollback completed")}))}migrate(e){var t,n,o,r,a,l,g,y;return s(this,void 0,void 0,(function*(){let m=d.default.join(e,"metadata.json"),v=d.default.join(e,"scripts");c.default.existsSync(v)||(this.logger.debug("Migration directory not exists, creating empty folder"),c.default.mkdirSync(v,{recursive:!0})),c.default.existsSync(m)||(this.logger.debug("Migration metadata does not exist, creating one"),c.default.writeFileSync(m,JSON.stringify([]))),this.logger.debug("Parsing migration metadata file");let b=JSON.parse(String(c.default.readFileSync(m)));this.logger.debug("Calculating differences...");const C=this.modelMetadata.filter((e=>!b.find((t=>e.id===t.id)))),M=this.modelMetadata.filter((e=>b.find((t=>t.id===e.id)))).map((e=>e.id));let O=[];O.push(...C.map((e=>this.generateCreateTableQuery(e))));for(const e of M){const i=b.find((t=>t.id===e)),s=this.modelMetadata.find((t=>t.id===e));i.id!==s.id&&O.push({upTableAdd:[`queryInterface.query("ALTER TABLE ${i.id} RENAME TO ${s.id}",{"transaction":t})`],downTableRemove:[`queryInterface.query("ALTER TABLE ${s.id} RENAME TO ${i.id}",{"transaction":t})`],upConstraintAdd:[],downConstraintRemove:[],upTableRemove:[],downTableAdd:[],upConstraintRemove:[],downConstraintAdd:[]});let d={upTableAdd:[],downTableRemove:[],upConstraintAdd:[],downConstraintRemove:[],upTableRemove:[],downTableAdd:[],upConstraintRemove:[],downConstraintAdd:[]};const c=(0,f.getDirectFields)(i).filter((e=>!(0,f.getDirectFields)(s).find((t=>e.name===t.name))));for(const e of c){const[t,n]=this.getAddColumnUpDown(s.id,e);if(d.upTableRemove.push(n),d.downTableAdd.push(t),e.fk){let t=this.modelMetadata.find((t=>{var n;return t.id===(null===(n=e.fk)||void 0===n?void 0:n.id)}));const[n,i]=this.getForeignKeyConstraintUpDown(t,s.id,e);d.upConstraintRemove.push(i),d.downConstraintAdd.push(n)}}const u=(0,f.getDirectFields)(s).filter((e=>!(0,f.getDirectFields)(i).find((t=>e.name===t.name))));for(const e of u){const[t,n]=this.getAddColumnUpDown(s.id,e);if(d.upTableAdd.push(t),d.downTableRemove.push(n),e.fk){let t=this.modelMetadata.find((t=>{var n;return t.id===(null===(n=e.fk)||void 0===n?void 0:n.id)}));const[n,i]=this.getForeignKeyConstraintUpDown(t,s.id,e);d.upConstraintAdd.push(n),d.downConstraintRemove.push(i)}}const h=(0,f.getDirectFields)(s).filter((e=>(0,f.getDirectFields)(i).find((t=>e.name===t.name)))).map((e=>e.name));for(const e of h){const c=(0,f.getFieldByName)(i,e),u=(0,f.getFieldByName)(s,e);if((this.isBooleanDiff(c.floating,u.floating)||this.isBooleanDiff(c.isBigInt,u.isBigInt)||this.isBooleanDiff(c.isRequired,u.isRequired)||this.isBooleanDiff(null===(t=c.pk)||void 0===t?void 0:t.isAutoIncrement,null===(n=u.pk)||void 0===n?void 0:n.isAutoIncrement)||c.dataType!==u.dataType||c.textLength!==u.textLength||c.defaultValue!==u.defaultValue)&&(d.upTableAdd.push(`queryInterface.changeColumn("${s.id}","${u.name}",${this.generateFieldPropertiesQuery(u)},{"transaction":t})`),d.downTableRemove.push(`queryInterface.changeColumn("${s.id}","${c.name}",${this.generateFieldPropertiesQuery(c)},{"transaction":t})`)),(null===(o=c.fk)||void 0===o?void 0:o.id)!==(null===(r=u.fk)||void 0===r?void 0:r.id)||(null===(a=c.fk)||void 0===a?void 0:a.cascade)!==(null===(l=u.fk)||void 0===l?void 0:l.cascade)){if(null===(g=c.fk)||void 0===g?void 0:g.id){const e=this.modelMetadata.find((e=>{var t;return e.id===(null===(t=c.fk)||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===(y=u.fk)||void 0===y?void 0:y.id){const e=this.modelMetadata.find((e=>{var t;return e.id===(null===(t=u.fk)||void 0===t?void 0:t.id)})),[t,n]=this.getForeignKeyConstraintUpDown(e,s.id,u);d.upTableAdd.push(t),d.downTableRemove.push(n)}}}const p=this.getUniqueConstraintGroups(i),m=this.getUniqueConstraintGroups(s),v=p.filter((e=>!!m.find((t=>uniqueGroupComparator(e,t))))),C=p.filter((e=>!v.find((t=>uniqueGroupComparator(e,t)))));for(const e of C){const[t,n]=this.getUniqueConstraintUpDown(s.id,e);d.upConstraintRemove.push(n),d.downConstraintAdd.push(t)}const M=m.filter((e=>!v.find((t=>uniqueGroupComparator(e,t)))));for(const e of M){const[t,n]=this.getUniqueConstraintUpDown(s.id,e);d.upConstraintAdd.push(t),d.downConstraintRemove.push(n)}for(const e of v){const t=p.find((t=>uniqueGroupComparator(t,e))),n=m.find((t=>uniqueGroupComparator(t,e)));if(t.fieldNames.length!==n.fieldNames.length||t.fieldNames.some((e=>!n.fieldNames.includes(e)))){const[e,i]=this.getUniqueConstraintUpDown(s.id,t),[o,r]=this.getUniqueConstraintUpDown(s.id,n);d.upConstraintRemove.push(i),d.upConstraintAdd.push(o),d.downConstraintRemove.push(r),d.downConstraintAdd.push(e)}}(d.upTableAdd.length||d.downTableRemove.length||d.upConstraintAdd.length||d.downConstraintRemove.length||d.upConstraintRemove.length||d.downConstraintAdd.length||d.upTableRemove.length||d.downTableAdd.length)&&O.push(d)}if(O.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(v,t),o=i.MIGRATION_TEMPLATE,r=new RegExp(i.COMMENT_BLOCK_REGEX_PATTERN),s=getTransactionalScript(e.up),a=getTransactionalScript(e.down);o=o.replace(r,s),o=o.replace(r,a),this.logger.debug("Writing to file",n),c.default.writeFileSync(n,o)}));throw yield migrationFunction({up:[...O.reduce(((e,t)=>e.concat(t.upConstraintRemove)),[]),...O.reduce(((e,t)=>e.concat(t.upTableRemove)),[]),...O.reduce(((e,t)=>e.concat(t.upTableAdd)),[]),...O.reduce(((e,t)=>e.concat(t.upConstraintAdd)),[])],down:[...O.reduce(((e,t)=>e.concat(t.downConstraintRemove)),[]).reverse(),...O.reduce(((e,t)=>e.concat(t.downTableRemove)),[]).reverse(),...O.reduce(((e,t)=>e.concat(t.downTableAdd)),[]).reverse(),...O.reduce(((e,t)=>e.concat(t.downConstraintAdd)),[]).reverse()]},e),this.logger.debug("Updating metadata file"),c.default.writeFileSync(m,JSON.stringify(this.modelMetadata)),u.ErrorBuilder.systemError(`Migration review needed: ${e}`)}this.logger.debug("No difference, running migration"),this.logger.debug("Create database if not exist");try{yield this.runProcess(`${this.cliPath} --url=${this.databaseURL} db:create`)}catch(e){if(String(e).indexOf("already exists")<0)throw e}if(this.logger.debug("Running migration"),this.sqlProvider===p.SqlProvider.POSTGRES){this.logger.debug("Creating unaccent extension for postgres");const e=new h.Sequelize(this.databaseURL);yield e.query("CREATE EXTENSION IF NOT EXISTS unaccent;")}else if(this.sqlProvider===p.SqlProvider.MYSQL){this.logger.debug("Creating unaccent function for mysql");const e=new h.Sequelize(this.databaseURL,{dialectOptions:{multipleStatements:!0}}),t="ĂÂÀÁẢÃẠẰẮẲẴẶẦẤẨẪẬÔƠÒÓỎÕỌỒỐỔỖỘỜỚỞỠỢÈÉẺẼẸÊỀẾỂỄỆÙÚỦŨỤƯỪỨỬỮỰÌÍỈĨỊỲÝỶỸỴ",n="AAAAAAAAAAAAAAAAAOOOOOOOOOOOOOOOOOEEEEEEEEEEEUUUUUUUUUUUIIIIIYYYYY",i=`SET GLOBAL log_bin_trust_function_creators = 1; \nDROP FUNCTION IF EXISTS unaccent; \nCREATE FUNCTION unaccent( textvalue TEXT ) RETURNS TEXT \nBEGIN \nSET @textvalue = textvalue; \nSET @withaccents = 'ŠšŽžÄÅÆÇËÎÏÑÖØÛÜŸÞäåæçëîïñõöøûüÿþƒ${t}${t.toLowerCase()}'; \nSET @withoutaccents = 'SsZzAAACEIINOOUUYBaaaceiinooouuybf${n}${n.toLowerCase()}'; \nSET @count = LENGTH(@withaccents); \nWHILE @count > 0 DO \nSET @textvalue = REPLACE(@textvalue, SUBSTRING(@withaccents, @count, 1), SUBSTRING(@withoutaccents, @count, 1)); \nSET @count = @count - 1; \nEND WHILE; \nRETURN @textvalue; \nEND; \n`;yield e.query(i,{type:h.QueryTypes.RAW})}yield this.runProcess(`${this.cliPath} --url=${this.databaseURL} --migrations-path=${v} db:migrate`),this.logger.debug("Migration finished")}))}};y.COMMENT_BLOCK_REGEX_PATTERN="/\\*(\\*(?!/)|[^*])*\\*\\/",y.MIGRATION_TEMPLATE="'use strict';\n module.exports = {\n up: async (queryInterface, Sequelize) => {\n /**\n */\n },\n \n down: async (queryInterface, Sequelize) => {\n /**\n */\n }\n };",y=i=o([(0,u.Injectable)(),r("design:paramtypes",[String,String,String,u.AbstractLogger])],y),t.DefaultSqlDatabaseMigrator=y},function(e,t){e.exports=require("child_process")},function(e,t,n){"use strict";var i=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},o=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},r=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))},s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.LocalSocketManager=void 0;const a=n(0),d=s(n(54)),c=n(1),l=n(2),u=n(4),h=n(26);class ExpressSocket extends h.AbstractServerSocket{constructor(e,t,n,i){super(e,t,n),this.logger=e,this.httpRequestHandler=t,this.authorizationProvider=n,this.socket=i;const o=Date.now();this.socketInfo={id:`${o.toString()}-${Math.trunc(1e6*Math.random())}`,isOpen:!0,authorized:!1,createdAt:o}}physicSend(e){return r(this,void 0,void 0,(function*(){this.socket.send(e)}))}setOpen(e){return r(this,void 0,void 0,(function*(){this.socketInfo.isOpen=e}))}physicDisconnect(){return r(this,void 0,void 0,(function*(){this.socket.close()}))}authorize(e){const t=Object.create(null,{authorize:{get:()=>super.authorize}});return r(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:i}=JSON.parse(e.data);n.handleMessage(i,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 r(this,void 0,void 0,(function*(){}))}create(e){return new ExpressSocket(this.logger,this.httpRequestHandler,this.authorizationProvider,e)}getAllSockets(){return r(this,void 0,void 0,(function*(){return this.allSockets}))}add(e){return r(this,void 0,void 0,(function*(){this.allSockets.push(e)}))}removeById(e){return r(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 r(this,void 0,void 0,(function*(){return this.allSockets.find((t=>t.getId()===e))}))}};p=i([(0,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 i=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},o=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},r=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))},s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.AwsSocketManager=void 0;const a=n(0),d=s(n(56)),c=s(n(57)),l=n(1),u=n(4),h=n(26),p=n(2);class ApiGatewaySocket extends h.AbstractServerSocket{constructor(e,t,n,i,o,r,s,a){super(t,n,i),this.socketManager=e,this.socketInfo=Object.assign({},o),this.apiGateway=r,this.redisClient=a,this.socketNamespace=s}physicSend(e){return r(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 r(this,void 0,void 0,(function*(){return new Promise(((e,t)=>this.redisClient.hset(this.socketNamespace,this.socketInfo.id||"",JSON.stringify(this.socketInfo),(n=>n?t(n):e()))))}))}physicDisconnect(){return r(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=>{this.logger.debug("Socket remove error",e)}))}))}setOpen(e){return r(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 r(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 r(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 r(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,i,o,r,s){super(s),this.region=e,this.socketDomainUrl=t,this.redisServerUrl=n,this.socketNamespace=i,this.httpRequestHandler=o,this.authorizationProvider=r,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 r(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:i}=e.body;return yield null==t?void 0:t.handleMessage(n,i),{code:200}}default:return}}))}init(){return r(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("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 r(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 r(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 r(this,void 0,void 0,(function*(){const t=yield new Promise(((t,n)=>this.redisClient.hget(this.socketNamespace,e,((e,i)=>e?n(e):t(i)))));if(t)return this.logger.debug("Serialized aws socket",t),this.create(JSON.parse(t))}))}getAllSockets(){return r(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,i)=>n?t(n):e(Object.keys(i).map((e=>{const t=i[e];return this.logger.debug("parsing serialized sockets",t),this.create(JSON.parse(t))})))))))}))}};f=i([(0,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";Object.defineProperty(t,"__esModule",{value:!0}),t._is=t._join=t._max=t._min=t._avg=t._sum=t._count=void 0;t._count=(e,t)=>({fn:"count",field:e,args:t});t._sum=e=>({fn:"sum",field:e});t._avg=e=>({fn:"avg",field:e});t._min=e=>({fn:"min",field:e});t._max=e=>({fn:"max",field:e});t._join=(e,t)=>({fn:"join",field:e,args:t});t._is=e=>({fn:"is",field:e})},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0})}])}));
|
|
1
|
+
!function webpackUniversalModuleDefinition(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var n=t();for(var i in n)("object"==typeof exports?exports:e)[i]=n[i]}}(global,(function(){return function(e){var t={};function __webpack_require__(n){if(t[n])return t[n].exports;var i=t[n]={i:n,l:!1,exports:{}};return e[n].call(i.exports,i,i.exports,__webpack_require__),i.l=!0,i.exports}return __webpack_require__.m=e,__webpack_require__.c=t,__webpack_require__.d=function(e,t,n){__webpack_require__.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},__webpack_require__.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},__webpack_require__.t=function(e,t){if(1&t&&(e=__webpack_require__(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(__webpack_require__.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var i in e)__webpack_require__.d(n,i,function(t){return e[t]}.bind(null,i));return n},__webpack_require__.n=function(e){var t=e&&e.__esModule?function getDefault(){return e.default}:function getModuleExports(){return e};return __webpack_require__.d(t,"a",t),t},__webpack_require__.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},__webpack_require__.p="",__webpack_require__(__webpack_require__.s=27)}([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.AbstractHttpAuthorizationProvider=void 0;t.AbstractHttpAuthorizationProvider=class AbstractHttpAuthorizationProvider{}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getDirectFields=t.getFieldByName=t.getTransactionFromContext=void 0;const i=n(0),o=n(8);t.getTransactionFromContext=e=>{const t=e[o.INJECTED_TRANSACTION];if(!t)throw i.ErrorBuilder.systemError("Cannot get transaction from current context");return t};t.getFieldByName=(e,t)=>e.fields.find((e=>e.name===t));t.getDirectFields=e=>e.fields.filter((e=>!e.hasMany))},function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractServerSocketManager=void 0;const o=n(24);t.AbstractServerSocketManager=class AbstractServerSocketManager{constructor(e){this.logger=e}getAllAliveSockets(){return i(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 i(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 i=n(0);t.HttpRequest=class HttpRequest{constructor(e,t){this.valueHolder={},this.method=e.method,this.pathName=e.pathName,this.headers=e.headers||{},this.hash=e.hash||"",this.socket=e.socket,this.params=e.params||{},(null==t?void 0:t.paramsValidationDto)&&(this.params=(0,i.validateData)(this.params,null==t?void 0:t.paramsValidationDto)),this.query=e.query||{},(null==t?void 0:t.queriesValidationDto)&&(this.query=(0,i.validateData)(this.jsonParsing(this.query,t.queriesValidationDto),t.queriesValidationDto)),this.body=e.body||{},t&&(t.httpMethod===i.HttpMethod.POST||t.httpMethod===i.HttpMethod.PUT)&&(null==t?void 0:t.bodyValidationDto)&&(this.body=(0,i.validateData)(this.body||{},t.bodyValidationDto))}jsonParsing(e,t){const n=Object.assign({},e);for(const o of t.fields)try{(void 0!==e[o.name]||o.isRequired)&&(n[o.name]=JSON.parse(e[o.name]))}catch(e){throw i.ErrorBuilder.error(i.Errors.VALIDATION_ERROR,`JSON parsing failed for field ${o.name}`)}return n}getAuthInfo(){return this.authInfo}setAuthInfo(e){this.authInfo=e}getHeaders(){return this.headers}getMethod(){return this.method}getHash(){return this.hash}getPathName(){return this.pathName}getValue(e){return this.valueHolder[e]}setValue(e,t){this.valueHolder[e]=t}getParams(){return this.params}getQuery(){return this.query}getBody(){return this.body}getSocket(){if(!this.socket)throw i.ErrorBuilder.systemError("Socket not found for current request");return this.socket}}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ResponseBuilder=t.HttpResponse=void 0;class HttpResponse{constructor(){this.code=200,this.headers={},this.cookies={}}}t.HttpResponse=HttpResponse;class ResponseBuilder{constructor(){this.response=new HttpResponse}status(e){return this.response.code=e,this}header(e,t){return this.response.headers[e]=t,this}cookie(e,t){return this.response.headers[e]=t,this}get(){return this.response}static json(e){const t=new ResponseBuilder;return t.response.value=e,t.response.headers["Content-Type"]="application/json",t}static html(e){const t=new ResponseBuilder;return t.response.value=e,t.response.headers["Content-Type"]="text/html; charset=UTF-8",t}static binary(e){const t=new ResponseBuilder;return t.response.value=e,t.response.headers["Content-Type"]="application/octet-stream",t}static success(){const e=new ResponseBuilder;return e.response.code=200,e.response}static notFound(e){const t=new ResponseBuilder;return t.response.code=404,t.response.value=e,t.response}static accessDenied(e){const t=new ResponseBuilder;return t.response.code=400,t.response.value=e,t.response}}t.ResponseBuilder=ResponseBuilder},function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractHttpController=void 0;const o=n(0),r=n(3);t.AbstractHttpController=class AbstractHttpController{constructor(e){this.databaseAdapter=e}isEndpoint(e){return!!e.httpMethod||void 0!==e.openAccess||!!e.accessConditions}getCurrentDatabaseAdapter(){return i(this,void 0,void 0,(function*(){return this.databaseAdapter}))}getCurrentTransaction(){return i(this,void 0,void 0,(function*(){return(0,r.getTransactionFromContext)(this)}))}getEndpointMetadata(){const e=(0,o.getObjectMetadata)(this.constructor);return e?e.fields.filter((e=>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";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractDatabaseAdapter=void 0;const o=n(0);t.AbstractDatabaseAdapter=class AbstractDatabaseAdapter{constructor(){this.modelMetadata=[],this.models=[],this.modelConnections={}}init(){return i(this,void 0,void 0,(function*(){this.models=((0,o.getGlobalStore)().models||[]).slice(),this.modelMetadata=this.models.map((e=>(0,o.getObjectMetadata)(e))),this.modelConnections=this.modelMetadata.reduce(((e,t)=>Object.assign(e,{[t.id]:{connection:void 0}})),{})}))}exit(){}}},function(e,t){e.exports=require("sequelize")},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.Raw=t.Headers=t.Queries=t.Params=t.Body=t.AccessCondition=t.OpenAccess=t.ApiResponse=t.Get=t.Del=t.Put=t.Post=t.Socket=t.Endpoint=t.Controller=void 0;const i=n(0);t.Controller=e=>t=>{(0,i.getServiceProvider)().register(t,"singleton");(0,i.initObjectMetadata)(t.prototype).permissionGroup=null==e?void 0:e.permissionGroup};t.Endpoint=e=>(t,n)=>{const o=(0,i.initFieldMetadata)(t,n);o.httpMethod=e.method,o.url=e.url};t.Socket=e=>(n,o,r)=>(0,t.Endpoint)({method:i.SocketMethod.MESSAGE,url:e})(n,o);t.Post=e=>(n,o,r)=>(0,t.Endpoint)({method:i.HttpMethod.POST,url:e})(n,o);t.Put=e=>(n,o,r)=>(0,t.Endpoint)({method:i.HttpMethod.PUT,url:e})(n,o);t.Del=e=>(n,o,r)=>(0,t.Endpoint)({method:i.HttpMethod.DEL,url:e})(n,o);t.Get=e=>(n,o,r)=>(0,t.Endpoint)({method:i.HttpMethod.GET,url:e})(n,o);t.ApiResponse=e=>(t,n,o)=>{(0,i.initFieldMetadata)(t,n).responseValidationDto=(0,i.getObjectMetadata)(e)};t.OpenAccess=()=>(e,t)=>{(0,i.initFieldMetadata)(e,t).openAccess=!0};t.AccessCondition=e=>(t,n)=>{(0,i.initFieldMetadata)(t,n).accessConditions=e};const RequestDeco=e=>(t,n,o)=>{const r=(0,i.initFieldMetadata)(t,n),s=Reflect.getMetadata("design:paramtypes",t,n)||[];switch(e){case"body":r.bodyValidationDto=(0,i.getObjectMetadata)(s[o]);break;case"params":r.paramsValidationDto=(0,i.getObjectMetadata)(s[o]);break;case"queries":r.queriesValidationDto=(0,i.getObjectMetadata)(s[o])}r.params||(r.params={}),r.params[o]={source:e,diClass:s[o]}};t.Body=()=>RequestDeco("body");t.Params=()=>RequestDeco("params");t.Queries=()=>RequestDeco("queries");t.Headers=()=>RequestDeco("headers");t.Raw=()=>RequestDeco("raw")},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";var i=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},o=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.FilterModelFieldAccessCondition=void 0;const r=n(0),s=n(9);t.FilterModelFieldAccessCondition=(e,t)=>{let n=class _ extends s.AbstractAccessCondition{resolveConditionValue(e){return o(this,void 0,void 0,(function*(){return t(e)}))}getConditionMetadata(){return{name:"filter_model_field",valueType:r.AccessConditionValueType.CHOICES,valueConstraint:(0,r.getObjectMetadata)(e).fields.map((e=>e.name))}}validate(e,t){return o(this,void 0,void 0,(function*(){return!!e&&e.every((e=>t.includes(e)))}))}};return n=i([(0,r.Register)({mode:"transient"})],n),n}},function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.Transactional=void 0;const o=n(0),r=n(8),s=n(10),a=n(19);t.Transactional=e=>(t,n,d)=>{const c=(0,o.initObjectMetadata)(t);(0,o.initFieldMetadata)(t,n),c.transactional=!0;const l=d.value;d.value=function(...d){return i(this,void 0,void 0,(function*(){const i=this;let c,u,h;try{c=yield i.getCurrentTransaction()}catch(e){}switch(e){case s.TransactionLink.CREATE_NEW:u=!0,h=yield(yield i.getCurrentDatabaseAdapter()).createTransaction();break;case s.TransactionLink.INHERIT_OR_CREATE:u=!c,h=c||(yield(yield i.getCurrentDatabaseAdapter()).createTransaction());break;case s.TransactionLink.INHERIT_OR_THROW:if(u=!1,!c)throw o.ErrorBuilder.systemError(`No transaction to inherit when executing ${t.constructor.name}:${n}`);h=c}const p=Object.assign(Object.create(i),i),f=Object.keys(p).filter((e=>{var t,n;return(null===(t=p[e])||void 0===t?void 0:t.constructor)&&(null===(n=(0,o.getObjectMetadata)(p[e].constructor))||void 0===n?void 0:n.transactional)}));for(const e of f){const t=p[e],n=Object.assign(Object.create(t),t,{[r.INJECTED_TRANSACTION]:h});p[e]=n}try{Object.assign(p,{[r.INJECTED_TRANSACTION]:h});let e=yield l.call(p,...d);return h.getState()===a.TransactionState.EXECUTING&&u&&(yield h.commit()),e}catch(e){throw h.getState()===a.TransactionState.EXECUTING&&u&&(yield h.rollback()),e}}))},Object.defineProperty(d.value,"name",{value:n})}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TransactionState=void 0,function(e){e.EXECUTING="executing",e.COMMITTED="commited",e.ROLLED_BACK="rolled_back"}(t.TransactionState||(t.TransactionState={}))},function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.ModelRepository=void 0;const o=n(0),r=n(3),s=n(21);class ModelRepository{constructor(e){this.model=e,this.modelMetadata=(0,o.getObjectMetadata)(this.model)}getNestedQueries(e){return this.modelMetadata.fields.filter((e=>e.hasMany)).filter((t=>e.fields&&e.fields[t.name])).map((t=>{const n=this.getRequestQueryConditionFromQuery(e.fields[t.name],(0,o.getObjectMetadata)((0,o.getModelById)(t.hasMany.id)));return{modelId:t.hasMany.id,queries:n.length?{_and:n}:{}}}))}getUploadHandler(){return i(this,void 0,void 0,(function*(){if(void 0===this.fileUploadHandler){const e=(0,o.getServiceProvider)().getInjector();this.fileUploadHandler=e.resolveOptional(s.AbstractFileUploadHandler)||null,yield e.initInstances()}return this.fileUploadHandler}))}getRequestQueryConditionFromQuery(e,t){var n;const i=[];for(const s of(0,r.getDirectFields)(t))if(e[s.name])if(s.pk||s.fk||s.isSymbol)i.push({_in:{[s.name]:e[s.name]}});else if(s.enum)i.push({_in:{[s.name]:e[s.name]}});else switch(s.dataType){case o.DataType.STRING:if(s.searchable){const t={[(null==s?void 0:s.searchable.caseSensitive)?(null==s?void 0:s.searchable.accentSensitive)?"_sub":"_usub":(null===(n=null==s?void 0:s.searchable)||void 0===n?void 0:n.accentSensitive)?"_isub":"_iusub"]:{[s.name]:e[s.name]}};i.push(t)}else i.push({_eq:{[s.name]:e[s.name]}});break;case o.DataType.NUMBER:const t=new o.RangeQueryDto;Object.assign(t,e[s.name]),t.min&&(t.minExclusive?i.push({_gt:{[s.name]:t.min}}):i.push({_gte:{[s.name]:t.min}})),t.max&&(t.maxExclusive?i.push({_lt:{[s.name]:t.max}}):i.push({_lte:{[s.name]:t.max}}))}return i}beforeCreating(e,t){return i(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 i(this,void 0,void 0,(function*(){const i=yield this.getUploadHandler();if(!i)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],r=t.mimeProps.uriMapper(n);e&&r&&(yield i.moveFile(e,r),n[t.name]=r,yield o.updateOne(n))}}))}beforeReturning(e){var t,n;return i(this,void 0,void 0,(function*(){const i=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)&&i){if(!o[e.name])continue;o[e.name]=(null===(n=e.mimeProps)||void 0===n?void 0:n.public)?yield i.resolvePublicUrl(o[e.name]):yield i.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 i(this,void 0,void 0,(function*(){const i=(0,r.getDirectFields)(this.modelMetadata),s=this.modelMetadata.fields.filter((e=>!!e.hasMany)),a=t.records;t.records=a.map((e=>i.reduce(((t,n)=>Object.assign(t,void 0!==e[n.name]?{[n.name]:e[n.name]}:{})),{}))),yield this.beforeCreating(e,t.records);let d=t.records.length?yield n.use(this.model).createMany(t.records):[];yield this.uriHandling(d,n),yield this.beforeReturning(d);const c=this.modelMetadata.fields.filter((e=>e.pk||e.serverValue||e.mimeProps)).map((e=>e.name));d=this.project(d,c);for(const i of s){const r=d.map(((e,t)=>(a[t][i.name]||[]).map((t=>Object.assign(Object.assign({},t),{[i.hasMany.column]:e.id}))))).reduce(((e,t)=>e.concat(t)),[]);if(r.length){const s=new ModelRepository((0,o.getModelById)(i.hasMany.id));t.records=r;const a=yield s.createMany({principal:e,body:t,tx:n});for(let e=0;e<a.records.length;e++)r[e]=Object.assign(Object.assign({},r[e]),a.records[e]);for(let e=0;e<d.length;e++){const t=[];for(let n=0;n<r.length;n++)r[n][i.hasMany.column]===d[e].id&&t.push(a.records[e]);d[e]=Object.assign(Object.assign({},d[e]),{[i.name]:t})}}}return{records:d}}))}updateMany({principal:e,queries:t,body:n,tx:s}){return i(this,void 0,void 0,(function*(){let i={};const a=this.modelMetadata.fields.filter((e=>!!e.hasMany)),d=(0,r.getDirectFields)(this.modelMetadata).filter((e=>void 0!==n.update[e.name])),c=d.reduce(((e,t)=>Object.assign(e,{[t.name]:n.update[t.name]})),{});if(t.fields){const e=this.getRequestQueryConditionFromQuery(t.fields,this.modelMetadata);e.length&&(i={_and:[...e]})}const l=this.getNestedQueries(t);let u=[];if(l.length){const e=yield s.use(this.model).getMany(i,{projection:["id"]},l);u=e.records.map((e=>e.id)),u.length&&d.length&&(yield s.use(this.model).updateMany({_in:{id:u}},c,!1))}else if(d.length)u=yield s.use(this.model).updateMany(i,c,!0);else{const e=yield s.use(this.model).getMany(i,{projection:["id"]});u=e.records.map((e=>e.id))}let h=u.map((e=>Object.assign(Object.assign({},c),{id:e})));yield this.uriHandling(h,s),yield this.beforeReturning(h);for(const t of a){const i=n.update[t.name];if(void 0===i||!u.length)continue;if(u.length>1)throw o.ErrorBuilder.systemError(`Multiple records found while updating @HasMany field: ${t.name}`);const r=h.find((e=>e.id===u[0])),a=(0,o.getModelById)(t.hasMany.id),d=s.use(a),c=(yield d.getRecords({_eq:{[t.hasMany.column]:r.id}})).map((e=>e.id)),l=i.map((e=>e.id)).filter((e=>!!e)),p=c.filter((e=>!l.includes(e))),f=i.filter((e=>!e.id)).map((e=>Object.assign(Object.assign({},e),{[t.hasMany.column]:r.id}))),g=i.filter((e=>!!e.id));yield d.deleteMany({_in:{id:p}});const y=new ModelRepository(a),m=yield y.createMany({principal:e,body:{records:f},tx:s}),v=f.map(((e,t)=>Object.assign(Object.assign({},e),m.records[t])));r[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,queryProvider:t}){var n;return i(this,void 0,void 0,(function*(){const i=[];if(e.fields&&i.push(...this.getRequestQueryConditionFromQuery(e.fields,this.modelMetadata)),e.search){const t=this.modelMetadata.fields.filter((e=>e.searchable)).map((t=>({_iusub:{[t.name]:e.search}})));t.length&&i.push({_or:t})}const r=yield t.use(this.model).getMany(i.length?{_and:i}:{},{limit:e.limit,page:e.page,projection:e.projection,order:null===(n=e.order)||void 0===n?void 0:n.map((e=>{const t=Object.keys(e).find((t=>!!e[t]));return[t,e[t]]}))},this.getNestedQueries(e)),s=r.records.map((e=>e.id));for(const n of this.modelMetadata.fields){if(!n.hasMany||e.projection&&!e.projection.includes(n.name))continue;const i=(0,o.getModelById)(n.hasMany.id),a=new ModelRepository(i),d=s.length?yield a.getMany({queries:{fields:{[n.hasMany.column]:s}},queryProvider:t}):{records:[]};for(const e of r.records)e[n.name]=d.records.filter((t=>t[n.hasMany.column]===e.id))}return yield this.beforeReturning(r.records),{total:r.total,records:this.project(r.records,e.projection)}}))}deleteMany({queries:e,tx:t}){return i(this,void 0,void 0,(function*(){let n={};if(e.fields){const t=this.getRequestQueryConditionFromQuery(e.fields,this.modelMetadata);t.length&&(n={_and:[...t]})}const i=this.getNestedQueries(e);let o=[];if(i.length){const e=yield t.use(this.model).getRecords(n,{},i);yield t.use(this.model).deleteMany({_in:{id:e.map((e=>e.id))}}),o=e}else o=yield t.use(this.model).deleteMany(n,e.returning);return{modified:o}}))}}t.ModelRepository=ModelRepository},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractFileUploadHandler=void 0;t.AbstractFileUploadHandler=class AbstractFileUploadHandler{}},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.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";Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractDatabaseMigrator=void 0;t.AbstractDatabaseMigrator=class AbstractDatabaseMigrator{}},function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractServerSocket=void 0;const o=n(0),r=n(5),s=n(15),a=n(24);t.AbstractServerSocket=class AbstractServerSocket{constructor(e,t,n){this.logger=e,this.requestHandler=t,this.authorizationProvider=n,this.socketInfo={}}addChannels(e){return i(this,void 0,void 0,(function*(){this.socketInfo.channels=(this.socketInfo.channels||[]).concat(e)}))}removeChannels(e){return i(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 i(this,void 0,void 0,(function*(){yield this.sendToSocket(o.SocketChannels.MESSAGE_CHANNEL,e)}))}disconnect(e){return i(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 i(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 i(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 i(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;return i(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 r.HttpRequest({method:o.SocketMethod.MESSAGE,pathName:"",headers:{authorization:e.authorizationData}});let i;for(const e of this.requestHandler.getMiddleware())if(i=yield e.intercept(n),i)break;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,i;try{yield this.removeChannels(e.channels),n=!0}catch(e){n=!1,i=e}yield this.sendToSocket(o.SocketChannels.CHANNEL_LEAVE_REQUEST,{success:n,channels:e.channels,error:i})}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 i,d=!0;for(const e of n){const t=new s.HttpEndpoint;t.httpMethod=o.SocketMethod.MESSAGE,t.mount=`/${e}`;const n=((0,o.getGlobalStore)().mountedEndpointInfo||[]).find((e=>e.endpoint.getEndpointId()===t.getEndpointId()));if(!n){i=`Channel not found: ${e}`,d=!1;break}const a=new r.HttpRequest({method:o.SocketMethod.MESSAGE,pathName:`/${e}`});try{yield this.authorizationProvider.authorize(this.socketInfo.authInfo,a,n)}catch(t){i=`Not permitted to join: ${e}`,d=!1;break}}if(yield this.sendToSocket(o.SocketChannels.CHANNEL_JOIN_REQUEST,{success:d,channels:e.channels,error:i}),!d)return;yield this.addChannels(n);for(const t of e.channels){const e=new a.ServerSocket(t,this);yield this.requestHandler.handle({method:o.SocketMethod.MESSAGE,rawPath:t,socket:e})}}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 a.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";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var o=Object.getOwnPropertyDescriptor(t,n);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,o)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),o=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||i(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),t.QueryTypes=void 0,o(n(14),t),o(n(5),t),o(n(28),t),o(n(29),t),o(n(30),t),o(n(6),t),o(n(31),t),o(n(7),t),o(n(35),t),o(n(36),t),o(n(37),t),o(n(1),t),o(n(16),t),o(n(2),t),o(n(9),t),o(n(17),t),o(n(38),t),o(n(39),t),o(n(40),t),o(n(41),t),o(n(46),t),o(n(47),t),o(n(21),t),o(n(48),t),o(n(11),t),o(n(10),t),o(n(49),t),o(n(51),t),o(n(13),t),o(n(18),t),o(n(25),t),o(n(4),t),o(n(53),t),o(n(55),t),o(n(58),t),o(n(59),t),o(n(20),t);var r=n(12);Object.defineProperty(t,"QueryTypes",{enumerable:!0,get:function(){return r.QueryTypes}})},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},function(e,t,n){"use strict";var i=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},o=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},r=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))},s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultHttpRequestHandler=void 0;const a=n(0),d=s(n(32)),c=n(33),l=s(n(34)),u=n(6),h=n(5),p=n(2),f=n(1),g=n(15),y=n(16),m=n(7);let v=class DefaultHttpRequestHandler extends f.AbstractHttpRequestHandler{constructor(e,t){super(),this.logger=e,this.authorizationProvider=t,this.injector=(0,a.getServiceProvider)().getInjector(),this.mountPoint="",this.mountedEndpointInfo=[],this.middleware=this.injector.resolveMultiple(y.AbstractHttpMiddleware)}init(){var e,t,n,i;return r(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=(0,a.getObjectMetadata)(e.constructor),n=e.getEndpointMetadata();for(const i of n){const n=new g.HttpEndpoint;n.mount=this.resolverMountPoint(t,[this.mountPoint||"/",i.url]),n.httpMethod=i.httpMethod,n.handler=t=>r(this,void 0,void 0,(function*(){if(n.httpMethod!==a.SocketMethod.MESSAGE){const e=yield this.authorizationProvider.resolvePrincipal(t);t.setAuthInfo(e),i.openAccess||(yield this.authorizationProvider.authorize(e,t,{endpoint:n,endpointMetadata:i}))}const o=Object.values(i.params||{}).map((e=>{switch(e.source){case"body":return t.getBody();case"params":return t.getParams();case"queries":return t.getQuery();case"headers":return t.getHeaders();case"raw":return t}}));return yield e[i.name](...o)})),n.controller=e,n.handlerFunctionName=i.name,o.push({endpointMetadata:i,endpoint:n})}}this.mountedEndpointInfo=[];for(const r of o){const o=this.mountedEndpointInfo.find((e=>e.endpoint.mount===r.endpoint.mount&&e.endpoint.httpMethod===r.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 ${r.endpoint.getEndpointId()} of ${null===(n=r.endpoint.controller)||void 0===n?void 0:n.constructor.name}:${r.endpoint.handlerFunctionName}`):(null===(i=this.logger)||void 0===i||i.debug(`Mouting: ${r.endpoint.getEndpointId()}`),this.mountedEndpointInfo.push(r))}(0,a.getGlobalStore)().mountedEndpointInfo=this.mountedEndpointInfo}))}exit(){}handle(e){return r(this,void 0,void 0,(function*(){const t=e.method,n=(0,d.default)({url:e.rawPath});let i={};const o=this.mountedEndpointInfo.find((e=>{const o=e.endpointMetadata.httpMethod===t&&(0,c.match)(e.endpointMetadata.url,{decode:decodeURIComponent})(n.pathname);return!!o&&(i=o,!0)}));if(!o)throw this.logger.debug(e),a.ErrorBuilder.error(a.Errors.NOT_FOUND,"Handler not found");const r=new h.HttpRequest({method:t,headers:e.headers,pathName:n.pathname||"",hash:n.hash||"",query:l.default.parse(n.search||""),params:i.params,body:e.body,socket:e.socket},o.endpointMetadata);let s;try{if(t!==a.SocketMethod.MESSAGE)for(const e of this.getMiddleware())if(s=yield e.intercept(r),s)break;s||(s=yield o.endpoint.handler&&o.endpoint.handler(r))}catch(e){this.logger.error(e),s=u.ResponseBuilder.json({name:e.name,message:e.message}).status(400).get()}if(!(s&&s instanceof u.HttpResponse))throw a.ErrorBuilder.systemError(`Invalid response value returned ${o.endpoint.httpMethod}:${o.endpoint.mount}, required instance of ${u.HttpResponse.name}, found ${s?s.constructor.name:s}`);return{body:null==s?void 0:s.value,code:(null==s?void 0:s.code)||400,cookies:(null==s?void 0:s.cookies)||{},headers:(null==s?void 0:s.headers)||{}}}))}getMiddleware(){return this.middleware}};v=i([(0,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 i=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},o=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},r=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}},s=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.CrudHttpController=void 0;const a=n(0),d=n(17),c=n(5),l=n(18),u=n(10),h=n(14),p=n(7),f=n(20),g=n(2),y=n(6);class CrudHttpController extends p.AbstractHttpController{constructor(e,t){super(t),this.model=e,this.databaseAdapter=t;const n=(0,a.getObjectMetadata)(e);this.model=(0,a.getModelById)(n.id),this.modelMetadata=(0,a.getObjectMetadata)(this.model)}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=a.DataType.OBJECT,(0,a.setObjectMetadata)(FieldsDto,t),n.objectTypeConstructor=FieldsDto,n}static projectionFieldDto(e){const t={name:"projection"};return t.dataType=a.DataType.ARRAY,t.vectorProps={superSet:e.fields.map((e=>e.name)),allowDuplicated:!1,minLength:1,elementDataType:a.DataType.STRING},t}static getBodyDtoRecordClass(e,t,n){class InstanceDto{}const i={fields:[],strict:!0},o=e.fields.filter((e=>!e.serverValue||e.serverValue&&e.pk&&!t&&!n)),r=e.fields.filter((e=>!!e.hasMany));return i.fields.push(...o.map((e=>Object.assign(Object.assign({},e),{isRequired:null===t?e.isRequired:t}))),...r.map((e=>({description:e.description,name:e.name,dataType:a.DataType.ARRAY,vectorProps:{elementDataType:a.DataType.OBJECT,minLength:0},objectTypeConstructor:CrudHttpController.getBodyDtoRecordClass((0,a.getObjectMetadata)((0,a.getModelById)(e.hasMany.id)),t,!1)})))),(0,a.setObjectMetadata)(InstanceDto,i),InstanceDto}static getRequestQueryFieldFromModel(e){return e.fields.map((e=>{const t={};if(t.name=e.name,t.isRequired=!1,e.pk||e.fk||e.isSymbol)t.dataType=a.DataType.ARRAY,t.vectorProps={elementDataType:e.dataType,allowDuplicated:!1,allowNull:e.allowNull,minLength:1};else if(e.enum)t.dataType=a.DataType.ARRAY,t.vectorProps={superSet:e.enum,allowDuplicated:!1,minLength:1,elementDataType:e.dataType,allowNull:e.allowNull};else switch(e.dataType){case a.DataType.STRING:t.dataType=a.DataType.STRING;break;case a.DataType.NUMBER:t.dataType=a.DataType.OBJECT,t.objectTypeConstructor=a.RangeQueryDto}return t}))}getAuthProvider(){return s(this,void 0,void 0,(function*(){if(void 0===this.authProvider){const e=(0,a.getServiceProvider)().getInjector();this.authProvider=e.resolveOptional(g.AbstractHttpAuthorizationProvider)||null,yield e.initInstances()}return this.authProvider}))}createManyEndpoinMetadata(){const e={};return e.httpMethod=a.HttpMethod.POST,e.url=this.getMountedUrl(),e.name=CrudHttpController.prototype.createMany.name,e.displayName="createMany"+this.model.name,e.bodyValidationDto=CrudHttpController.getCreateManyBodyValidator(this.modelMetadata),e.responseValidationDto=CrudHttpController.getCreateManyResponseValidator(this.modelMetadata),e}getManyEndpointMetadata(){const e={};return e.httpMethod=a.HttpMethod.GET,e.url=this.getMountedUrl(),e.name=CrudHttpController.prototype.getMany.name,e.displayName="getAll"+this.model.name,e.queriesValidationDto=CrudHttpController.getGetManyQueryValidator(this.modelMetadata),e.responseValidationDto=CrudHttpController.getGetManyResponseValidator(this.modelMetadata),e.accessConditions=[(0,d.FilterModelFieldAccessCondition)(this.model,(e=>e.getQuery().projection))],e}updateManyEndpoinMetadata(){const e={};return e.httpMethod=a.HttpMethod.PUT,e.url=this.getMountedUrl(),e.name=CrudHttpController.prototype.updateMany.name,e.displayName="update"+this.model.name,e.queriesValidationDto=CrudHttpController.getUpdateManyQueryValidator(this.modelMetadata),e.bodyValidationDto=CrudHttpController.getUpdateManyBodyValidator(this.modelMetadata),e.responseValidationDto=CrudHttpController.getUpdateManyResponseValidator(this.modelMetadata),e.accessConditions=[(0,d.FilterModelFieldAccessCondition)(this.model,(e=>Object.keys(e.getBody().update)))],e}deleteManyEndpoinMetadata(){const e={};return e.httpMethod=a.HttpMethod.DEL,e.url=this.getMountedUrl(),e.name=CrudHttpController.prototype.deleteMany.name,e.displayName="delete"+this.model.name,e.queriesValidationDto=CrudHttpController.getUpdateManyQueryValidator(this.modelMetadata),e}static getCreateManyBodyValidator(e){const t={fields:[],strict:!0},n={name:"records"};return n.dataType=a.DataType.ARRAY,n.isRequired=!0,n.vectorProps={elementDataType:a.DataType.OBJECT,minLength:0},n.objectTypeConstructor=CrudHttpController.getBodyDtoRecordClass(e,null,!0),t.fields.push(n),t}static getCreateManyResponseValidator(e){const t={fields:[]},n={name:"records"};return n.dataType=a.DataType.OBJECT,n.isRequired=!0,n.vectorProps={elementDataType:a.DataType.OBJECT,minLength:0},n.objectTypeConstructor=CrudHttpController.getBodyDtoRecordClass(e,null,!0),t.fields.push(n),t}static getGetManyResponseValidator(e){const t={fields:[]},n={name:"total"};n.dataType=a.DataType.NUMBER,n.isRequired=!0,t.fields.push(n);const i={name:"records"};return i.dataType=a.DataType.ARRAY,i.isRequired=!0,i.vectorProps={elementDataType:a.DataType.OBJECT,minLength:0},i.objectTypeConstructor=CrudHttpController.getBodyDtoRecordClass(e,!1,!0),t.fields.push(i),t}static getGetManyQueryValidator(e){const t={fields:[CrudHttpController.queryFieldDto(e)]},n={name:"search"};n.dataType=a.DataType.STRING,t.fields.push(n),t.fields.push(CrudHttpController.projectionFieldDto(e));const i={name:"order"};i.dataType=a.DataType.ARRAY,i.vectorProps={elementDataType:a.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=a.DataType.OBJECT,t.enum=["asc","desc"],t}))),(0,a.setObjectMetadata)(SortElementDto,o),i.objectTypeConstructor=SortElementDto,t.fields.push(i);const r={name:"limit"};r.dataType=a.DataType.NUMBER,r.rangeProps={min:1},t.fields.push(r);const s={name:"page"};return s.dataType=a.DataType.NUMBER,s.rangeProps={min:1},t.fields.push(s),t}static getUpdateManyQueryValidator(e){const t={name:"returning"};return t.dataType=a.DataType.BOOLEAN,t.isRequired=!1,{fields:[t,CrudHttpController.queryFieldDto(e)]}}static getUpdateManyBodyValidator(e){const t={fields:[],strict:!0},n={name:"update"};return n.dataType=a.DataType.OBJECT,n.objectTypeConstructor=CrudHttpController.getBodyDtoRecordClass(e,!1,!0),t.fields.push(n),t}static getUpdateManyResponseValidator(e){const t={fields:[],strict:!0},n={name:"modified"};return n.dataType=a.DataType.ARRAY,n.vectorProps={minLength:0,elementDataType:a.DataType.OBJECT},n.objectTypeConstructor=CrudHttpController.getBodyDtoRecordClass(e,!1,!0),t.fields.push(n),t}static createManyBodyValidator(e){class Validator{}return(0,a.setObjectMetadata)(Validator,CrudHttpController.getCreateManyBodyValidator((0,a.getObjectMetadata)(e))),Validator}static getManyQueryValidator(e){class Validator{}return(0,a.setObjectMetadata)(Validator,CrudHttpController.getGetManyQueryValidator((0,a.getObjectMetadata)(e))),Validator}static updateManyQueryValidator(e){class Validator{}return(0,a.setObjectMetadata)(Validator,CrudHttpController.getUpdateManyQueryValidator((0,a.getObjectMetadata)(e))),Validator}static updateManyBodyValidator(e){class Validator{}return(0,a.setObjectMetadata)(Validator,CrudHttpController.getUpdateManyBodyValidator((0,a.getObjectMetadata)(e))),Validator}getEndpointMetadata(){var e,t,n,i;const o=super.getEndpointMetadata(),r=[];(null===(e=this.modelMetadata.ignoreCrud)||void 0===e?void 0:e.includes(a.HttpMethod.GET))?o.splice(o.findIndex((e=>e.name===CrudHttpController.prototype.getMany.name)),1):r.push(this.getManyEndpointMetadata()),(null===(t=this.modelMetadata.ignoreCrud)||void 0===t?void 0:t.includes(a.HttpMethod.POST))?o.splice(o.findIndex((e=>e.name===CrudHttpController.prototype.createMany.name)),1):r.push(this.createManyEndpoinMetadata()),(null===(n=this.modelMetadata.ignoreCrud)||void 0===n?void 0:n.includes(a.HttpMethod.PUT))?o.splice(o.findIndex((e=>e.name===CrudHttpController.prototype.updateMany.name)),1):r.push(this.updateManyEndpoinMetadata()),(null===(i=this.modelMetadata.ignoreCrud)||void 0===i?void 0:i.includes(a.HttpMethod.DEL))?o.splice(o.findIndex((e=>e.name===CrudHttpController.prototype.deleteMany.name)),1):r.push(this.deleteManyEndpoinMetadata());for(const e of r){const t=o.findIndex((t=>t.httpMethod===e.httpMethod&&t.url===e.url||t.name===e.name));t>=0?o[t]=Object.assign(Object.assign(Object.assign({},e),o[t]),{accessConditions:[...e.accessConditions||[],...o[t].accessConditions||[]]}):o.push(e)}return o}createMany(e){return s(this,void 0,void 0,(function*(){const t=yield this.getCurrentTransaction(),n=new f.ModelRepository(this.model),i=yield this.getAuthProvider(),o=i&&(yield i.resolvePrincipal(e)),r=yield n.createMany({principal:o,body:e.getBody(),tx:t});return y.ResponseBuilder.json(r).get()}))}getMany(e){return s(this,void 0,void 0,(function*(){const t=new f.ModelRepository(this.model),n=yield t.getMany({queries:e.getQuery(),queryProvider:this.databaseAdapter});return y.ResponseBuilder.json(n).get()}))}updateMany(e){return s(this,void 0,void 0,(function*(){const t=yield this.getCurrentTransaction(),n=yield this.getAuthProvider(),i=n&&(yield n.resolvePrincipal(e)),o=new f.ModelRepository(this.model),r=yield o.updateMany({principal:i,queries:e.getQuery(),body:e.getBody(),tx:t});return y.ResponseBuilder.json(r).get()}))}deleteMany(e){return s(this,void 0,void 0,(function*(){const t=yield this.getCurrentTransaction(),n=new f.ModelRepository(this.model),i=yield n.deleteMany({queries:e.getQuery(),tx:t});return y.ResponseBuilder.json({modified:i.modified.map((e=>e.id)).map((e=>({id:e})))}).get()}))}}i([(0,l.Transactional)(u.TransactionLink.INHERIT_OR_CREATE),(0,h.AccessCondition)([]),r(0,(0,h.Raw)()),o("design:type",Function),o("design:paramtypes",[c.HttpRequest]),o("design:returntype",Promise)],CrudHttpController.prototype,"createMany",null),i([(0,h.AccessCondition)([]),r(0,(0,h.Raw)()),o("design:type",Function),o("design:paramtypes",[c.HttpRequest]),o("design:returntype",Promise)],CrudHttpController.prototype,"getMany",null),i([(0,l.Transactional)(u.TransactionLink.INHERIT_OR_CREATE),(0,h.AccessCondition)([]),r(0,(0,h.Raw)()),o("design:type",Function),o("design:paramtypes",[c.HttpRequest]),o("design:returntype",Promise)],CrudHttpController.prototype,"updateMany",null),i([(0,l.Transactional)(u.TransactionLink.INHERIT_OR_CREATE),(0,h.AccessCondition)([]),r(0,(0,h.Raw)()),o("design:type",Function),o("design:paramtypes",[c.HttpRequest]),o("design:returntype",Promise)],CrudHttpController.prototype,"deleteMany",null),t.CrudHttpController=CrudHttpController},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},function(e,t,n){"use strict";var i=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},o=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},r=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.OwnedResourceAccessCondition=void 0;const s=n(0),a=n(11),d=n(9);t.OwnedResourceAccessCondition=e=>{let t=class _ extends d.AbstractAccessCondition{constructor(e){super(),this.db=e}resolveConditionValue(t){return r(this,void 0,void 0,(function*(){return e(t,this.db)}))}validate(e){return r(this,void 0,void 0,(function*(){return!!e}))}getConditionMetadata(){return{name:"owned_resource",valueType:s.AccessConditionValueType.BOOLEAN}}};return t=i([(0,s.Register)({mode:"transient"}),o("design:paramtypes",[a.AbstractDatabaseAdapter])],t),t}},function(e,t,n){"use strict";var i,o=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},r=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},s=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.FileLogMedium=void 0;const d=a(n(22)),c=a(n(23)),l=n(0);let u=i=class FileLogMedium{constructor(e){const t=e.separated?i.levels.map((t=>c.default.join(e.destination,t+".log"))):[e.destination];this.destination=t.map((e=>(d.default.existsSync(c.default.dirname(e))||d.default.mkdirSync(c.default.dirname(e),{recursive:!0}),d.default.openSync(e,"a")))),this.separated=!!e.separated}init(){return s(this,void 0,void 0,(function*(){}))}exit(){this.destination.forEach((e=>d.default.closeSync(e)))}write(e,t){const n=this.separated?this.destination[i.levels.indexOf(e)]:0;d.default.appendFileSync(n,t)}};u.levels=Object.values(l.LogLevel),u=i=o([(0,l.Initable)(),r("design:paramtypes",[Object])],u),t.FileLogMedium=u},function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.ClaireServer=void 0;const o=n(0),r=n(8);class ClaireServer extends o.ClaireApp{constructor(){super(),this.injector=(0,o.getServiceProvider)().getInjector(),this.booted=!1,this.logger=this.injector.resolve(o.AbstractLogger)}init(){return i(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(r.ExitCode.SIGTERM_INTERUPTION)))),process.on("SIGINT",(()=>(this.logger.warn("SIGINT interrupt signal"),this.stop(r.ExitCode.SIGTERM_INTERUPTION)))),process.on("uncaughtException",(e=>(this.logger.error("uncaughtException",e.name,e.stack),this.stop(r.ExitCode.UNCAUGHT_EXCEPTION)))),process.on("unhandledRejection",(e=>(this.logger.error("unhandledRejection",e.name,e.stack),this.stop(r.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 i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ExpressWrapper=void 0;const r=n(0),s=o(n(42)),a=o(n(43)),d=o(n(44)),c=o(n(45)),l=n(4),u=n(1);t.ExpressWrapper=class ExpressWrapper{constructor(e,t){this.injector=(0,r.getServiceProvider)().getInjector(),this.server=e,this.config=t,this.logger=this.injector.resolve(r.AbstractLogger),this.socketManager=this.injector.resolveOptional(l.AbstractServerSocketManager),this.httpRequestHandler=this.injector.resolve(u.AbstractHttpRequestHandler)}close(){var e;null===(e=this.httpServer)||void 0===e||e.close()}listen(e){var t,n;return i(this,void 0,void 0,(function*(){yield this.server.init(),yield this.injector.initInstances();const o=(0,s.default)(),r=a.default.createServer(o);return null===(t=this.socketManager)||void 0===t||t.configure(r),o.use((0,d.default)()),o.use(s.default.raw({limit:1024*((null===(n=this.config)||void 0===n?void 0:n.maxBodySizeKB)||4096)})),o.use((0,c.default)()),o.use(((e,t,n)=>{e.files&&(e.body||(e.body={}),Object.keys(e.files).forEach((t=>{e.body[t]=e.files[t]}))),n()})),o.use(s.default.urlencoded({extended:!1})),o.use(s.default.json()),o.all("*",((e,t)=>{(()=>i(this,void 0,void 0,(function*(){var n;const i=!!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(i);return o||(o=yield this.httpRequestHandler.handle(i)),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({name:e.name,message:e.message})}))})),new Promise(((t,n)=>{this.httpServer=r.listen(e,t).on("error",n)}))}))}}},function(e,t){e.exports=require("express")},function(e,t){e.exports=require("http")},function(e,t){e.exports=require("cors")},function(e,t){e.exports=require("express-fileupload")},function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.LambdaWrapper=void 0;const o=n(0),r=n(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=(0,o.getServiceProvider)().getInjector(),this.socketManager=this.injector.resolveOptional(s.AbstractServerSocketManager),this.httpRequestHandler=this.injector.resolve(r.AbstractHttpRequestHandler)}handler(e){var t,n;return i(this,void 0,void 0,(function*(){yield this.server.init(),yield this.injector.initInstances(),null===(t=this.socketManager)||void 0===t||t.configure();const i=this.requestMapper(e);if(!i)return toApiGatewayFormat(400,"Cannot resolve event");if(i.method===o.HttpMethod.OPTIONS)return toApiGatewayFormat(200);try{let e=yield null===(n=this.socketManager)||void 0===n?void 0:n.intercept(i);return e||(e=yield this.httpRequestHandler.handle(i)),toApiGatewayFormat(e.code,e.body)}catch(e){return toApiGatewayFormat(400,{name:e.name,message:e.message})}}))}}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractService=void 0;const o=n(3);t.AbstractService=class AbstractService{constructor(e){this.databaseAdapter=e}getCurrentDatabaseAdapter(){return i(this,void 0,void 0,(function*(){return this.databaseAdapter}))}getCurrentTransaction(){return i(this,void 0,void 0,(function*(){return(0,o.getTransactionFromContext)(this)}))}}},function(e,t,n){"use strict";var i=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},o=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},r=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSqlDatabaseAdapter=void 0;const s=n(0),a=n(12),d=n(19),c=n(11),l=n(50),u=n(13),h=n(3),getModelId=e=>{const t=(0,s.getObjectMetadata)(e);if(!t)throw s.ErrorBuilder.systemError(`Metadata for ${e.name} not found, check @Model decorator`);return t.id},p=["_and","_or"],convertOp=e=>[a.Op.and,a.Op.or,a.Op.eq,a.Op.ne,a.Op.gt,a.Op.lt,a.Op.gte,a.Op.lte,a.Op.regexp,a.Op.like,a.Op.in][["_and","_or","_eq","_neq","_gt","_lt","_gte","_lte","_regex","_sub","_in"].indexOf(e)],safetifyColumn=(e,t)=>{const n=t===u.SqlProvider.MYSQL?"`":'"';return e.split(".").map((e=>`${n}${e}${n}`)).join(".")},getAggregatorColumn=(e,t)=>{const n=safetifyColumn(e.field,t);switch(e.fn){case"count":return`${!0===e.args?`COUNT(DISTINCT(${n}))`:`COUNT(${n})`}${t===u.SqlProvider.POSTGRES?"::int":""}`;case"sum":return`SUM(${n})`;case"avg":return`AVG(${n})`;case"min":return`MIN(${n})`;case"max":return`MAX(${n})`;case"join":return t===u.SqlProvider.POSTGRES?`string_agg(${n}, '${e.args}')`:`GROUP_CONCAT(${n} SEPARATOR '${e.args}')`;case"is":return n;default:throw s.ErrorBuilder.systemError(`Not supported agg function: ${e.fn}`)}};class Joiner{constructor(e){this.adapter=e,this.joinInfo=[],this.columnId=0}join(e,t,n,i){return this.joinInfo.push({rightModel:e,leftField:t,rightField:n,joinMode:i||"inner"}),this}where(e){return this.queryCondition=e,this}groupBy(e){return this.groupByFields=e,this}having(e){return this.havingCondition=e,this}getExecuteCondition(){const e=[],t=this.convertHavingCondition(this.havingCondition||{},e);return{conditions:{where:this.adapter.getQueryObjectFromQueryConditions(this.queryCondition,!0),transaction:this.adapter.transaction,include:this.joinInfo.map((e=>{const t=(0,s.getTableName)(e.rightModel);return{attributes:[],model:this.adapter.modelConnections[t].connection,duplicating:!1,required:"inner"===e.joinMode,on:{[`$${e.leftField}$`]:{[convertOp("_eq")]:a.Sequelize.col(e.rightField)}}}})),group:this.groupByFields,attributes:this.adapter.sqlProvider===u.SqlProvider.POSTGRES?[]:e.map((e=>[a.Sequelize.literal(e.sequelizeColumn),e.columnId])),having:t,raw:!0},collector:e}}countWithCondition(e){var t;return r(this,void 0,void 0,(function*(){e.offset=0,e.limit=this.adapter.sqlProvider===u.SqlProvider.POSTGRES?1:0,e.attributes=[...this.adapter.sqlProvider===u.SqlProvider.MYSQL&&e.attributes||[],[this.adapter.sqlProvider===u.SqlProvider.POSTGRES?a.Sequelize.literal("(COUNT(*) OVER ())::int"):a.Sequelize.literal("COUNT(*)"),"count"]];const n=this.adapter.sqlProvider===u.SqlProvider.POSTGRES?yield this.adapter.getCurrentConnection().findAll(e):yield this.adapter.getCurrentConnection().count(e);return(null===(t=n[0])||void 0===t?void 0:t.count)||0}))}count(){return r(this,void 0,void 0,(function*(){const{conditions:e}=this.getExecuteCondition();return this.countWithCondition(e)}))}rows(e,t){return r(this,void 0,void 0,(function*(){const{conditions:n,collector:i}=this.getExecuteCondition();n.attributes=[...n.attributes||[],...Object.keys(e).map((t=>[a.Sequelize.literal(getAggregatorColumn(e[t],this.adapter.sqlProvider)),t]))],n.limit=null==t?void 0:t.limit,n.offset=(null==t?void 0:t.limit)&&t.limit*((t.page||1)-1);const o=yield this.adapter.getCurrentConnection().findAll(n);return{total:yield this.countWithCondition(Object.assign(Object.assign({},n),{attributes:i.map((e=>[a.Sequelize.literal(e.sequelizeColumn),e.columnId]))})),records:o}}))}convertHavingOperation(e,t){const n=getAggregatorColumn(t[0],this.adapter.sqlProvider);return{columnId:"col__"+this.columnId++,sequelizeColumn:n,sequelizeOps:{[convertOp(e)]:t[1]}}}convertHavingCondition(e,t){if(!e)return{};const n=Object.keys(e);if(!n.length)return{};const i=n.map((n=>{if(p.includes(n))return{[convertOp(n)]:e[n].map((e=>this.convertHavingCondition(e,t)))};{const i=this.convertHavingOperation(n,e[n]);return t.push(i),this.adapter.sqlProvider===u.SqlProvider.POSTGRES?a.Sequelize.where(a.Sequelize.literal(i.sequelizeColumn),i.sequelizeOps):{[i.columnId]:i.sequelizeOps}}}));return i.length>1?{[convertOp("_and")]:i}:i[0]}}class ModelAdapter extends l.AbstractQuery{constructor(e){super(e.model),this.dbConnection=e.dbConnection,this.modelConnections=e.modelConnections,this.transaction=e.transaction,this.sqlProvider=e.sqlProvider,this.logger=null==e?void 0:e.logger}getCurrentConnection(){const e=(0,s.getObjectMetadata)(this.model).id;return this.modelConnections[e].connection}resolveNestedIncludes(e){return e&&e.map((e=>({model:this.modelConnections[e.modelId].connection,where:this.getQueryObjectFromQueryConditions(e.queries)})))}join(e,t,n,i){const o=new Joiner(this);return o.join(e,t,n,i),o}count(e,t,n){return r(this,void 0,void 0,(function*(){const i={where:this.getQueryObjectFromQueryConditions(e),transaction:this.transaction,include:this.resolveNestedIncludes(n)};return(null==t?void 0:t.distinct)&&Object.assign(i,{distinct:!0,col:t.distinct}),yield this.getCurrentConnection().count(i)}))}getById(e,t){return this.getOne({_eq:{id:e}},t)}getByIds(e,t){return this.getRecords({_in:{id:e}},t)}getOne(e,t){return r(this,void 0,void 0,(function*(){const n=yield this.getMany(e,{limit:1});return n.records.length?this.convertToLogicObjects(n.records,null==t?void 0:t.projection)[0]:void 0}))}getRecords(e,t,n){return r(this,void 0,void 0,(function*(){return(yield this.getMany(e,t,n)).records}))}getMany(e,t,n){return r(this,void 0,void 0,(function*(){let i={where:this.getQueryObjectFromQueryConditions(e),transaction:this.transaction,include:this.resolveNestedIncludes(n)};if((null==t?void 0:t.order)&&Object.assign(i,{order:t.order}),(null==t?void 0:t.projection)&&Object.assign(i,{attributes:t.projection}),(null==t?void 0:t.limit)&&(i=Object.assign(i,{limit:t.limit}),t.page&&(i=Object.assign(i,{offset:t.limit*(t.page-1)}))),1!==(null==t?void 0:t.limit)||t.page){if(null==t?void 0:t.limit){const{count:e,rows:n}=yield this.getCurrentConnection().findAndCountAll(i);return{total:e,records:this.convertToLogicObjects(n,null==t?void 0:t.projection)}}{const e=yield this.getCurrentConnection().findAll(i);return{total:0,records:this.convertToLogicObjects(e,null==t?void 0:t.projection)}}}{const e=yield this.getCurrentConnection().findOne(i);return{total:0,records:e?this.convertToLogicObjects([e],t.projection):[]}}}))}createOne(e){return r(this,void 0,void 0,(function*(){return(yield this.createMany([e]))[0]}))}createMany(e){return r(this,void 0,void 0,(function*(){let t=yield this.getCurrentConnection().bulkCreate(this.convertToDataObjects(e),{transaction:this.transaction});return this.convertToLogicObjects(t)}))}updateOne(e){return r(this,void 0,void 0,(function*(){return yield this.getCurrentConnection().update(this.convertToDataObjects([e],!0)[0],{where:this.getQueryObjectFromQueryConditions({_eq:{id:e.id}}),transaction:this.transaction}),e}))}updateMany(e,t,n){return r(this,void 0,void 0,(function*(){if(n){const n=yield this.getRecords(e,{projection:["id"]});if(!n.length)return[];const i=n.map((e=>e.id));return yield this.getCurrentConnection().update(this.convertToDataObjects([t],!0)[0],{where:this.getQueryObjectFromQueryConditions({_in:{id:i}}),transaction:this.transaction}),i}return yield this.getCurrentConnection().update(this.convertToDataObjects([t],!0)[0],{where:this.getQueryObjectFromQueryConditions(e),transaction:this.transaction}),[]}))}deleteOne(e){return r(this,void 0,void 0,(function*(){return yield this.deleteMany({_eq:{id:e.id}}),e}))}deleteMany(e,t){return r(this,void 0,void 0,(function*(){if(t){const t=yield this.getMany(e);if(!t.records.length)return[];const n=t.records.map((e=>e.id));return yield this.getCurrentConnection().destroy({where:this.getQueryObjectFromQueryConditions({_in:{id:n}}),transaction:this.transaction}),t.records}return yield this.getCurrentConnection().destroy({where:this.getQueryObjectFromQueryConditions(e),transaction:this.transaction}),[]}))}rawQuery(...e){return r(this,void 0,void 0,(function*(){const t=e[0],n=e[1]||{};if("string"!=typeof t)throw s.ErrorBuilder.error(s.Errors.QUERY_ERROR,"First argument of raw sql expected to be string");return this.dbConnection.query(t,Object.assign({transaction:this.transaction,raw:!0},n))}))}mapToSequelizeOperator(e,t,n,i,o){const r=o?a.Sequelize.literal(safetifyColumn(n,e)):a.Sequelize.col(n);switch(t){case"_sub":switch(this.sqlProvider){case u.SqlProvider.MYSQL:return a.Sequelize.where(r,{[a.Op.like]:a.Sequelize.literal(`${this.dbConnection.escape(`%${i}%`)} COLLATE utf8mb4_0900_as_cs`)});default:return a.Sequelize.where(r,{[a.Op.like]:`%${i}%`})}case"_isub":switch(this.sqlProvider){case u.SqlProvider.POSTGRES:return a.Sequelize.where(r,{[a.Op.iLike]:`%${i}%`});case u.SqlProvider.MYSQL:return a.Sequelize.where(r,{[a.Op.like]:a.Sequelize.literal(`${this.dbConnection.escape(`%${i}%`)} COLLATE utf8mb4_0900_as_ci`)})}case"_usub":switch(this.sqlProvider){case u.SqlProvider.POSTGRES:return a.Sequelize.where(a.Sequelize.fn("unaccent",r),{[a.Op.like]:a.Sequelize.literal(`unaccent(${this.dbConnection.escape(`%${i}%`)})`)});case u.SqlProvider.MYSQL:return a.Sequelize.where(a.Sequelize.fn("unaccent",r),{[a.Op.like]:a.Sequelize.literal(`unaccent(${this.dbConnection.escape(`%${i}%`)}) COLLATE utf8mb4_0900_as_cs`)})}case"_iusub":switch(this.sqlProvider){case u.SqlProvider.POSTGRES:return a.Sequelize.where(a.Sequelize.fn("unaccent",r),{[a.Op.iLike]:a.Sequelize.literal(`unaccent(${this.dbConnection.escape(`%${i}%`)})`)});case u.SqlProvider.MYSQL:return a.Sequelize.where(r,{[a.Op.like]:a.Sequelize.literal(`${this.dbConnection.escape(`%${i}%`)} COLLATE utf8mb4_0900_ai_ci`)})}case"_in":const e=i.filter((e=>null!==e));return e.length<i.length?a.Sequelize.or(a.Sequelize.where(r,{[a.Op.eq]:null}),...e.length?[a.Sequelize.where(r,{[a.Op.in]:e})]:[]):a.Sequelize.where(r,{[a.Op.in]:i});default:return a.Sequelize.where(r,{[convertOp(t)]:i})}}getQueryObjectFromQueryConditions(e,t){if(!e)return{};const n=Object.keys(e);if(!n.length)return{};const i=n.map((n=>p.includes(n)?{[convertOp(n)]:e[n].map((e=>this.getQueryObjectFromQueryConditions(e)))}:{[convertOp("_and")]:Object.keys(e[n]).map((i=>this.mapToSequelizeOperator(this.sqlProvider,n,i,e[n][i],t)))}));return i.length>1?{[convertOp("_and")]:i}:i[0]}}class TransactionAdapter{constructor(e){this.modelAdapters={},this.transaction=e.transaction,this.dbConnection=e.dbConnection,this.logger=e.logger,this.modelConnections=e.modelConnections,this.sqlProvider=e.sqlProvider,this.transactionState=d.TransactionState.EXECUTING}use(e){const t=getModelId(e);let n=this.modelAdapters[t];return n||(this.modelAdapters,n=new ModelAdapter({model:e,dbConnection:this.dbConnection,modelConnections:this.modelConnections,logger:this.logger,transaction:this.transaction,sqlProvider:this.sqlProvider}),this.modelAdapters[t]=n),n}commit(){return r(this,void 0,void 0,(function*(){return this.transactionState=d.TransactionState.COMMITTED,this.transaction.commit()}))}rollback(){return r(this,void 0,void 0,(function*(){return this.transactionState=d.TransactionState.ROLLED_BACK,this.transaction.rollback()}))}getState(){return this.transactionState}}let f=class DefaultSqlDatabaseAdapter extends c.AbstractDatabaseAdapter{constructor(e,t,n){super(),this.logger=n,this.injector=(0,s.getServiceProvider)().getInjector(),this.modelAdapters={},this.sqlProvider=e,this.dbConnection=new a.Sequelize(`${e}://${t}`,{dialect:this.sqlProvider,logging:e=>this.logger.debug(e),define:{timestamps:!1}})}createTransaction(){return r(this,void 0,void 0,(function*(){let e=yield this.dbConnection.transaction();return new TransactionAdapter({transaction:e,dbConnection:this.dbConnection,logger:this.logger,modelConnections:this.modelConnections,sqlProvider:this.sqlProvider})}))}init(){const e=Object.create(null,{init:{get:()=>super.init}});var t,n,i,o;return r(this,void 0,void 0,(function*(){yield e.init.call(this),yield this.injector.initInstances(),null===(t=this.logger)||void 0===t||t.debug("Connecting to database"),yield this.dbConnection.authenticate(),null===(n=this.logger)||void 0===n||n.debug("Generating in-memory schema");for(const e of this.modelMetadata){const t=this.generateSchemaObject(e);this.modelConnections[e.id].connection=t}for(const e of this.modelMetadata){const t=this.modelConnections[e.id].connection,n=e.fields.filter((e=>e.fk));for(const o of n){const n=null===(i=o.fk)||void 0===i?void 0:i.id;if(!n)throw s.ErrorBuilder.systemError(`FK model id not resolved for ${e.id}:${o.name}`);const r=this.modelConnections[n].connection;t.belongsTo(r,{foreignKey:o.name}),r.hasMany(t,{foreignKey:o.name})}}null===(o=this.logger)||void 0===o||o.debug("Database adapter init succeeded")}))}exit(){var e;return null===(e=this.logger)||void 0===e||e.debug("Closing connection to database"),this.dbConnection.close(),0}use(e){const t=getModelId(e);let n=this.modelAdapters[t];return n||(n=new ModelAdapter({model:e,dbConnection:this.dbConnection,modelConnections:this.modelConnections,logger:this.logger,sqlProvider:this.sqlProvider}),this.modelAdapters[t]=n),n}generateSchemaObject(e){let t={};const n=(0,h.getDirectFields)(e);for(const e of n){switch(t[e.name]={},e.dataType){case s.DataType.NUMBER:e.floating?t[e.name].type=a.DataTypes.FLOAT:e.isBigInt?t[e.name].type=a.DataTypes.BIGINT:t[e.name].type=a.DataTypes.INTEGER;break;case s.DataType.STRING:e.textLength?t[e.name].type=a.DataTypes.STRING(e.textLength):t[e.name].type=a.DataTypes.STRING;break;case s.DataType.BOOLEAN:t[e.name].type=a.DataTypes.BOOLEAN;break;case s.DataType.ARRAY:case s.DataType.OBJECT:t[e.name].type=a.DataTypes.TEXT}e.pk&&(t[e.name].primaryKey=!0,e.pk.isAutoIncrement&&(t[e.name].autoIncrement=!0)),void 0!==e.defaultValue&&(t[e.name].defaultValue=e.defaultValue),t[e.name].allowNull=!e.isRequired}return this.dbConnection.define(e.id,t,{tableName:e.id,freezeTableName:!0,name:{singular:e.id,plural:e.id}})}};f=i([(0,s.Initable)(),(0,s.Injectable)(),o("design:paramtypes",[String,String,s.AbstractLogger])],f),t.DefaultSqlDatabaseAdapter=f},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractQuery=void 0;const i=n(0);t.AbstractQuery=class AbstractQuery{constructor(e){const t=(0,i.getObjectMetadata)(e);this.model=(0,i.getModelById)(t.id)||e,this.metadata=(0,i.getObjectMetadata)(this.model)}convertToLogicObjects(e,t){return e.map((e=>{let n=new this.model;return this.metadata.fields.filter((e=>!t||t.includes(e.name))).forEach((t=>{const i=e[t.name];void 0!==i&&(t.isBigInt?n[t.name]=Number(i):t.vectorProps?n[t.name]=JSON.parse(i):n[t.name]=i)})),n}))}convertToDataObjects(e,t){const n=Date.now();return e.map((e=>{let i=new this.model;for(const o of this.metadata.fields){let r=e[o.name];o.vectorProps?r=JSON.stringify(r):(o.modificationTimestamp||o.creationTimestamp&&!t)&&(r=n),i[o.name]=r}return i}))}}},function(e,t,n){"use strict";var i,o=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},r=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},s=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultSqlDatabaseMigrator=void 0;const d=a(n(23)),c=a(n(22)),l=n(52),u=n(0),h=n(12),p=n(13),f=n(3),g=n(25),uniqueGroupComparator=(e,t)=>!e.groupName&&!t.groupName&&e.fieldNames[0]===t.fieldNames[0]||!!e.groupName&&e.groupName===t.groupName;let y=i=class DefaultSqlDatabaseMigrator extends g.AbstractDatabaseMigrator{constructor(e,t,n,i){super(),this.cliPath=e,this.sqlProvider=t,this.connectionString=n,this.logger=i,this.injector=(0,u.getServiceProvider)().getInjector(),this.cliPath=e,this.databaseURL=`${t}://${n}`,this.modelMetadata=((0,u.getGlobalStore)().models||[]).map((e=>(0,u.getObjectMetadata)(e)))}init(){return s(this,void 0,void 0,(function*(){yield this.injector.initInstances()}))}exit(){}getUniqueConstraintGroups(e){const t=[],n=(0,f.getDirectFields)(e).filter((e=>!!e.unique));for(const e of n)if(e.unique.groupName){let n=t.find((t=>t.groupName===e.unique.groupName));n||(n={groupName:e.unique.groupName,fieldNames:[]},t.push(n)),n.fieldNames.push(e.name)}else t.push({fieldNames:[e.name]});return t}generateFieldPropertiesQuery(e){let t="{";if(e.pk&&(t+="primaryKey:true,",e.pk.isAutoIncrement&&(t+="autoIncrement:true,")),void 0!==e.defaultValue&&(t+=`defaultValue:${JSON.stringify(e.defaultValue)},`),t+=`allowNull:${e.isRequired?"false":"true"},`,void 0!==e.dataType)switch(e.dataType){case u.DataType.STRING:e.textLength?t+=`type:Sequelize.STRING(${e.textLength}),`:t+="type:Sequelize.TEXT,";break;case u.DataType.NUMBER:e.floating?t+="type:Sequelize.FLOAT,":e.isBigInt?t+="type:Sequelize.BIGINT,":t+="type:Sequelize.INTEGER,";break;case u.DataType.BOOLEAN:t+="type:Sequelize.BOOLEAN,";break;case u.DataType.ARRAY:case u.DataType.OBJECT:t+="type:Sequelize.TEXT,"}return t+="}",t}getUniqueConstraintUpDown(e,t){const n=`${e}_${t.groupName||t.fieldNames[0]}_un`;return[`queryInterface.addConstraint("${e}",{fields:${JSON.stringify(t.fieldNames)},type:"unique",name:"${n}","transaction":t})`,`queryInterface.removeConstraint("${e}","${n}",{"transaction":t})`]}getSqlCascadeAction(e){switch(e){case"delete":return"CASCADE";case"restrict":return"RESTRICT";case"nullify":return"SET NULL";default:return"RESTRICT"}}getForeignKeyConstraintUpDown(e,t,n){var i,o;const r=`${t}_${n.name}_fk`;return[`queryInterface.addConstraint("${t}",{fields:["${n.name}"],type:"foreign key",name:"${r}",references:{table:"${e.id}",field:"id"},onDelete:'${this.getSqlCascadeAction(null===(i=n.fk)||void 0===i?void 0:i.cascade)}',onUpdate:'${this.getSqlCascadeAction(null===(o=n.fk)||void 0===o?void 0:o.cascade)}',"transaction":t})`,`queryInterface.removeConstraint("${t}","${r}",{"transaction":t})`]}getAddColumnUpDown(e,t){return[`queryInterface.addColumn('${e}','${t.name}',${this.generateFieldPropertiesQuery(t)},{"transaction":t})`,`queryInterface.removeColumn('${e}','${t.name}',{"transaction":t})`]}generateCreateTableQuery(e){let t={upTableAdd:[],downTableRemove:[],upConstraintAdd:[],downConstraintRemove:[],upTableRemove:[],downTableAdd:[],upConstraintRemove:[],downConstraintAdd:[]},n="",i="";n+="{\n";for(const t of(0,f.getDirectFields)(e)){let e=this.generateFieldPropertiesQuery(t);n+=`${t.name}:${e},\n`}n+="}\n",i+='{charset:"utf8",transaction:t}',t.upTableAdd.push(`queryInterface.createTable("${e.id}",${n},{charset:"utf8",transaction:t})`),t.downTableRemove.push(`queryInterface.dropTable("${e.id}",{"transaction":t})`);const o=this.getUniqueConstraintGroups(e);for(const n of o){const[i,o]=this.getUniqueConstraintUpDown(e.id,n);t.upConstraintAdd.push(i),t.downConstraintRemove.push(o)}for(const n of(0,f.getDirectFields)(e))if(n.fk){let i=this.modelMetadata.find((e=>{var t;return e.id===(null===(t=n.fk)||void 0===t?void 0:t.id)}));const[o,r]=this.getForeignKeyConstraintUpDown(i,e.id,n);t.upConstraintAdd.push(o),t.downConstraintRemove.push(r)}return t}isBooleanDiff(e,t){return!!e&&!t||!!t&&!e}runProcess(e){return s(this,void 0,void 0,(function*(){return new Promise(((t,n)=>{(0,l.exec)(e,{env:process.env},(e=>(e&&n(e),t())))}))}))}rollback(e){return s(this,void 0,void 0,(function*(){let t=d.default.join(e,"scripts");if(!c.default.existsSync)throw u.ErrorBuilder.systemError("Migration directory not found");this.logger.debug("Rolling back last migration"),yield this.runProcess(`${this.cliPath} --url=${this.databaseURL} --migrations-path=${t} db:migrate:undo`),this.logger.debug("Rollback completed")}))}migrate(e){var t,n,o,r,a,l,g,y;return s(this,void 0,void 0,(function*(){let m=d.default.join(e,"metadata.json"),v=d.default.join(e,"scripts");c.default.existsSync(v)||(this.logger.debug("Migration directory not exists, creating empty folder"),c.default.mkdirSync(v,{recursive:!0})),c.default.existsSync(m)||(this.logger.debug("Migration metadata does not exist, creating one"),c.default.writeFileSync(m,JSON.stringify([]))),this.logger.debug("Parsing migration metadata file");let b=JSON.parse(String(c.default.readFileSync(m)));this.logger.debug("Calculating differences...");const C=this.modelMetadata.filter((e=>!b.find((t=>e.id===t.id)))),M=this.modelMetadata.filter((e=>b.find((t=>t.id===e.id)))).map((e=>e.id));let O=[];O.push(...C.map((e=>this.generateCreateTableQuery(e))));for(const e of M){const i=b.find((t=>t.id===e)),s=this.modelMetadata.find((t=>t.id===e));i.id!==s.id&&O.push({upTableAdd:[`queryInterface.query("ALTER TABLE ${i.id} RENAME TO ${s.id}",{"transaction":t})`],downTableRemove:[`queryInterface.query("ALTER TABLE ${s.id} RENAME TO ${i.id}",{"transaction":t})`],upConstraintAdd:[],downConstraintRemove:[],upTableRemove:[],downTableAdd:[],upConstraintRemove:[],downConstraintAdd:[]});let d={upTableAdd:[],downTableRemove:[],upConstraintAdd:[],downConstraintRemove:[],upTableRemove:[],downTableAdd:[],upConstraintRemove:[],downConstraintAdd:[]};const c=(0,f.getDirectFields)(i).filter((e=>!(0,f.getDirectFields)(s).find((t=>e.name===t.name))));for(const e of c){const[t,n]=this.getAddColumnUpDown(s.id,e);if(d.upTableRemove.push(n),d.downTableAdd.push(t),e.fk){let t=this.modelMetadata.find((t=>{var n;return t.id===(null===(n=e.fk)||void 0===n?void 0:n.id)}));const[n,i]=this.getForeignKeyConstraintUpDown(t,s.id,e);d.upConstraintRemove.push(i),d.downConstraintAdd.push(n)}}const u=(0,f.getDirectFields)(s).filter((e=>!(0,f.getDirectFields)(i).find((t=>e.name===t.name))));for(const e of u){const[t,n]=this.getAddColumnUpDown(s.id,e);if(d.upTableAdd.push(t),d.downTableRemove.push(n),e.fk){let t=this.modelMetadata.find((t=>{var n;return t.id===(null===(n=e.fk)||void 0===n?void 0:n.id)}));const[n,i]=this.getForeignKeyConstraintUpDown(t,s.id,e);d.upConstraintAdd.push(n),d.downConstraintRemove.push(i)}}const h=(0,f.getDirectFields)(s).filter((e=>(0,f.getDirectFields)(i).find((t=>e.name===t.name)))).map((e=>e.name));for(const e of h){const c=(0,f.getFieldByName)(i,e),u=(0,f.getFieldByName)(s,e);if((this.isBooleanDiff(c.floating,u.floating)||this.isBooleanDiff(c.isBigInt,u.isBigInt)||this.isBooleanDiff(c.isRequired,u.isRequired)||this.isBooleanDiff(null===(t=c.pk)||void 0===t?void 0:t.isAutoIncrement,null===(n=u.pk)||void 0===n?void 0:n.isAutoIncrement)||c.dataType!==u.dataType||c.textLength!==u.textLength||c.defaultValue!==u.defaultValue)&&(d.upTableAdd.push(`queryInterface.changeColumn("${s.id}","${u.name}",${this.generateFieldPropertiesQuery(u)},{"transaction":t})`),d.downTableRemove.push(`queryInterface.changeColumn("${s.id}","${c.name}",${this.generateFieldPropertiesQuery(c)},{"transaction":t})`)),(null===(o=c.fk)||void 0===o?void 0:o.id)!==(null===(r=u.fk)||void 0===r?void 0:r.id)||(null===(a=c.fk)||void 0===a?void 0:a.cascade)!==(null===(l=u.fk)||void 0===l?void 0:l.cascade)){if(null===(g=c.fk)||void 0===g?void 0:g.id){const e=this.modelMetadata.find((e=>{var t;return e.id===(null===(t=c.fk)||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===(y=u.fk)||void 0===y?void 0:y.id){const e=this.modelMetadata.find((e=>{var t;return e.id===(null===(t=u.fk)||void 0===t?void 0:t.id)})),[t,n]=this.getForeignKeyConstraintUpDown(e,s.id,u);d.upTableAdd.push(t),d.downTableRemove.push(n)}}}const p=this.getUniqueConstraintGroups(i),m=this.getUniqueConstraintGroups(s),v=p.filter((e=>!!m.find((t=>uniqueGroupComparator(e,t))))),C=p.filter((e=>!v.find((t=>uniqueGroupComparator(e,t)))));for(const e of C){const[t,n]=this.getUniqueConstraintUpDown(s.id,e);d.upConstraintRemove.push(n),d.downConstraintAdd.push(t)}const M=m.filter((e=>!v.find((t=>uniqueGroupComparator(e,t)))));for(const e of M){const[t,n]=this.getUniqueConstraintUpDown(s.id,e);d.upConstraintAdd.push(t),d.downConstraintRemove.push(n)}for(const e of v){const t=p.find((t=>uniqueGroupComparator(t,e))),n=m.find((t=>uniqueGroupComparator(t,e)));if(t.fieldNames.length!==n.fieldNames.length||t.fieldNames.some((e=>!n.fieldNames.includes(e)))){const[e,i]=this.getUniqueConstraintUpDown(s.id,t),[o,r]=this.getUniqueConstraintUpDown(s.id,n);d.upConstraintRemove.push(i),d.upConstraintAdd.push(o),d.downConstraintRemove.push(r),d.downConstraintAdd.push(e)}}(d.upTableAdd.length||d.downTableRemove.length||d.upConstraintAdd.length||d.downConstraintRemove.length||d.upConstraintRemove.length||d.downConstraintAdd.length||d.upTableRemove.length||d.downTableAdd.length)&&O.push(d)}if(O.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(v,t),o=i.MIGRATION_TEMPLATE,r=new RegExp(i.COMMENT_BLOCK_REGEX_PATTERN),s=getTransactionalScript(e.up),a=getTransactionalScript(e.down);o=o.replace(r,s),o=o.replace(r,a),this.logger.debug("Writing to file",n),c.default.writeFileSync(n,o)}));throw yield migrationFunction({up:[...O.reduce(((e,t)=>e.concat(t.upConstraintRemove)),[]),...O.reduce(((e,t)=>e.concat(t.upTableRemove)),[]),...O.reduce(((e,t)=>e.concat(t.upTableAdd)),[]),...O.reduce(((e,t)=>e.concat(t.upConstraintAdd)),[])],down:[...O.reduce(((e,t)=>e.concat(t.downConstraintRemove)),[]).reverse(),...O.reduce(((e,t)=>e.concat(t.downTableRemove)),[]).reverse(),...O.reduce(((e,t)=>e.concat(t.downTableAdd)),[]).reverse(),...O.reduce(((e,t)=>e.concat(t.downConstraintAdd)),[]).reverse()]},e),this.logger.debug("Updating metadata file"),c.default.writeFileSync(m,JSON.stringify(this.modelMetadata)),u.ErrorBuilder.systemError(`Migration review needed: ${e}`)}this.logger.debug("No difference, running migration"),this.logger.debug("Create database if not exist");try{yield this.runProcess(`${this.cliPath} --url=${this.databaseURL} db:create`)}catch(e){if(String(e).indexOf("already exists")<0)throw e}if(this.logger.debug("Running migration"),this.sqlProvider===p.SqlProvider.POSTGRES){this.logger.debug("Creating unaccent extension for postgres");const e=new h.Sequelize(this.databaseURL);yield e.query("CREATE EXTENSION IF NOT EXISTS unaccent;")}else if(this.sqlProvider===p.SqlProvider.MYSQL){this.logger.debug("Creating unaccent function for mysql");const e=new h.Sequelize(this.databaseURL,{dialectOptions:{multipleStatements:!0}}),t="ĂÂÀÁẢÃẠẰẮẲẴẶẦẤẨẪẬÔƠÒÓỎÕỌỒỐỔỖỘỜỚỞỠỢÈÉẺẼẸÊỀẾỂỄỆÙÚỦŨỤƯỪỨỬỮỰÌÍỈĨỊỲÝỶỸỴ",n="AAAAAAAAAAAAAAAAAOOOOOOOOOOOOOOOOOEEEEEEEEEEEUUUUUUUUUUUIIIIIYYYYY",i=`SET GLOBAL log_bin_trust_function_creators = 1; \nDROP FUNCTION IF EXISTS unaccent; \nCREATE FUNCTION unaccent( textvalue TEXT ) RETURNS TEXT \nBEGIN \nSET @textvalue = textvalue; \nSET @withaccents = 'ŠšŽžÄÅÆÇËÎÏÑÖØÛÜŸÞäåæçëîïñõöøûüÿþƒ${t}${t.toLowerCase()}'; \nSET @withoutaccents = 'SsZzAAACEIINOOUUYBaaaceiinooouuybf${n}${n.toLowerCase()}'; \nSET @count = LENGTH(@withaccents); \nWHILE @count > 0 DO \nSET @textvalue = REPLACE(@textvalue, SUBSTRING(@withaccents, @count, 1), SUBSTRING(@withoutaccents, @count, 1)); \nSET @count = @count - 1; \nEND WHILE; \nRETURN @textvalue; \nEND; \n`;yield e.query(i,{type:h.QueryTypes.RAW})}yield this.runProcess(`${this.cliPath} --url=${this.databaseURL} --migrations-path=${v} db:migrate`),this.logger.debug("Migration finished")}))}};y.COMMENT_BLOCK_REGEX_PATTERN="/\\*(\\*(?!/)|[^*])*\\*\\/",y.MIGRATION_TEMPLATE="'use strict';\n module.exports = {\n up: async (queryInterface, Sequelize) => {\n /**\n */\n },\n \n down: async (queryInterface, Sequelize) => {\n /**\n */\n }\n };",y=i=o([(0,u.Injectable)(),r("design:paramtypes",[String,String,String,u.AbstractLogger])],y),t.DefaultSqlDatabaseMigrator=y},function(e,t){e.exports=require("child_process")},function(e,t,n){"use strict";var i=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},o=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},r=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))},s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.LocalSocketManager=void 0;const a=n(0),d=s(n(54)),c=n(1),l=n(2),u=n(4),h=n(26);class ExpressSocket extends h.AbstractServerSocket{constructor(e,t,n,i){super(e,t,n),this.logger=e,this.httpRequestHandler=t,this.authorizationProvider=n,this.socket=i;const o=Date.now();this.socketInfo={id:`${o.toString()}-${Math.trunc(1e6*Math.random())}`,isOpen:!0,authorized:!1,createdAt:o}}physicSend(e){return r(this,void 0,void 0,(function*(){this.socket.send(e)}))}setOpen(e){return r(this,void 0,void 0,(function*(){this.socketInfo.isOpen=e}))}physicDisconnect(){return r(this,void 0,void 0,(function*(){this.socket.close()}))}authorize(e){const t=Object.create(null,{authorize:{get:()=>super.authorize}});return r(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:i}=JSON.parse(e.data);n.handleMessage(i,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 r(this,void 0,void 0,(function*(){}))}create(e){return new ExpressSocket(this.logger,this.httpRequestHandler,this.authorizationProvider,e)}getAllSockets(){return r(this,void 0,void 0,(function*(){return this.allSockets}))}add(e){return r(this,void 0,void 0,(function*(){this.allSockets.push(e)}))}removeById(e){return r(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 r(this,void 0,void 0,(function*(){return this.allSockets.find((t=>t.getId()===e))}))}};p=i([(0,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 i=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},o=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},r=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))((function(o,r){function fulfilled(e){try{step(i.next(e))}catch(e){r(e)}}function rejected(e){try{step(i.throw(e))}catch(e){r(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))},s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.AwsSocketManager=void 0;const a=n(0),d=s(n(56)),c=s(n(57)),l=n(1),u=n(4),h=n(26),p=n(2);class ApiGatewaySocket extends h.AbstractServerSocket{constructor(e,t,n,i,o,r,s,a){super(t,n,i),this.socketManager=e,this.socketInfo=Object.assign({},o),this.apiGateway=r,this.redisClient=a,this.socketNamespace=s}physicSend(e){return r(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 r(this,void 0,void 0,(function*(){return new Promise(((e,t)=>this.redisClient.hset(this.socketNamespace,this.socketInfo.id||"",JSON.stringify(this.socketInfo),(n=>n?t(n):e()))))}))}physicDisconnect(){return r(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=>{this.logger.debug("Socket remove error",e)}))}))}setOpen(e){return r(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 r(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 r(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 r(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,i,o,r,s){super(s),this.region=e,this.socketDomainUrl=t,this.redisServerUrl=n,this.socketNamespace=i,this.httpRequestHandler=o,this.authorizationProvider=r,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 r(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:i}=e.body;return yield null==t?void 0:t.handleMessage(n,i),{code:200}}default:return}}))}init(){return r(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("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 r(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 r(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 r(this,void 0,void 0,(function*(){const t=yield new Promise(((t,n)=>this.redisClient.hget(this.socketNamespace,e,((e,i)=>e?n(e):t(i)))));if(t)return this.logger.debug("Serialized aws socket",t),this.create(JSON.parse(t))}))}getAllSockets(){return r(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,i)=>n?t(n):e(Object.keys(i).map((e=>{const t=i[e];return this.logger.debug("parsing serialized sockets",t),this.create(JSON.parse(t))})))))))}))}};f=i([(0,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";Object.defineProperty(t,"__esModule",{value:!0}),t._is=t._join=t._max=t._min=t._avg=t._sum=t._count=void 0;t._count=(e,t)=>({fn:"count",field:e,args:t});t._sum=e=>({fn:"sum",field:e});t._avg=e=>({fn:"avg",field:e});t._min=e=>({fn:"min",field:e});t._max=e=>({fn:"max",field:e});t._join=(e,t)=>({fn:"join",field:e,args:t});t._is=e=>({fn:"is",field:e})},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0})}])}));
|