@resolveio/server-lib 20.1.11 → 20.1.13

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.
@@ -31,7 +31,7 @@ export declare class MethodManager {
31
31
  callMethod(id_methodLatency: string, ws: WebSocket, messageDate: Date, messageId: number, method: string, ...methodData: any[]): void;
32
32
  callMethodInternal(method: any, ...methodData: any[]): Promise<any>;
33
33
  private sendWS;
34
- sendEmail(sendTo: string, subject: string, text?: string, html?: string, attachments?: any[], send_from?: string, reply_to?: string): Promise<unknown>;
34
+ sendEmail(sendTo: string, subject: string, text?: string, html?: string, attachments?: any[], send_from?: string, reply_to?: string, local_override?: boolean): Promise<unknown>;
35
35
  getAWS(): AWS;
36
36
  readFile(fileName: any): Promise<unknown>;
37
37
  readImage(fileName: any): Promise<unknown>;
@@ -1,2 +1,2 @@
1
- "use strict";var __awaiter=this&&this.__awaiter||function(e,n,r,i){return new(r=r||Promise)(function(o,t){function fulfilled(e){try{step(i.next(e))}catch(e){t(e)}}function rejected(e){try{step(i.throw(e))}catch(e){t(e)}}function step(e){var t;e.done?o(e.value):((t=e.value)instanceof r?t:new r(function(e){e(t)})).then(fulfilled,rejected)}step((i=i.apply(e,n||[])).next())})},__generator=this&&this.__generator||function(n,r){var i,s,a,d={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]},l={next:verb(0),throw:verb(1),return:verb(2)};return"function"==typeof Symbol&&(l[Symbol.iterator]=function(){return this}),l;function verb(o){return function(e){var t=[o,e];if(i)throw new TypeError("Generator is already executing.");for(;d=l&&t[l=0]?0:d;)try{if(i=1,s&&(a=2&t[0]?s.return:t[0]?s.throw||((a=s.return)&&a.call(s),0):s.next)&&!(a=a.call(s,t[1])).done)return a;switch(s=0,(t=a?[2&t[0],a.value]:t)[0]){case 0:case 1:a=t;break;case 4:return d.label++,{value:t[1],done:!1};case 5:d.label++,s=t[1],t=[0];continue;case 7:t=d.ops.pop(),d.trys.pop();continue;default:if(!(a=0<(a=d.trys).length&&a[a.length-1])&&(6===t[0]||2===t[0])){d=0;continue}if(3===t[0]&&(!a||t[1]>a[0]&&t[1]<a[3]))d.label=t[1];else if(6===t[0]&&d.label<a[1])d.label=a[1],a=t;else{if(!(a&&d.label<a[2])){a[2]&&d.ops.pop(),d.trys.pop();continue}d.label=a[2],d.ops.push(t)}}t=r.call(n,d)}catch(e){t=[6,e],s=0}finally{i=a=0}if(5&t[0])throw t[1];return{value:t[0]?t[1]:void 0,done:!0}}}},__spreadArray=this&&this.__spreadArray||function(e,t,o){if(o||2===arguments.length)for(var n,r=0,i=t.length;r<i;r++)!n&&r in t||((n=n||Array.prototype.slice.call(t,0,r))[r]=t[r]);return e.concat(n||Array.prototype.slice.call(t))},collections_1=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.MethodManager=exports.AWS=void 0,require("../methods/collections")),logs_1=require("../methods/logs"),counters_1=require("../methods/counters"),pdf_1=require("../methods/pdf"),aws_1=require("../methods/aws"),path=require("path"),fs=require("fs"),nodemailer=require("nodemailer"),sesTransport=require("nodemailer-ses-transport"),accounts_1=require("../methods/accounts"),init_1=require("../fixtures/init"),cron_jobs_1=require("../fixtures/cron-jobs"),cron_jobs_2=require("../methods/cron-jobs"),flags_1=require("../methods/flags"),method_response_collection_1=require("../collections/method-response.collection"),common_1=require("../util/common"),log_collection_1=require("../collections/log.collection"),log_method_latency_collection_1=require("../collections/log-method-latency.collection"),moment=require("moment-timezone"),report_builder_1=require("../methods/report-builder"),support_1=require("../methods/support"),monitor_1=require("../methods/monitor"),email_history_collection_1=require("../collections/email-history.collection"),mongo_manager_1=require("./mongo.manager"),client_s3_1=require("@aws-sdk/client-s3"),AWS=function(){function AWS(e){this._serverConfig=null,this._s3=null,this._s3USEast1=null,this._serverConfig=e}return AWS.prototype.s3=function(){return this._s3||(this._s3=new client_s3_1.S3({credentials:{accessKeyId:process.env.AWS_ACCESS_KEY,secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY},region:process.env.AWS_REGION,apiVersion:"2006-03-01"})),this._s3},AWS.prototype.s3USEast1=function(){return"us-east-1"===process.env.AWS_REGION?this.s3():(this._s3USEast1||(this._s3USEast1=new client_s3_1.S3({credentials:{accessKeyId:process.env.AWS_ACCESS_KEY,secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY},region:"us-east-1",apiVersion:"2006-03-01"})),this._s3USEast1)},AWS}(),MethodManager=(exports.AWS=AWS,function(){function MethodManager(e,t,o,n){var r=this;this._methods={},this._sendQueue=[],this._runningQueue=!1,this._debugCallMethodInternalHits=0,this._debugCallMethodHits=0,this._debugCallMethodCronJobHits=0,this._debugSendQueueHits=0,this._mainServer=e,this.serverConfig=t,this.clientDir=o,this._monitorManagerFunction=n,(0,init_1.loadServerInit)(),(0,cron_jobs_1.loadServerCronJobs)(),(0,accounts_1.loadAccountMethods)(this),(0,aws_1.loadAWSMethods)(this),(0,collections_1.loadCollectionMethods)(this),(0,counters_1.loadCounterMethods)(this),(0,logs_1.loadLogMethods)(this),(0,pdf_1.loadPDFMethods)(this),(0,cron_jobs_2.loadCronJobMethods)(this),(0,flags_1.loadFlagMethods)(this),(0,report_builder_1.loadReportBuilderMethods)(this),(0,support_1.loadSupportMethods)(this),(0,monitor_1.loadMonitorMethods)(this),this._aws=new AWS(t),e.sesMail?this._mailer=nodemailer.createTransport(sesTransport({accessKeyId:process.env.AWS_ACCESS_KEY,secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY,region:process.env.AWS_SES_REGION})):this._mailer=nodemailer.createTransport({host:this.serverConfig.MAIL_HOST,port:this.serverConfig.MAIL_PORT,secure:!1,auth:{user:this.serverConfig.MAIL_USERNAME,pass:this.serverConfig.MAIL_PASSWORD},tls:{ciphers:"SSLv3"}}),setInterval(function(){r._mainServer.getSubscriptionManager().getEnableDebug()&&(console.log(new Date,"Method Manager","Send Queue Length",r._sendQueue.length),console.log(new Date,"Method Manager","Send Queue Hits",r._debugSendQueueHits),console.log(new Date,"Method Manager","Call Method Internal Hits",r._debugCallMethodInternalHits),console.log(new Date,"Method Manager","Call Method Hits",r._debugCallMethodHits),console.log(new Date,"Method Manager","Call Method Cron Hits",r._debugCallMethodCronJobHits)),r._debugCallMethodInternalHits=0,r._debugCallMethodHits=0,r._debugCallMethodCronJobHits=0,r._debugSendQueueHits=0,r._debugSendQueueHits=0},6e4),setInterval(function(){if(!r._runningQueue&&r._sendQueue.length){r._runningQueue=!0;for(var e=r._sendQueue.length-1;0<=e;e--)!function(e){r._debugSendQueueHits+=1;var t,o=r._mainServer.getWS(r._sendQueue[e].id_ws);o&&o.readyState===o.OPEN?o.bufferedAmount<20480&&(t=r._sendQueue.pop(),o.send(JSON.stringify(t.data),function(e){e&&r._mainServer.unsubscribeWS(o)}),"reportBuilderGetResults"!==t.method&&"reportBuilderGetDistinctValue"!==t.method&&"reportBuilderBuildTree"!==t.method&&"generatePDF"!==t.method&&"getWOOfflineData"!==t.method&&"countQuery"!==t.method&&"countWithQuery"!==t.method&&"countCollectionWithQuery"!==t.method&&"find"!==t.method&&"findOne"!==t.method&&"findWithOptions"!==t.method&&"uploadFileAndSave"!==t.method&&"getDrivers"!==t.method&&"processAirdropDistribution"!==t.method&&log_collection_1.Logs.insertOne({_id:(0,mongo_manager_1.objectIdHexString)(),type:"client-response",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify([t.methodData,t.data]))<2e5?JSON.stringify([t.methodData,t.data],null,2):"Too Big",method:t.method,id_user:o.id_user||"",user:o.user||"",messageId:t.data.messageId,route:""}),method_response_collection_1.MethodResponses.create({_id:(0,mongo_manager_1.objectIdHexString)(),__v:0,id_user:o.id_user||"",message_id:t.data.messageId,response:(0,common_1.getBinarySize)(JSON.stringify(t.data))<2e5?t.data:{error:"Too Big"},method:t.method,date:t.date})):r._sendQueue.splice(e,1)}(e);r._runningQueue=!1}},25)}return MethodManager.prototype.getMainServer=function(){return this._mainServer},MethodManager.prototype.methods=function(e){this._methods=Object.assign(this._methods,e)},MethodManager.prototype.callMethodCron=function(t){for(var e,o=this,n=[],r=1;r<arguments.length;r++)n[r-1]=arguments[r];if(this._debugCallMethodCronJobHits+=1,this._methods[t]){if((1<n.length||n[0])&&!this._methods[t].skipValidation){if(!this._methods[t].check)return console.error(new Date,"No Check Function For Method "+t),void this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Check Function For Method "+t);if(!this._methods[t].check._schema)return console.error(new Date,"No Check Schema For Method "+t),void this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Check Function For Method "+t);for(var i={},s=Object.keys(this._methods[t].check._schema).filter(function(e){return!e.includes(".")}),a=0;a<n.length;a++)i[s[a]]=n[a];try{this._methods[t].check.validate(i)}catch(e){if(e)return console.error(new Date,"Error in Method Check ("+t+")",e),void this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"Match Error On Method "+t+"\n\nData Being Checked\n"+JSON.stringify(i,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2))}}var d=this._monitorManagerFunction.startMonitorFunction("Cron Method",t,"","",n);return(e=this._methods[t].function).call.apply(e,__spreadArray([Object.assign({},this,MethodManager.prototype,{id_user:"",user:"",id_ws:""})],n,!1)).then(function(e){return o._monitorManagerFunction.finishMonitorFunction(d),e},function(e){return o._monitorManagerFunction.finishMonitorFunction(d),o.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+o.serverConfig.CLIENT_NAME,"Error Detected During Method "+t+" - (callMethodCron)\n\nData \n"+JSON.stringify(n,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2)),e})}console.log("No Method: "+t),this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Method: "+t)},MethodManager.prototype.callMethod=function(n,r,i,s,a){for(var e,t=this,d=[],o=5;o<arguments.length;o++)d[o-5]=arguments[o];if(this._debugCallMethodHits+=1,this._methods[a]){if((1<d.length||d[0])&&!this._methods[a].skipValidation){if(!this._methods[a].check)return console.error(new Date,"No Check Function For Method "+a),this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Check Function For Method "+a),this.sendWS(r,i,a,d,l={messageId:s,hasError:!0,data:"Internal Error"}),void(n&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:n}));if(!this._methods[a].check._schema)return console.error(new Date,"No Check Schema For Method "+a),this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Check Function For Method "+a),l={messageId:s,hasError:!0,data:"Internal Error"},n&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:n}),void this.sendWS(r,i,a,d,l);for(var l,c={},h=Object.keys(this._methods[a].check._schema).filter(function(e){return!e.includes(".")}),u=0;u<d.length;u++)c[h[u]]=d[u];try{this._methods[a].check.validate(c)}catch(e){if(e)return console.error(new Date,"Error in Method Check ("+a+")",e),"processAirdropDistribution"!==a&&this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"Match Error On Method "+a+"\n\nData Being Checked\n"+JSON.stringify(c,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2)),this.sendWS(r,i,a,d,l={messageId:s,hasError:!0,data:"Internal Error"}),void(n&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:n}))}}var _=this._monitorManagerFunction.startMonitorFunction("Method",a,r.user||"",r.id_socket||"",d);(e=this._methods[a].function).call.apply(e,__spreadArray([Object.assign({},this,MethodManager.prototype,{id_user:r.id_user,user:r.user,id_ws:r.id_socket})],d,!1)).then(function(o){return __awaiter(t,void 0,void 0,function(){var t;return __generator(this,function(e){switch(e.label){case 0:return(this._monitorManagerFunction.finishMonitorFunction(_),t={messageId:s,hasError:!1,data:o},this.sendWS(r,i,a,d,t),n)?[4,log_method_latency_collection_1.LogMethodLatencies.findById(n)]:[3,2];case 1:(t=e.sent())&&log_method_latency_collection_1.LogMethodLatencies.updateOne({_id:n},{$set:{date_end:new Date,latency_ms:moment().diff(moment(t.date_start),"milliseconds",!0)}}),e.label=2;case 2:return[2]}})})},function(e){t._monitorManagerFunction.finishMonitorFunction(_),t.sendWS(r,i,a,d,{messageId:s,hasError:!0,data:e}),n&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:n}),"processAirdropDistribution"!==a&&t.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+t.serverConfig.CLIENT_NAME,"Error Detected During Method "+a+" - (callMethod)\n\nData \n"+JSON.stringify(d,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2))})}else console.log("No Method: "+a),this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Method: "+a),this.sendWS(r,i,a,d,l={messageId:s,hasError:!0,data:"Internal Error"}),n&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:n})},MethodManager.prototype.callMethodInternal=function(t){for(var o=this,n=[],e=1;e<arguments.length;e++)n[e-1]=arguments[e];if(this._debugCallMethodInternalHits+=1,!this._methods[t])return console.log("No Method: "+t),null;if((1<n.length||n[0]&&"function"!=typeof n[0])&&!this._methods[t].skipValidation){if(!this._methods[t].check)return console.error(new Date,"No Check Function For Method "+t),null;if(!this._methods[t].check._schema)return console.error(new Date,"No Check Schema For Method "+t),null}"insertSubscriptionLog"!==t&&"getDataURIfromURL"!==t&&"processAirdropDistribution"!==t&&log_collection_1.Logs.insertOne({_id:(0,mongo_manager_1.objectIdHexString)(),type:"callMethodInternal",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify([n]))<2e5?JSON.stringify([n],null,2):"Too Big",method:t,id_user:this.id_user||"",user:this.user||"",messageId:0,route:""});var r="function"==typeof n[n.length-1]?n.slice(0,-1):n,i=this._monitorManagerFunction.startMonitorFunction("Internal Method",t,this.user||"","",r),s=(s=this._methods[t].function).call.apply(s,__spreadArray([Object.assign({},this,MethodManager.prototype)],r,!1)).then(function(e){return o._monitorManagerFunction.finishMonitorFunction(i),e},function(e){return o._monitorManagerFunction.finishMonitorFunction(i),o.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+o.serverConfig.CLIENT_NAME,"Error Detected During Method "+t+" - (callMethodInternal)\n\nData \n"+JSON.stringify(n,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2)),e});return n[n.length-1]&&"function"==typeof n[n.length-1]&&s.then(function(e){return n[n.length-1](null,e)},function(e){return n[n.length-1](e,null)}),s},MethodManager.prototype.sendWS=function(e,t,o,n,r){this._sendQueue.splice(0,0,{id_ws:e.id_socket,method:o,methodData:n,data:r,date:t})},MethodManager.prototype.sendEmail=function(n,r,i,s,a,d,l){var o=this;return new Promise(function(t,e){return __awaiter(o,void 0,void 0,function(){var o=this;return __generator(this,function(e){return(n=!this.serverConfig.ROOT_URL.match(new RegExp(/https\:\/\/dev\./))&&!this.serverConfig.ROOT_URL.match(new RegExp(/https\:\/\/www\.dev\./))&&"http://localhost:4200"!==this.serverConfig.ROOT_URL||n.match(new RegExp(/\@resolveio\.com/))?n:"dev@resolveio.com")&&("http://localhost:4200"!==this.serverConfig.ROOT_URL?this._mailer.sendMail({replyTo:null!=l?l:this.serverConfig.MAIL_REPLY_TO||void 0,from:d||this.serverConfig.MAIL_FROM,to:n,subject:(this.serverConfig.ROOT_URL.match(new RegExp(/https\:\/\/dev\./))||this.serverConfig.ROOT_URL.match(new RegExp(/https\:\/\/www\.dev\./))?"(DEV SERVER) - ":"")+r,text:i,html:s,attachments:a},function(e,t){e?(console.log(e),email_history_collection_1.EmailHistories.create({_id:(0,mongo_manager_1.objectIdHexString)(),__v:0,date:new Date,id_user:o.id_user||"",user:o.user||"",email:n,success:!1,verified:!1})):email_history_collection_1.EmailHistories.create({_id:(0,mongo_manager_1.objectIdHexString)(),__v:0,date:new Date,id_user:o.id_user||"",user:o.user||"",email:n,success:!0,verified:!1})}):console.log("Send email",n,r,i,s,a,d),t(!0)),[2]})})})},MethodManager.prototype.getAWS=function(){return this._aws},MethodManager.prototype.readFile=function(e){var t=this;return new Promise(function(o,n){fs.existsSync(path.join(__dirname,"../private/"+e))?fs.readFile(path.join(__dirname,"../private/"+e),"utf-8",function(e,t){e?n(e):o(t)}):fs.existsSync(path.join(t.clientDir,"./private/"+e))&&fs.readFile(path.join(t.clientDir,"./private/"+e),"utf-8",function(e,t){e?n(e):o(t)})})},MethodManager.prototype.readImage=function(e){var t=this;return new Promise(function(o,n){fs.existsSync(path.join(__dirname,"../private/"+e))?fs.readFile(path.join(__dirname,"../private/"+e),"base64",function(e,t){e?n(e):o(t)}):fs.existsSync(path.join(t.clientDir,"./private/"+e))&&fs.readFile(path.join(t.clientDir,"./private/"+e),"base64",function(e,t){e?n(e):o(t)})})},MethodManager}());exports.MethodManager=MethodManager;
1
+ "use strict";var __awaiter=this&&this.__awaiter||function(e,n,r,i){return new(r=r||Promise)(function(o,t){function fulfilled(e){try{step(i.next(e))}catch(e){t(e)}}function rejected(e){try{step(i.throw(e))}catch(e){t(e)}}function step(e){var t;e.done?o(e.value):((t=e.value)instanceof r?t:new r(function(e){e(t)})).then(fulfilled,rejected)}step((i=i.apply(e,n||[])).next())})},__generator=this&&this.__generator||function(n,r){var i,s,a,d={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]},l={next:verb(0),throw:verb(1),return:verb(2)};return"function"==typeof Symbol&&(l[Symbol.iterator]=function(){return this}),l;function verb(o){return function(e){var t=[o,e];if(i)throw new TypeError("Generator is already executing.");for(;d=l&&t[l=0]?0:d;)try{if(i=1,s&&(a=2&t[0]?s.return:t[0]?s.throw||((a=s.return)&&a.call(s),0):s.next)&&!(a=a.call(s,t[1])).done)return a;switch(s=0,(t=a?[2&t[0],a.value]:t)[0]){case 0:case 1:a=t;break;case 4:return d.label++,{value:t[1],done:!1};case 5:d.label++,s=t[1],t=[0];continue;case 7:t=d.ops.pop(),d.trys.pop();continue;default:if(!(a=0<(a=d.trys).length&&a[a.length-1])&&(6===t[0]||2===t[0])){d=0;continue}if(3===t[0]&&(!a||t[1]>a[0]&&t[1]<a[3]))d.label=t[1];else if(6===t[0]&&d.label<a[1])d.label=a[1],a=t;else{if(!(a&&d.label<a[2])){a[2]&&d.ops.pop(),d.trys.pop();continue}d.label=a[2],d.ops.push(t)}}t=r.call(n,d)}catch(e){t=[6,e],s=0}finally{i=a=0}if(5&t[0])throw t[1];return{value:t[0]?t[1]:void 0,done:!0}}}},__spreadArray=this&&this.__spreadArray||function(e,t,o){if(o||2===arguments.length)for(var n,r=0,i=t.length;r<i;r++)!n&&r in t||((n=n||Array.prototype.slice.call(t,0,r))[r]=t[r]);return e.concat(n||Array.prototype.slice.call(t))},collections_1=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.MethodManager=exports.AWS=void 0,require("../methods/collections")),logs_1=require("../methods/logs"),counters_1=require("../methods/counters"),pdf_1=require("../methods/pdf"),aws_1=require("../methods/aws"),path=require("path"),fs=require("fs"),nodemailer=require("nodemailer"),sesTransport=require("nodemailer-ses-transport"),accounts_1=require("../methods/accounts"),init_1=require("../fixtures/init"),cron_jobs_1=require("../fixtures/cron-jobs"),cron_jobs_2=require("../methods/cron-jobs"),flags_1=require("../methods/flags"),method_response_collection_1=require("../collections/method-response.collection"),common_1=require("../util/common"),log_collection_1=require("../collections/log.collection"),log_method_latency_collection_1=require("../collections/log-method-latency.collection"),moment=require("moment-timezone"),report_builder_1=require("../methods/report-builder"),support_1=require("../methods/support"),monitor_1=require("../methods/monitor"),email_history_collection_1=require("../collections/email-history.collection"),mongo_manager_1=require("./mongo.manager"),client_s3_1=require("@aws-sdk/client-s3"),AWS=function(){function AWS(e){this._serverConfig=null,this._s3=null,this._s3USEast1=null,this._serverConfig=e}return AWS.prototype.s3=function(){return this._s3||(this._s3=new client_s3_1.S3({credentials:{accessKeyId:process.env.AWS_ACCESS_KEY,secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY},region:process.env.AWS_REGION,apiVersion:"2006-03-01"})),this._s3},AWS.prototype.s3USEast1=function(){return"us-east-1"===process.env.AWS_REGION?this.s3():(this._s3USEast1||(this._s3USEast1=new client_s3_1.S3({credentials:{accessKeyId:process.env.AWS_ACCESS_KEY,secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY},region:"us-east-1",apiVersion:"2006-03-01"})),this._s3USEast1)},AWS}(),MethodManager=(exports.AWS=AWS,function(){function MethodManager(e,t,o,n){var r=this;this._methods={},this._sendQueue=[],this._runningQueue=!1,this._debugCallMethodInternalHits=0,this._debugCallMethodHits=0,this._debugCallMethodCronJobHits=0,this._debugSendQueueHits=0,this._mainServer=e,this.serverConfig=t,this.clientDir=o,this._monitorManagerFunction=n,(0,init_1.loadServerInit)(),(0,cron_jobs_1.loadServerCronJobs)(),(0,accounts_1.loadAccountMethods)(this),(0,aws_1.loadAWSMethods)(this),(0,collections_1.loadCollectionMethods)(this),(0,counters_1.loadCounterMethods)(this),(0,logs_1.loadLogMethods)(this),(0,pdf_1.loadPDFMethods)(this),(0,cron_jobs_2.loadCronJobMethods)(this),(0,flags_1.loadFlagMethods)(this),(0,report_builder_1.loadReportBuilderMethods)(this),(0,support_1.loadSupportMethods)(this),(0,monitor_1.loadMonitorMethods)(this),this._aws=new AWS(t),e.sesMail?this._mailer=nodemailer.createTransport(sesTransport({accessKeyId:process.env.AWS_ACCESS_KEY,secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY,region:process.env.AWS_SES_REGION})):this._mailer=nodemailer.createTransport({host:this.serverConfig.MAIL_HOST,port:this.serverConfig.MAIL_PORT,secure:!1,auth:{user:this.serverConfig.MAIL_USERNAME,pass:this.serverConfig.MAIL_PASSWORD},tls:{ciphers:"SSLv3"}}),setInterval(function(){r._mainServer.getSubscriptionManager().getEnableDebug()&&(console.log(new Date,"Method Manager","Send Queue Length",r._sendQueue.length),console.log(new Date,"Method Manager","Send Queue Hits",r._debugSendQueueHits),console.log(new Date,"Method Manager","Call Method Internal Hits",r._debugCallMethodInternalHits),console.log(new Date,"Method Manager","Call Method Hits",r._debugCallMethodHits),console.log(new Date,"Method Manager","Call Method Cron Hits",r._debugCallMethodCronJobHits)),r._debugCallMethodInternalHits=0,r._debugCallMethodHits=0,r._debugCallMethodCronJobHits=0,r._debugSendQueueHits=0,r._debugSendQueueHits=0},6e4),setInterval(function(){if(!r._runningQueue&&r._sendQueue.length){r._runningQueue=!0;for(var e=r._sendQueue.length-1;0<=e;e--)!function(e){r._debugSendQueueHits+=1;var t,o=r._mainServer.getWS(r._sendQueue[e].id_ws);o&&o.readyState===o.OPEN?o.bufferedAmount<20480&&(t=r._sendQueue.pop(),o.send(JSON.stringify(t.data),function(e){e&&r._mainServer.unsubscribeWS(o)}),"reportBuilderGetResults"!==t.method&&"reportBuilderGetDistinctValue"!==t.method&&"reportBuilderBuildTree"!==t.method&&"generatePDF"!==t.method&&"getWOOfflineData"!==t.method&&"countQuery"!==t.method&&"countWithQuery"!==t.method&&"countCollectionWithQuery"!==t.method&&"find"!==t.method&&"findOne"!==t.method&&"findWithOptions"!==t.method&&"uploadFileAndSave"!==t.method&&"getDrivers"!==t.method&&"processAirdropDistribution"!==t.method&&log_collection_1.Logs.insertOne({_id:(0,mongo_manager_1.objectIdHexString)(),type:"client-response",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify([t.methodData,t.data]))<2e5?JSON.stringify([t.methodData,t.data],null,2):"Too Big",method:t.method,id_user:o.id_user||"",user:o.user||"",messageId:t.data.messageId,route:""}),method_response_collection_1.MethodResponses.create({_id:(0,mongo_manager_1.objectIdHexString)(),__v:0,id_user:o.id_user||"",message_id:t.data.messageId,response:(0,common_1.getBinarySize)(JSON.stringify(t.data))<2e5?t.data:{error:"Too Big"},method:t.method,date:t.date})):r._sendQueue.splice(e,1)}(e);r._runningQueue=!1}},25)}return MethodManager.prototype.getMainServer=function(){return this._mainServer},MethodManager.prototype.methods=function(e){this._methods=Object.assign(this._methods,e)},MethodManager.prototype.callMethodCron=function(t){for(var e,o=this,n=[],r=1;r<arguments.length;r++)n[r-1]=arguments[r];if(this._debugCallMethodCronJobHits+=1,this._methods[t]){if((1<n.length||n[0])&&!this._methods[t].skipValidation){if(!this._methods[t].check)return console.error(new Date,"No Check Function For Method "+t),void this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Check Function For Method "+t);if(!this._methods[t].check._schema)return console.error(new Date,"No Check Schema For Method "+t),void this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Check Function For Method "+t);for(var i={},s=Object.keys(this._methods[t].check._schema).filter(function(e){return!e.includes(".")}),a=0;a<n.length;a++)i[s[a]]=n[a];try{this._methods[t].check.validate(i)}catch(e){if(e)return console.error(new Date,"Error in Method Check ("+t+")",e),void this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"Match Error On Method "+t+"\n\nData Being Checked\n"+JSON.stringify(i,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2))}}var d=this._monitorManagerFunction.startMonitorFunction("Cron Method",t,"","",n);return(e=this._methods[t].function).call.apply(e,__spreadArray([Object.assign({},this,MethodManager.prototype,{id_user:"",user:"",id_ws:""})],n,!1)).then(function(e){return o._monitorManagerFunction.finishMonitorFunction(d),e},function(e){return o._monitorManagerFunction.finishMonitorFunction(d),o.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+o.serverConfig.CLIENT_NAME,"Error Detected During Method "+t+" - (callMethodCron)\n\nData \n"+JSON.stringify(n,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2)),e})}console.log("No Method: "+t),this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Method: "+t)},MethodManager.prototype.callMethod=function(n,r,i,s,a){for(var e,t=this,d=[],o=5;o<arguments.length;o++)d[o-5]=arguments[o];if(this._debugCallMethodHits+=1,this._methods[a]){if((1<d.length||d[0])&&!this._methods[a].skipValidation){if(!this._methods[a].check)return console.error(new Date,"No Check Function For Method "+a),this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Check Function For Method "+a),this.sendWS(r,i,a,d,l={messageId:s,hasError:!0,data:"Internal Error"}),void(n&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:n}));if(!this._methods[a].check._schema)return console.error(new Date,"No Check Schema For Method "+a),this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Check Function For Method "+a),l={messageId:s,hasError:!0,data:"Internal Error"},n&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:n}),void this.sendWS(r,i,a,d,l);for(var l,c={},h=Object.keys(this._methods[a].check._schema).filter(function(e){return!e.includes(".")}),u=0;u<d.length;u++)c[h[u]]=d[u];try{this._methods[a].check.validate(c)}catch(e){if(e)return console.error(new Date,"Error in Method Check ("+a+")",e),"processAirdropDistribution"!==a&&this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"Match Error On Method "+a+"\n\nData Being Checked\n"+JSON.stringify(c,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2)),this.sendWS(r,i,a,d,l={messageId:s,hasError:!0,data:"Internal Error"}),void(n&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:n}))}}var _=this._monitorManagerFunction.startMonitorFunction("Method",a,r.user||"",r.id_socket||"",d);(e=this._methods[a].function).call.apply(e,__spreadArray([Object.assign({},this,MethodManager.prototype,{id_user:r.id_user,user:r.user,id_ws:r.id_socket})],d,!1)).then(function(o){return __awaiter(t,void 0,void 0,function(){var t;return __generator(this,function(e){switch(e.label){case 0:return(this._monitorManagerFunction.finishMonitorFunction(_),t={messageId:s,hasError:!1,data:o},this.sendWS(r,i,a,d,t),n)?[4,log_method_latency_collection_1.LogMethodLatencies.findById(n)]:[3,2];case 1:(t=e.sent())&&log_method_latency_collection_1.LogMethodLatencies.updateOne({_id:n},{$set:{date_end:new Date,latency_ms:moment().diff(moment(t.date_start),"milliseconds",!0)}}),e.label=2;case 2:return[2]}})})},function(e){t._monitorManagerFunction.finishMonitorFunction(_),t.sendWS(r,i,a,d,{messageId:s,hasError:!0,data:e}),n&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:n}),"processAirdropDistribution"!==a&&t.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+t.serverConfig.CLIENT_NAME,"Error Detected During Method "+a+" - (callMethod)\n\nData \n"+JSON.stringify(d,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2))})}else console.log("No Method: "+a),this.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+this.serverConfig.CLIENT_NAME,"No Method: "+a),this.sendWS(r,i,a,d,l={messageId:s,hasError:!0,data:"Internal Error"}),n&&log_method_latency_collection_1.LogMethodLatencies.deleteOne({_id:n})},MethodManager.prototype.callMethodInternal=function(t){for(var o=this,n=[],e=1;e<arguments.length;e++)n[e-1]=arguments[e];if(this._debugCallMethodInternalHits+=1,!this._methods[t])return console.log("No Method: "+t),null;if((1<n.length||n[0]&&"function"!=typeof n[0])&&!this._methods[t].skipValidation){if(!this._methods[t].check)return console.error(new Date,"No Check Function For Method "+t),null;if(!this._methods[t].check._schema)return console.error(new Date,"No Check Schema For Method "+t),null}"insertSubscriptionLog"!==t&&"getDataURIfromURL"!==t&&"processAirdropDistribution"!==t&&log_collection_1.Logs.insertOne({_id:(0,mongo_manager_1.objectIdHexString)(),type:"callMethodInternal",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify([n]))<2e5?JSON.stringify([n],null,2):"Too Big",method:t,id_user:this.id_user||"",user:this.user||"",messageId:0,route:""});var r="function"==typeof n[n.length-1]?n.slice(0,-1):n,i=this._monitorManagerFunction.startMonitorFunction("Internal Method",t,this.user||"","",r),s=(s=this._methods[t].function).call.apply(s,__spreadArray([Object.assign({},this,MethodManager.prototype)],r,!1)).then(function(e){return o._monitorManagerFunction.finishMonitorFunction(i),e},function(e){return o._monitorManagerFunction.finishMonitorFunction(i),o.sendEmail("dev@resolveio.com","SERVER - Error Detected - "+o.serverConfig.CLIENT_NAME,"Error Detected During Method "+t+" - (callMethodInternal)\n\nData \n"+JSON.stringify(n,null,2)+"\n\nErrors\n"+JSON.stringify(e,null,2)),e});return n[n.length-1]&&"function"==typeof n[n.length-1]&&s.then(function(e){return n[n.length-1](null,e)},function(e){return n[n.length-1](e,null)}),s},MethodManager.prototype.sendWS=function(e,t,o,n,r){this._sendQueue.splice(0,0,{id_ws:e.id_socket,method:o,methodData:n,data:r,date:t})},MethodManager.prototype.sendEmail=function(n,r,i,s,a,d,l,c){var o=this;return void 0===c&&(c=!1),new Promise(function(t,e){return __awaiter(o,void 0,void 0,function(){var o=this;return __generator(this,function(e){return(n=!this.serverConfig.ROOT_URL.match(new RegExp(/https\:\/\/dev\./))&&!this.serverConfig.ROOT_URL.match(new RegExp(/https\:\/\/www\.dev\./))&&"http://localhost:4200"!==this.serverConfig.ROOT_URL||n.match(new RegExp(/\@resolveio\.com/))?n:"dev@resolveio.com")&&("http://localhost:4200"!==this.serverConfig.ROOT_URL||c?this._mailer.sendMail({replyTo:null!=l?l:this.serverConfig.MAIL_REPLY_TO||void 0,from:d||this.serverConfig.MAIL_FROM,to:n,subject:(this.serverConfig.ROOT_URL.match(new RegExp(/https\:\/\/dev\./))||this.serverConfig.ROOT_URL.match(new RegExp(/https\:\/\/www\.dev\./))?"(DEV SERVER) - ":"")+r,text:i,html:s,attachments:a},function(e,t){e?(console.log(e),email_history_collection_1.EmailHistories.create({_id:(0,mongo_manager_1.objectIdHexString)(),__v:0,date:new Date,id_user:o.id_user||"",user:o.user||"",email:n,success:!1,verified:!1})):email_history_collection_1.EmailHistories.create({_id:(0,mongo_manager_1.objectIdHexString)(),__v:0,date:new Date,id_user:o.id_user||"",user:o.user||"",email:n,success:!0,verified:!1})}):console.log("Send email",n,r,i,s,a,d),t(!0)),[2]})})})},MethodManager.prototype.getAWS=function(){return this._aws},MethodManager.prototype.readFile=function(e){var t=this;return new Promise(function(o,n){fs.existsSync(path.join(__dirname,"../private/"+e))?fs.readFile(path.join(__dirname,"../private/"+e),"utf-8",function(e,t){e?n(e):o(t)}):fs.existsSync(path.join(t.clientDir,"./private/"+e))&&fs.readFile(path.join(t.clientDir,"./private/"+e),"utf-8",function(e,t){e?n(e):o(t)})})},MethodManager.prototype.readImage=function(e){var t=this;return new Promise(function(o,n){fs.existsSync(path.join(__dirname,"../private/"+e))?fs.readFile(path.join(__dirname,"../private/"+e),"base64",function(e,t){e?n(e):o(t)}):fs.existsSync(path.join(t.clientDir,"./private/"+e))&&fs.readFile(path.join(t.clientDir,"./private/"+e),"base64",function(e,t){e?n(e):o(t)})})},MethodManager}());exports.MethodManager=MethodManager;
2
2
  //# sourceMappingURL=method.manager.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/managers/method.manager.ts"],"names":["collections_1","require","logs_1","counters_1","pdf_1","aws_1","path","fs","nodemailer","sesTransport","accounts_1","init_1","cron_jobs_1","cron_jobs_2","flags_1","method_response_collection_1","common_1","log_collection_1","log_method_latency_collection_1","moment","report_builder_1","support_1","monitor_1","email_history_collection_1","mongo_manager_1","client_s3_1","AWS","serverConfig","this","_serverConfig","_s3","_s3USEast1","prototype","s3","S3","credentials","accessKeyId","process","env","AWS_ACCESS_KEY","secretAccessKey","AWS_SECRET_ACCESS_KEY","region","AWS_REGION","apiVersion","s3USEast1","MethodManager","exports","mainServer","clientDir","monitorManagerFunction","_this","_methods","_sendQueue","_runningQueue","_debugCallMethodInternalHits","_debugCallMethodHits","_debugCallMethodCronJobHits","_debugSendQueueHits","_mainServer","_monitorManagerFunction","loadServerInit","loadServerCronJobs","loadAccountMethods","loadAWSMethods","loadCollectionMethods","loadCounterMethods","loadLogMethods","loadPDFMethods","loadCronJobMethods","loadFlagMethods","loadReportBuilderMethods","loadSupportMethods","loadMonitorMethods","_aws","sesMail","_mailer","createTransport","AWS_SES_REGION","host","port","secure","auth","user","pass","tls","ciphers","setInterval","getSubscriptionManager","getEnableDebug","console","log","Date","length","i","sendItem","ws","getWS","id_ws","readyState","OPEN","bufferedAmount","pop","send","JSON","stringify","data","error","unsubscribeWS","method","Logs","insertOne","_id","objectIdHexString","type","collection","id_document","payload","getBinarySize","methodData","id_user","messageId","route","MethodResponses","create","__v","message_id","response","date","splice","getMainServer","methods","Object","assign","callMethodCron","_i","arguments","skipValidation","check","sendEmail","_schema","valObj","rootKeys","keys","filter","a","includes","validate","errors","monitor","startMonitorFunction","_a","function","call","apply","__spreadArray","then","res","finishMonitorFunction","methodErrs","callMethod","id_methodLatency","messageDate","sendWS","serverRes","hasError","LogMethodLatencies","deleteOne","__awaiter","findById","latency","sent","updateOne","$set","date_end","latency_ms","diff","date_start","err","callMethodInternal","functionMethodData","slice","promise","sendTo","subject","text","html","attachments","send_from","reply_to","Promise","resolve","reject","match","RegExp","sendMail","replyTo","undefined","from","MAIL_FROM","to","info","EmailHistories","email","success","verified","getAWS","readFile","fileName","existsSync","join","__dirname","readImage"],"mappings":"wqDACAA,e,gGAAAC,QAAA,wBAAA,GAEAC,OAAAD,QAAA,iBAAA,EACAE,WAAAF,QAAA,qBAAA,EACAG,MAAAH,QAAA,gBAAA,EACAI,MAAAJ,QAAA,gBAAA,EACAK,KAAAL,QAAA,MAAA,EACAM,GAAAN,QAAA,IAAA,EACAO,WAAAP,QAAA,YAAA,EACAQ,aAAAR,QAAA,0BAAA,EACAS,WAAAT,QAAA,qBAAA,EACAU,OAAAV,QAAA,kBAAA,EACAW,YAAAX,QAAA,uBAAA,EACAY,YAAAZ,QAAA,sBAAA,EACAa,QAAAb,QAAA,kBAAA,EACAc,6BAAAd,QAAA,2CAAA,EACAe,SAAAf,QAAA,gBAAA,EACAgB,iBAAAhB,QAAA,+BAAA,EAEAiB,gCAAAjB,QAAA,8CAAA,EACAkB,OAAAlB,QAAA,iBAAA,EACAmB,iBAAAnB,QAAA,2BAAA,EACAoB,UAAApB,QAAA,oBAAA,EACAqB,UAAArB,QAAA,oBAAA,EACAsB,2BAA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rB,GACzEqB,EACHc,EAAOd,CAAG,EAGVa,EAAQlC,CAAG,CAEb,CAAC,EAGGtJ,GAAG0M,WAAW3M,KAAK4M,KAAK/J,EAAKF,UAAY,aAAe+J,CAAS,CAAC,GACrEzM,GAAGwM,SAASzM,KAAK4M,KAAK/J,EAAKF,UAAY,aAAe+J,CAAS,EAAG,SAAU,SAAC9B,EAAKrB,GAC7EqB,EACHc,EAAOd,CAAG,EAGVa,EAAQlC,CAAG,CAEb,CAAC,CAGJ,CAAC,CACF,EACD/G,aAAA,EAAC,GA9gBYC,QAAAD,cAAAA","file":"method.manager.js","sourcesContent":["import { ServerResponseModel } from '../models/server-response.model';\nimport { loadCollectionMethods } from '../methods/collections';\nimport { MethodModel } from '../models/method.model';\nimport { loadLogMethods } from '../methods/logs';\nimport { loadCounterMethods } from '../methods/counters';\nimport { loadPDFMethods } from '../methods/pdf';\nimport { loadAWSMethods } from '../methods/aws';\nimport * as path from 'path';\nimport * as fs from 'fs';\nimport * as nodemailer from 'nodemailer';\nimport * as sesTransport from 'nodemailer-ses-transport';\nimport { loadAccountMethods } from '../methods/accounts';\nimport { loadServerInit } from '../fixtures/init';\nimport { loadServerCronJobs } from '../fixtures/cron-jobs';\nimport { loadCronJobMethods } from '../methods/cron-jobs';\nimport { loadFlagMethods } from '../methods/flags';\nimport { MethodResponses } from '../collections/method-response.collection';\nimport { getBinarySize } from '../util/common';\nimport { Logs } from '../collections/log.collection';\nimport ResolveIOMainServer from '../server-app';\nimport { LogMethodLatencies } from '../collections/log-method-latency.collection';\nimport * as moment from 'moment-timezone';\nimport { loadReportBuilderMethods } from '../methods/report-builder';\nimport { loadSupportMethods } from '../methods/support';\nimport { loadMonitorMethods } from '../methods/monitor';\nimport { EmailHistories } from '../collections/email-history.collection';\nimport { objectIdHexString } from './mongo.manager';\nimport { MonitorManagerFunction } from './monitor.manager';\nimport { S3 } from '@aws-sdk/client-s3';\n\nexport class AWS {\n\tprivate _serverConfig = null;\n\tprivate _s3: S3 = null;\n\tprivate _s3USEast1: S3 = null;\n\n\tconstructor(serverConfig) {\n\t\tthis._serverConfig = serverConfig;\n\t}\n\n\tpublic s3() : S3 {\n\t\tif (this._s3) {\n\t\t\treturn this._s3;\n\t\t}\n\n\t\tthis._s3 = new S3({\n\t\t\tcredentials: {\n\t\t\t\taccessKeyId: process.env.AWS_ACCESS_KEY,\n\t\t\t\tsecretAccessKey: process.env.AWS_SECRET_ACCESS_KEY\n\t\t\t},\n\t\t\tregion: process.env.AWS_REGION,\n\t\t\tapiVersion: '2006-03-01'\n\t\t});\n\n\t\treturn this._s3;\n\t}\n\n\tpublic s3USEast1() : S3 {\n\t\tif (process.env.AWS_REGION === 'us-east-1') {\n\t\t\treturn this.s3();\n\t\t}\n\t\telse {\n\t\t\tif (this._s3USEast1) {\n\t\t\t\treturn this._s3USEast1;\n\t\t\t}\n\t\t\t\n\t\t\tthis._s3USEast1 = new S3({\n\t\t\t\tcredentials: {\n\t\t\t\t\taccessKeyId: process.env.AWS_ACCESS_KEY,\n\t\t\t\t\tsecretAccessKey: process.env.AWS_SECRET_ACCESS_KEY\n\t\t\t\t},\n\t\t\t\tregion: 'us-east-1',\n\t\t\t\tapiVersion: '2006-03-01'\n\t\t\t});\n\t\n\t\t\treturn this._s3USEast1;\n\t\t}\n\t}\n}\n\nexport class MethodManager {\n\tprivate _mainServer: ResolveIOMainServer;\n\tpublic _methods: MethodModel = {};\n\tprivate _mailer: nodemailer.Transporter;\n\tprivate _aws: AWS;\n\tprivate serverConfig;\n\tprivate clientDir;\n\tprivate _sendQueue = [];\n\tprivate _runningQueue = false;\n\tprivate _monitorManagerFunction: MonitorManagerFunction;\n\n\tprivate _debugCallMethodInternalHits = 0;\n\tprivate _debugCallMethodHits = 0;\n\tprivate _debugCallMethodCronJobHits = 0;\n\tprivate _debugSendQueueHits = 0;\n\n\tconstructor(mainServer, serverConfig, clientDir, monitorManagerFunction: MonitorManagerFunction) {\n\t\tthis._mainServer = mainServer;\n\t\tthis.serverConfig = serverConfig;\n\t\tthis.clientDir = clientDir;\n\t\tthis._monitorManagerFunction = monitorManagerFunction;\n\n\t\t// Fixtures\n\t\tloadServerInit();\n\t\tloadServerCronJobs();\n\n\t\t// Methods\n\t\tloadAccountMethods(this);\n\t\tloadAWSMethods(this);\n\t\tloadCollectionMethods(this);\n\t\tloadCounterMethods(this);\n\t\tloadLogMethods(this);\n\t\tloadPDFMethods(this);\n\t\tloadCronJobMethods(this);\n\t\tloadFlagMethods(this);\n\t\tloadReportBuilderMethods(this);\n\t\tloadSupportMethods(this);\n\t\tloadMonitorMethods(this);\n\n\t\tthis._aws = new AWS(serverConfig);\t\t\n\n\t\tif (mainServer.sesMail) {\n\t\t\tthis._mailer = nodemailer.createTransport(sesTransport({\n\t\t\t\taccessKeyId: process.env.AWS_ACCESS_KEY,\n\t\t\t\tsecretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,\n\t\t\t\tregion: process.env.AWS_SES_REGION\n\t\t\t}));\n\t\t}\n\t\telse {\n\t\t\tthis._mailer = nodemailer.createTransport({\n\t\t\t\thost: this.serverConfig['MAIL_HOST'], // 'smtp.office365.com', // Office 365 server\n\t\t\t\tport: this.serverConfig['MAIL_PORT'], //587, // secure SMTP\n\t\t\t\tsecure: false, // false for TLS - as a boolean not string - but the default is false so just remove this completely\n\t\t\t\tauth: {\n\t\t\t\t\tuser: this.serverConfig['MAIL_USERNAME'],\n\t\t\t\t\tpass: this.serverConfig['MAIL_PASSWORD']\n\t\t\t\t},\n\t\t\t\ttls: {\n\t\t\t\t\tciphers: 'SSLv3'\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\tsetInterval(() => {\n\t\t\tif (this._mainServer.getSubscriptionManager().getEnableDebug()) {\n\t\t\t\tconsole.log(new Date(), 'Method Manager', 'Send Queue Length', this._sendQueue.length);\n\t\t\t\tconsole.log(new Date(), 'Method Manager', 'Send Queue Hits', this._debugSendQueueHits);\n\t\t\t\tconsole.log(new Date(), 'Method Manager', 'Call Method Internal Hits', this._debugCallMethodInternalHits);\n\t\t\t\tconsole.log(new Date(), 'Method Manager', 'Call Method Hits', this._debugCallMethodHits);\n\t\t\t\tconsole.log(new Date(), 'Method Manager', 'Call Method Cron Hits', this._debugCallMethodCronJobHits);\n\t\t\t}\n\n\t\t\tthis._debugCallMethodInternalHits = 0;\n\t\t\tthis._debugCallMethodHits = 0;\n\t\t\tthis._debugCallMethodCronJobHits = 0;\n\t\t\tthis._debugSendQueueHits = 0;\n\t\t\tthis._debugSendQueueHits = 0;\n\t\t}, 60000);\n\n\t\tsetInterval(() => {\n\t\t\tif (!this._runningQueue) {\n\t\t\t\tif (this._sendQueue.length) {\n\t\t\t\t\tthis._runningQueue = true;\n\n\t\t\t\t\tfor (let i = this._sendQueue.length - 1; i >= 0; i--) {\n\t\t\t\t\t\tthis._debugSendQueueHits += 1;\n\n\t\t\t\t\t\tlet ws = this._mainServer.getWS(this._sendQueue[i].id_ws);\n\t\t\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\t\t\tif (ws.bufferedAmount < 20480) {\n\t\t\t\t\t\t\t\tlet sendItem = this._sendQueue.pop();\n\t\t\t\t\t\t\t\tws.send(JSON.stringify(sendItem.data), (error) => {\n\t\t\t\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\t\t\t\tthis._mainServer.unsubscribeWS(ws);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\t\tif (sendItem.method !== 'reportBuilderGetResults' && sendItem.method !== 'reportBuilderGetDistinctValue' && sendItem.method !== 'reportBuilderBuildTree' && sendItem.method !== 'generatePDF' && sendItem.method !== 'getWOOfflineData' && sendItem.method !== 'countQuery' && sendItem.method !== 'countWithQuery' && sendItem.method !== 'countCollectionWithQuery' && sendItem.method !== 'find' && sendItem.method !== 'findOne' && sendItem.method !== 'findWithOptions' && sendItem.method !== 'uploadFileAndSave' && sendItem.method !== 'getDrivers' && sendItem.method !== 'processAirdropDistribution') {\n\t\t\t\t\t\t\t\t\tLogs.insertOne({\n\t\t\t\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\t\t\t\ttype: 'client-response',\n\t\t\t\t\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\t\t\t\t\tpayload: getBinarySize(JSON.stringify([sendItem.methodData, sendItem.data])) < 200000 ? JSON.stringify([sendItem.methodData, sendItem.data], null, 2) : 'Too Big',\n\t\t\t\t\t\t\t\t\t\tmethod: sendItem.method,\n\t\t\t\t\t\t\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\t\t\t\t\t\t\tuser: ws['user'] || '',\n\t\t\t\t\t\t\t\t\t\tmessageId: sendItem.data.messageId,\n\t\t\t\t\t\t\t\t\t\troute: ''\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tMethodResponses.create({\n\t\t\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\t\t\t__v: 0,\n\t\t\t\t\t\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\t\t\t\t\t\tmessage_id: sendItem.data.messageId,\n\t\t\t\t\t\t\t\t\tresponse: getBinarySize(JSON.stringify(sendItem.data)) < 200000 ? sendItem.data : {error: 'Too Big'},\n\t\t\t\t\t\t\t\t\tmethod: sendItem.method,\n\t\t\t\t\t\t\t\t\tdate: sendItem.date\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tthis._sendQueue.splice(i, 1);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tthis._runningQueue = false;\n\t\t\t\t}\n\t\t\t}\n\t\t}, 25);\n\t}\n\n\tpublic getMainServer() {\n\t\treturn this._mainServer;\n\t}\n\n\t// Add methods to private methods object\n\tpublic methods(method: MethodModel) {\n\t\tthis._methods = Object.assign(this._methods, method);\n\t}\n\n\tpublic callMethodCron(method: string, ...methodData: any[]) {\n\t\tthis._debugCallMethodCronJobHits += 1;\n\n\t\tif (!this._methods[method]) {\n\t\t\tconsole.log('No Method: ' + method);\n\n\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'No Method: ' + method);\n\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tif ((methodData.length > 1 || methodData[0]) && !this._methods[method].skipValidation) {\n\t\t\tif (!this._methods[method].check) {\n\t\t\t\tconsole.error(new Date(), 'No Check Function For Method ' + method);\n\n\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'No Check Function For Method ' + method);\n\t\n\t\t\t\treturn;\n\t\t\t}\n\t\t\telse if (!this._methods[method].check._schema) {\n\t\t\t\tconsole.error(new Date(), 'No Check Schema For Method ' + method);\n\n\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'No Check Function For Method ' + method);\n\t\n\t\t\t\treturn;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tlet valObj = {};\n\t\t\t\tlet valKeys = Object.keys(this._methods[method].check._schema);\n\n\t\t\t\tlet rootKeys = valKeys.filter(a => !a.includes('.'));\n\t\t\t\t\n\t\t\t\tfor (let i = 0; i < methodData.length; i++) {\n\t\t\t\t\tvalObj[rootKeys[i]] = methodData[i];\n\t\t\t\t}\n\n\t\t\t\ttry {\n\t\t\t\t\tthis._methods[method].check.validate(valObj);\n\t\t\t\t}\n\t\t\t\tcatch (errors) {\n\t\t\t\t\tif (errors) {\n\t\t\t\t\t\tconsole.error(new Date(), 'Error in Method Check (' + method + ')', errors);\n\n\t\t\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Match Error On Method ' + method + '\\n\\nData Being Checked\\n' + JSON.stringify(valObj, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(errors, null, 2));\n\t\t\t\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Cron Method', method, '', '', methodData);\n\t\tlet promise = this._methods[method].function.call(Object.assign({}, this, MethodManager.prototype, {id_user: '', user: '', id_ws: ''}), ...methodData)\n\t\t.then(res => {\n\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\treturn res;\n\t\t}, methodErrs => {\n\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Error Detected During Method ' + method + ' - (callMethodCron)\\n\\nData \\n' + JSON.stringify(methodData, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(methodErrs, null, 2));\n\t\t\treturn methodErrs;\n\t\t});\n\n\t\treturn promise;\n\t}\n\n\t// Call/run method (Emit on Socket)\n\tpublic callMethod(id_methodLatency: string, ws: WebSocket, messageDate: Date, messageId: number, method: string, ...methodData: any[]) {\n\t\tthis._debugCallMethodHits += 1;\n\t\t\n\t\tif (!this._methods[method]) {\n\t\t\tconsole.log('No Method: ' + method);\n\n\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'No Method: ' + method);\n\t\t\t\n\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\tmessageId: messageId,\n\t\t\t\thasError: true,\n\t\t\t\tdata: 'Internal Error'\n\t\t\t};\n\n\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\n\t\t\tif (id_methodLatency) {\n\t\t\t\tLogMethodLatencies.deleteOne({_id: id_methodLatency});\n\t\t\t}\n\n\t\t\treturn;\n\t\t}\n\n\t\tif ((methodData.length > 1 || methodData[0]) && !this._methods[method].skipValidation) {\n\t\t\tif (!this._methods[method].check) {\n\t\t\t\tconsole.error(new Date(), 'No Check Function For Method ' + method);\n\n\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'No Check Function For Method ' + method);\n\t\t\t\t\n\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\thasError: true,\n\t\t\t\t\tdata: 'Internal Error'\n\t\t\t\t};\n\t\n\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\n\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\tLogMethodLatencies.deleteOne({_id: id_methodLatency});\n\t\t\t\t}\n\t\n\t\t\t\treturn;\n\t\t\t}\n\t\t\telse if (!this._methods[method].check._schema) {\n\t\t\t\tconsole.error(new Date(), 'No Check Schema For Method ' + method);\n\n\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'No Check Function For Method ' + method);\n\t\t\t\t\n\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\thasError: true,\n\t\t\t\t\tdata: 'Internal Error'\n\t\t\t\t};\n\n\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\tLogMethodLatencies.deleteOne({_id: id_methodLatency});\n\t\t\t\t}\n\t\n\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\t\n\t\t\t\treturn;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tlet valObj = {};\n\t\t\t\tlet valKeys = Object.keys(this._methods[method].check._schema);\n\n\t\t\t\tlet rootKeys = valKeys.filter(a => !a.includes('.'));\n\t\t\t\t\n\t\t\t\tfor (let i = 0; i < methodData.length; i++) {\n\t\t\t\t\tvalObj[rootKeys[i]] = methodData[i];\n\t\t\t\t}\n\n\t\t\t\ttry {\n\t\t\t\t\tthis._methods[method].check.validate(valObj);\n\t\t\t\t}\n\t\t\t\tcatch (errors) {\n\t\t\t\t\tif (errors) {\n\t\t\t\t\t\tconsole.error(new Date(), 'Error in Method Check (' + method + ')', errors);\n\n\t\t\t\t\t\tif (method !== 'processAirdropDistribution') {\n\t\t\t\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Match Error On Method ' + method + '\\n\\nData Being Checked\\n' + JSON.stringify(valObj, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(errors, null, 2));\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\t\thasError: true,\n\t\t\t\t\t\t\tdata: 'Internal Error'\n\t\t\t\t\t\t};\n\t\t\t\t\t\t\n\t\t\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\n\t\t\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\t\t\tLogMethodLatencies.deleteOne({_id: id_methodLatency});\n\t\t\t\t\t\t}\n\t\t\t\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Method', method, ws['user'] || '', ws['id_socket'] || '', methodData);\n\t\tthis._methods[method].function.call(Object.assign({}, this, MethodManager.prototype, {id_user: ws['id_user'], user: ws['user'], id_ws: ws['id_socket']}), ...methodData)\n\t\t.then(async (res) => {\n\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\n\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\tmessageId: messageId,\n\t\t\t\thasError: false,\n\t\t\t\tdata: res\n\t\t\t};\n\n\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\n\t\t\tif (id_methodLatency) {\n\t\t\t\tlet latency = await LogMethodLatencies.findById(id_methodLatency);\n\n\t\t\t\tif (latency) {\n\t\t\t\t\tLogMethodLatencies.updateOne({_id: id_methodLatency}, {$set: {date_end: new Date(), latency_ms: moment().diff(moment(latency.date_start), 'milliseconds', true)}});\n\t\t\t\t}\n\t\t\t}\n\t\t}, err => {\n\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\tmessageId: messageId,\n\t\t\t\thasError: true,\n\t\t\t\tdata: err\n\t\t\t};\n\n\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\n\t\t\tif (id_methodLatency) {\n\t\t\t\tLogMethodLatencies.deleteOne({_id: id_methodLatency});\n\t\t\t}\n\n\t\t\tif (method !== 'processAirdropDistribution') {\n\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Error Detected During Method ' + method + ' - (callMethod)\\n\\nData \\n' + JSON.stringify(methodData, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(err, null, 2));\n\t\t\t}\n\t\t});\n\t}\n\n\t// Call/run method internal (No Emit on Socket)\n\tpublic callMethodInternal(method, ...methodData: any[]): Promise<any> {\n\t\tthis._debugCallMethodInternalHits += 1;\n\t\t\n\t\tif (!this._methods[method]) {\n\t\t\tconsole.log('No Method: ' + method);\n\t\t\treturn null;\n\t\t}\n\n\t\tif ((methodData.length > 1 || (methodData[0] && typeof(methodData[0]) !== 'function')) && !this._methods[method].skipValidation) {\n\t\t\tif (!this._methods[method].check) {\n\t\t\t\tconsole.error(new Date(), 'No Check Function For Method ' + method);\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\telse if (!this._methods[method].check._schema) {\n\t\t\t\tconsole.error(new Date(), 'No Check Schema For Method ' + method);\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\n\t\tif (method !== 'insertSubscriptionLog' && method !== 'getDataURIfromURL' && method !== 'processAirdropDistribution') {\n\t\t\tLogs.insertOne({\n\t\t\t\t_id: objectIdHexString(),\n\t\t\t\ttype: 'callMethodInternal',\n\t\t\t\tcollection: '',\n\t\t\t\tid_document: '',\n\t\t\t\tpayload: getBinarySize(JSON.stringify([methodData])) < 200000 ? JSON.stringify([methodData], null, 2) : 'Too Big',\n\t\t\t\tmethod: method,\n\t\t\t\tid_user: this['id_user'] || '',\n\t\t\t\tuser: this['user'] || '',\n\t\t\t\tmessageId: 0,\n\t\t\t\troute: ''\n\t\t\t});\n\t\t}\n\n\t\tlet functionMethodData = typeof(methodData[methodData.length - 1]) === 'function' ? methodData.slice(0, -1) : methodData;\n\n\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Internal Method', method, this['user'] || '', '', functionMethodData);\n\t\tlet promise = this._methods[method].function.call(Object.assign({}, this, MethodManager.prototype), ...functionMethodData)\n\t\t.then(res => {\n\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\treturn res;\n\t\t}, methodErrs => {\n\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Error Detected During Method ' + method + ' - (callMethodInternal)\\n\\nData \\n' + JSON.stringify(methodData, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(methodErrs, null, 2));\n\t\t\treturn methodErrs;\n\t\t});\n\n\t\tif (methodData[methodData.length - 1] && typeof(methodData[methodData.length - 1]) === 'function') {\n\t\t\tpromise.then(res => methodData[methodData.length - 1](null, res), err => methodData[methodData.length - 1](err, null));\n\t\t}\n\t\t\n\t\treturn promise;\n\t}\n\n\tprivate sendWS(ws: WebSocket, messageDate: Date, method: string, methodData: any[], data: ServerResponseModel) {\n\t\tthis._sendQueue.splice(0, 0, {\n\t\t\tid_ws: ws['id_socket'],\n\t\t\tmethod: method,\n\t\t\tmethodData: methodData,\n\t\t\tdata: data,\n\t\t\tdate: messageDate\n\t\t});\n\t}\n\n\tpublic sendEmail(sendTo: string, subject: string, text?: string, html?: string, attachments?: any[], send_from?: string, reply_to?: string) {\n\t\treturn new Promise(async (resolve, reject) => {\n\t\t\tif ((this.serverConfig['ROOT_URL'].match(new RegExp(/https\\:\\/\\/dev\\./)) || this.serverConfig['ROOT_URL'].match(new RegExp(/https\\:\\/\\/www\\.dev\\./)) || this.serverConfig['ROOT_URL'] === 'http://localhost:4200') && !sendTo.match(new RegExp(/\\@resolveio\\.com/))) {\n\t\t\t\tsendTo = 'dev@resolveio.com';\n\t\t\t}\n\n\t\t\tif (sendTo) {\n\t\t\t\tif (this.serverConfig['ROOT_URL'] !== 'http://localhost:4200') {\n\t\t\t\t\tthis._mailer.sendMail({\n\t\t\t\t\t\treplyTo: reply_to !== null && reply_to !== undefined ? reply_to : (this.serverConfig['MAIL_REPLY_TO'] || undefined), //orders@acefluids.com\n\t\t\t\t\t\tfrom: send_from ? send_from : this.serverConfig.MAIL_FROM,\n\t\t\t\t\t\tto: sendTo,\n\t\t\t\t\t\tsubject: (this.serverConfig['ROOT_URL'].match(new RegExp(/https\\:\\/\\/dev\\./)) || this.serverConfig['ROOT_URL'].match(new RegExp(/https\\:\\/\\/www\\.dev\\./)) ? '(DEV SERVER) - ' : '') + subject,\n\t\t\t\t\t\ttext: text,\n\t\t\t\t\t\thtml: html,\n\t\t\t\t\t\tattachments: attachments\n\t\t\t\t\t}, (err, info) => {\n\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\tconsole.log(err);\n\n\t\t\t\t\t\t\tEmailHistories.create({\n\t\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\t\t__v: 0,\n\t\t\t\t\t\t\t\tdate: new Date(),\n\t\t\t\t\t\t\t\tid_user: this['id_user'] || '',\n\t\t\t\t\t\t\t\tuser: this['user'] || '',\n\t\t\t\t\t\t\t\temail: sendTo,\n\t\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\t\tverified: false\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tEmailHistories.create({\n\t\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\t\t__v: 0,\n\t\t\t\t\t\t\t\tdate: new Date(),\n\t\t\t\t\t\t\t\tid_user: this['id_user'] || '',\n\t\t\t\t\t\t\t\tuser: this['user'] || '',\n\t\t\t\t\t\t\t\temail: sendTo,\n\t\t\t\t\t\t\t\tsuccess: true,\n\t\t\t\t\t\t\t\tverified: false\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tconsole.log('Send email', sendTo, subject, text, html, attachments, send_from);\n\t\t\t\t}\n\n\t\t\t\tresolve(true);\n\t\t\t}\n\t\t});\n\t}\n\n\tpublic getAWS(): AWS {\n\t\treturn this._aws;\n\t}\n\n\tpublic readFile(fileName) {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tif (fs.existsSync(path.join(__dirname, ('../private/' + fileName)))) {\n\t\t\t\tfs.readFile(path.join(__dirname, ('../private/' + fileName)), 'utf-8', (err, res) => { \n\t\t\t\t\tif (err) {\n\t\t\t\t\t\treject(err);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tresolve(res);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (fs.existsSync(path.join(this.clientDir, ('./private/' + fileName)))) {\n\t\t\t\t\tfs.readFile(path.join(this.clientDir, ('./private/' + fileName)), 'utf-8', (err, res) => { \n\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\treject(err);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tresolve(res);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n\n\tpublic readImage(fileName) {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tif (fs.existsSync(path.join(__dirname, ('../private/' + fileName)))) {\n\t\t\t\tfs.readFile(path.join(__dirname, ('../private/' + fileName)), 'base64', (err, res) => { \n\t\t\t\t\tif (err) {\n\t\t\t\t\t\treject(err);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tresolve(res);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (fs.existsSync(path.join(this.clientDir, ('./private/' + fileName)))) {\n\t\t\t\t\tfs.readFile(path.join(this.clientDir, ('./private/' + fileName)), 'base64', (err, res) => { \n\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\treject(err);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tresolve(res);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n}"]}
1
+ {"version":3,"sources":["../../src/managers/method.manager.ts"],"names":["collections_1","require","logs_1","counters_1","pdf_1","aws_1","path","fs","nodemailer","sesTransport","accounts_1","init_1","cron_jobs_1","cron_jobs_2","flags_1","method_response_collection_1","common_1","log_collection_1","log_method_latency_collection_1","moment","report_builder_1","support_1","monitor_1","email_history_collection_1","mongo_manager_1","client_s3_1","AWS","serverConfig","this","_serverConfig","_s3","_s3USEast1","prototype","s3","S3","credentials","accessKeyId","process","env","AWS_ACCESS_KEY","secretAccessKey","AWS_SECRET_ACCESS_KEY","region","AWS_REGION","apiVersion","s3USEast1","MethodManager","exports","mainServer","clientDir","monitorManagerFunction","_this","_methods","_sendQueue","_runningQueue","_debugCallMethodInternalHits","_debugCallMethodHits","_debugCallMethodCronJobHits","_debugSendQueueHits","_mainServer","_monitorManagerFunction","loadServerInit","loadServerCronJobs","loadAccountMethods","loadAWSMethods","loadCollectionMethods","loadCounterMethods","loadLogMethods","loadPDFMethods","loadCronJobMethods","loadFlagMethods","loadReportBuilderMethods","loadSupportMethods","loadMonitorMethods","_aws","sesMail","_mailer","createTransport","AWS_SES_REGION","host","port","secure","auth","user","pass","tls","ciphers","setInterval","getSubscriptionManager","getEnableDebug","console","log","Date","length","i","sendItem","ws","getWS","id_ws","readyState","OPEN","bufferedAmount","pop","send","JSON","stringify","data","error","unsubscribeWS","method","Logs","insertOne","_id","objectIdHexString","type","collection","id_document","payload","getBinarySize","methodData","id_user","messageId","route","MethodResponses","create","__v","message_id","response","date","splice","getMainServer","methods","Object","assign","callMethodCron","_i","arguments","skipValidation","check","sendEmail","_schema","valObj","rootKeys","keys","filter","a","includes","validate","errors","monitor","startMonitorFunction","_a","function","call","apply","__spreadArray","then","res","finishMonitorFunction","methodErrs","callMethod","id_methodLatency","messageDate","sendWS","serverRes","hasError","LogMethodLatencies","deleteOne","__awaiter","findById","latency","sent","updateOne","$set","date_end","latency_ms","diff","date_start","err","callMethodInternal","functionMethodData","slice","promise","sendTo","subject","text","html","attachments","send_from","reply_to","local_override","Promise","resolve","reject","match","RegExp","sendMail","replyTo","undefined","from","MAIL_FROM","to","info","EmailHistories","email","success","verified","getAWS","readFile","fileName","existsSync","join","__dirname","readImage"],"mappings":"wqDACAA,e,gGAAAC,QAAA,wBAAA,GAEAC,OAAAD,QAAA,iBAAA,EACAE,WAAAF,QAAA,qBAAA,EACAG,MAAAH,QAAA,gBAAA,EACAI,MAAAJ,QAAA,gBAAA,EACAK,KAAAL,QAAA,MAAA,EACAM,GAAAN,QAAA,IAAA,EACAO,WAAAP,QAAA,YAAA,EACAQ,aAAAR,QAAA,0BAAA,EACAS,WAAAT,QAAA,qBAAA,EACAU,OAAAV,QAAA,kBAAA,EACAW,YAAAX,QAAA,uBAAA,EACAY,YAAAZ,QAAA,sBAAA,EACAa,QAAAb,QAAA,kBAAA,EACAc,6BAAAd,QAAA,2CAAA,EACAe,SAAAf,QAAA,gBAAA,EACAgB,iBAAAhB,QAAA,+BAAA,EAEAiB,gCAAAjB,QAAA,8CAAA,EACAkB,OAAAlB,QAAA,iBAAA,EACAmB,iBAAAnB,QAAA,2BAAA,EACAoB,UAAApB,QAAA,oBAAA,EACAqB,UAAArB,QAAA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GyM,SAAS1M,KAAK6M,KAAKC,UAAY,cAAgBH,CAAS,EAAG,SAAU,SAAC/B,EAAKrB,GACzEqB,EACHe,EAAOf,CAAG,EAGVc,EAAQnC,CAAG,CAEb,CAAC,EAGGtJ,GAAG2M,WAAW5M,KAAK6M,KAAKhK,EAAKF,UAAY,aAAegK,CAAS,CAAC,GACrE1M,GAAGyM,SAAS1M,KAAK6M,KAAKhK,EAAKF,UAAY,aAAegK,CAAS,EAAG,SAAU,SAAC/B,EAAKrB,GAC7EqB,EACHe,EAAOf,CAAG,EAGVc,EAAQnC,CAAG,CAEb,CAAC,CAGJ,CAAC,CACF,EACD/G,aAAA,EAAC,GA9gBYC,QAAAD,cAAAA","file":"method.manager.js","sourcesContent":["import { ServerResponseModel } from '../models/server-response.model';\nimport { loadCollectionMethods } from '../methods/collections';\nimport { MethodModel } from '../models/method.model';\nimport { loadLogMethods } from '../methods/logs';\nimport { loadCounterMethods } from '../methods/counters';\nimport { loadPDFMethods } from '../methods/pdf';\nimport { loadAWSMethods } from '../methods/aws';\nimport * as path from 'path';\nimport * as fs from 'fs';\nimport * as nodemailer from 'nodemailer';\nimport * as sesTransport from 'nodemailer-ses-transport';\nimport { loadAccountMethods } from '../methods/accounts';\nimport { loadServerInit } from '../fixtures/init';\nimport { loadServerCronJobs } from '../fixtures/cron-jobs';\nimport { loadCronJobMethods } from '../methods/cron-jobs';\nimport { loadFlagMethods } from '../methods/flags';\nimport { MethodResponses } from '../collections/method-response.collection';\nimport { getBinarySize } from '../util/common';\nimport { Logs } from '../collections/log.collection';\nimport ResolveIOMainServer from '../server-app';\nimport { LogMethodLatencies } from '../collections/log-method-latency.collection';\nimport * as moment from 'moment-timezone';\nimport { loadReportBuilderMethods } from '../methods/report-builder';\nimport { loadSupportMethods } from '../methods/support';\nimport { loadMonitorMethods } from '../methods/monitor';\nimport { EmailHistories } from '../collections/email-history.collection';\nimport { objectIdHexString } from './mongo.manager';\nimport { MonitorManagerFunction } from './monitor.manager';\nimport { S3 } from '@aws-sdk/client-s3';\n\nexport class AWS {\n\tprivate _serverConfig = null;\n\tprivate _s3: S3 = null;\n\tprivate _s3USEast1: S3 = null;\n\n\tconstructor(serverConfig) {\n\t\tthis._serverConfig = serverConfig;\n\t}\n\n\tpublic s3() : S3 {\n\t\tif (this._s3) {\n\t\t\treturn this._s3;\n\t\t}\n\n\t\tthis._s3 = new S3({\n\t\t\tcredentials: {\n\t\t\t\taccessKeyId: process.env.AWS_ACCESS_KEY,\n\t\t\t\tsecretAccessKey: process.env.AWS_SECRET_ACCESS_KEY\n\t\t\t},\n\t\t\tregion: process.env.AWS_REGION,\n\t\t\tapiVersion: '2006-03-01'\n\t\t});\n\n\t\treturn this._s3;\n\t}\n\n\tpublic s3USEast1() : S3 {\n\t\tif (process.env.AWS_REGION === 'us-east-1') {\n\t\t\treturn this.s3();\n\t\t}\n\t\telse {\n\t\t\tif (this._s3USEast1) {\n\t\t\t\treturn this._s3USEast1;\n\t\t\t}\n\t\t\t\n\t\t\tthis._s3USEast1 = new S3({\n\t\t\t\tcredentials: {\n\t\t\t\t\taccessKeyId: process.env.AWS_ACCESS_KEY,\n\t\t\t\t\tsecretAccessKey: process.env.AWS_SECRET_ACCESS_KEY\n\t\t\t\t},\n\t\t\t\tregion: 'us-east-1',\n\t\t\t\tapiVersion: '2006-03-01'\n\t\t\t});\n\t\n\t\t\treturn this._s3USEast1;\n\t\t}\n\t}\n}\n\nexport class MethodManager {\n\tprivate _mainServer: ResolveIOMainServer;\n\tpublic _methods: MethodModel = {};\n\tprivate _mailer: nodemailer.Transporter;\n\tprivate _aws: AWS;\n\tprivate serverConfig;\n\tprivate clientDir;\n\tprivate _sendQueue = [];\n\tprivate _runningQueue = false;\n\tprivate _monitorManagerFunction: MonitorManagerFunction;\n\n\tprivate _debugCallMethodInternalHits = 0;\n\tprivate _debugCallMethodHits = 0;\n\tprivate _debugCallMethodCronJobHits = 0;\n\tprivate _debugSendQueueHits = 0;\n\n\tconstructor(mainServer, serverConfig, clientDir, monitorManagerFunction: MonitorManagerFunction) {\n\t\tthis._mainServer = mainServer;\n\t\tthis.serverConfig = serverConfig;\n\t\tthis.clientDir = clientDir;\n\t\tthis._monitorManagerFunction = monitorManagerFunction;\n\n\t\t// Fixtures\n\t\tloadServerInit();\n\t\tloadServerCronJobs();\n\n\t\t// Methods\n\t\tloadAccountMethods(this);\n\t\tloadAWSMethods(this);\n\t\tloadCollectionMethods(this);\n\t\tloadCounterMethods(this);\n\t\tloadLogMethods(this);\n\t\tloadPDFMethods(this);\n\t\tloadCronJobMethods(this);\n\t\tloadFlagMethods(this);\n\t\tloadReportBuilderMethods(this);\n\t\tloadSupportMethods(this);\n\t\tloadMonitorMethods(this);\n\n\t\tthis._aws = new AWS(serverConfig);\t\t\n\n\t\tif (mainServer.sesMail) {\n\t\t\tthis._mailer = nodemailer.createTransport(sesTransport({\n\t\t\t\taccessKeyId: process.env.AWS_ACCESS_KEY,\n\t\t\t\tsecretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,\n\t\t\t\tregion: process.env.AWS_SES_REGION\n\t\t\t}));\n\t\t}\n\t\telse {\n\t\t\tthis._mailer = nodemailer.createTransport({\n\t\t\t\thost: this.serverConfig['MAIL_HOST'], // 'smtp.office365.com', // Office 365 server\n\t\t\t\tport: this.serverConfig['MAIL_PORT'], //587, // secure SMTP\n\t\t\t\tsecure: false, // false for TLS - as a boolean not string - but the default is false so just remove this completely\n\t\t\t\tauth: {\n\t\t\t\t\tuser: this.serverConfig['MAIL_USERNAME'],\n\t\t\t\t\tpass: this.serverConfig['MAIL_PASSWORD']\n\t\t\t\t},\n\t\t\t\ttls: {\n\t\t\t\t\tciphers: 'SSLv3'\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\tsetInterval(() => {\n\t\t\tif (this._mainServer.getSubscriptionManager().getEnableDebug()) {\n\t\t\t\tconsole.log(new Date(), 'Method Manager', 'Send Queue Length', this._sendQueue.length);\n\t\t\t\tconsole.log(new Date(), 'Method Manager', 'Send Queue Hits', this._debugSendQueueHits);\n\t\t\t\tconsole.log(new Date(), 'Method Manager', 'Call Method Internal Hits', this._debugCallMethodInternalHits);\n\t\t\t\tconsole.log(new Date(), 'Method Manager', 'Call Method Hits', this._debugCallMethodHits);\n\t\t\t\tconsole.log(new Date(), 'Method Manager', 'Call Method Cron Hits', this._debugCallMethodCronJobHits);\n\t\t\t}\n\n\t\t\tthis._debugCallMethodInternalHits = 0;\n\t\t\tthis._debugCallMethodHits = 0;\n\t\t\tthis._debugCallMethodCronJobHits = 0;\n\t\t\tthis._debugSendQueueHits = 0;\n\t\t\tthis._debugSendQueueHits = 0;\n\t\t}, 60000);\n\n\t\tsetInterval(() => {\n\t\t\tif (!this._runningQueue) {\n\t\t\t\tif (this._sendQueue.length) {\n\t\t\t\t\tthis._runningQueue = true;\n\n\t\t\t\t\tfor (let i = this._sendQueue.length - 1; i >= 0; i--) {\n\t\t\t\t\t\tthis._debugSendQueueHits += 1;\n\n\t\t\t\t\t\tlet ws = this._mainServer.getWS(this._sendQueue[i].id_ws);\n\t\t\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\t\t\tif (ws.bufferedAmount < 20480) {\n\t\t\t\t\t\t\t\tlet sendItem = this._sendQueue.pop();\n\t\t\t\t\t\t\t\tws.send(JSON.stringify(sendItem.data), (error) => {\n\t\t\t\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\t\t\t\tthis._mainServer.unsubscribeWS(ws);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\t\tif (sendItem.method !== 'reportBuilderGetResults' && sendItem.method !== 'reportBuilderGetDistinctValue' && sendItem.method !== 'reportBuilderBuildTree' && sendItem.method !== 'generatePDF' && sendItem.method !== 'getWOOfflineData' && sendItem.method !== 'countQuery' && sendItem.method !== 'countWithQuery' && sendItem.method !== 'countCollectionWithQuery' && sendItem.method !== 'find' && sendItem.method !== 'findOne' && sendItem.method !== 'findWithOptions' && sendItem.method !== 'uploadFileAndSave' && sendItem.method !== 'getDrivers' && sendItem.method !== 'processAirdropDistribution') {\n\t\t\t\t\t\t\t\t\tLogs.insertOne({\n\t\t\t\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\t\t\t\ttype: 'client-response',\n\t\t\t\t\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\t\t\t\t\tpayload: getBinarySize(JSON.stringify([sendItem.methodData, sendItem.data])) < 200000 ? JSON.stringify([sendItem.methodData, sendItem.data], null, 2) : 'Too Big',\n\t\t\t\t\t\t\t\t\t\tmethod: sendItem.method,\n\t\t\t\t\t\t\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\t\t\t\t\t\t\tuser: ws['user'] || '',\n\t\t\t\t\t\t\t\t\t\tmessageId: sendItem.data.messageId,\n\t\t\t\t\t\t\t\t\t\troute: ''\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tMethodResponses.create({\n\t\t\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\t\t\t__v: 0,\n\t\t\t\t\t\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\t\t\t\t\t\tmessage_id: sendItem.data.messageId,\n\t\t\t\t\t\t\t\t\tresponse: getBinarySize(JSON.stringify(sendItem.data)) < 200000 ? sendItem.data : {error: 'Too Big'},\n\t\t\t\t\t\t\t\t\tmethod: sendItem.method,\n\t\t\t\t\t\t\t\t\tdate: sendItem.date\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tthis._sendQueue.splice(i, 1);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tthis._runningQueue = false;\n\t\t\t\t}\n\t\t\t}\n\t\t}, 25);\n\t}\n\n\tpublic getMainServer() {\n\t\treturn this._mainServer;\n\t}\n\n\t// Add methods to private methods object\n\tpublic methods(method: MethodModel) {\n\t\tthis._methods = Object.assign(this._methods, method);\n\t}\n\n\tpublic callMethodCron(method: string, ...methodData: any[]) {\n\t\tthis._debugCallMethodCronJobHits += 1;\n\n\t\tif (!this._methods[method]) {\n\t\t\tconsole.log('No Method: ' + method);\n\n\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'No Method: ' + method);\n\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tif ((methodData.length > 1 || methodData[0]) && !this._methods[method].skipValidation) {\n\t\t\tif (!this._methods[method].check) {\n\t\t\t\tconsole.error(new Date(), 'No Check Function For Method ' + method);\n\n\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'No Check Function For Method ' + method);\n\t\n\t\t\t\treturn;\n\t\t\t}\n\t\t\telse if (!this._methods[method].check._schema) {\n\t\t\t\tconsole.error(new Date(), 'No Check Schema For Method ' + method);\n\n\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'No Check Function For Method ' + method);\n\t\n\t\t\t\treturn;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tlet valObj = {};\n\t\t\t\tlet valKeys = Object.keys(this._methods[method].check._schema);\n\n\t\t\t\tlet rootKeys = valKeys.filter(a => !a.includes('.'));\n\t\t\t\t\n\t\t\t\tfor (let i = 0; i < methodData.length; i++) {\n\t\t\t\t\tvalObj[rootKeys[i]] = methodData[i];\n\t\t\t\t}\n\n\t\t\t\ttry {\n\t\t\t\t\tthis._methods[method].check.validate(valObj);\n\t\t\t\t}\n\t\t\t\tcatch (errors) {\n\t\t\t\t\tif (errors) {\n\t\t\t\t\t\tconsole.error(new Date(), 'Error in Method Check (' + method + ')', errors);\n\n\t\t\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Match Error On Method ' + method + '\\n\\nData Being Checked\\n' + JSON.stringify(valObj, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(errors, null, 2));\n\t\t\t\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Cron Method', method, '', '', methodData);\n\t\tlet promise = this._methods[method].function.call(Object.assign({}, this, MethodManager.prototype, {id_user: '', user: '', id_ws: ''}), ...methodData)\n\t\t.then(res => {\n\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\treturn res;\n\t\t}, methodErrs => {\n\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Error Detected During Method ' + method + ' - (callMethodCron)\\n\\nData \\n' + JSON.stringify(methodData, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(methodErrs, null, 2));\n\t\t\treturn methodErrs;\n\t\t});\n\n\t\treturn promise;\n\t}\n\n\t// Call/run method (Emit on Socket)\n\tpublic callMethod(id_methodLatency: string, ws: WebSocket, messageDate: Date, messageId: number, method: string, ...methodData: any[]) {\n\t\tthis._debugCallMethodHits += 1;\n\t\t\n\t\tif (!this._methods[method]) {\n\t\t\tconsole.log('No Method: ' + method);\n\n\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'No Method: ' + method);\n\t\t\t\n\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\tmessageId: messageId,\n\t\t\t\thasError: true,\n\t\t\t\tdata: 'Internal Error'\n\t\t\t};\n\n\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\n\t\t\tif (id_methodLatency) {\n\t\t\t\tLogMethodLatencies.deleteOne({_id: id_methodLatency});\n\t\t\t}\n\n\t\t\treturn;\n\t\t}\n\n\t\tif ((methodData.length > 1 || methodData[0]) && !this._methods[method].skipValidation) {\n\t\t\tif (!this._methods[method].check) {\n\t\t\t\tconsole.error(new Date(), 'No Check Function For Method ' + method);\n\n\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'No Check Function For Method ' + method);\n\t\t\t\t\n\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\thasError: true,\n\t\t\t\t\tdata: 'Internal Error'\n\t\t\t\t};\n\t\n\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\n\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\tLogMethodLatencies.deleteOne({_id: id_methodLatency});\n\t\t\t\t}\n\t\n\t\t\t\treturn;\n\t\t\t}\n\t\t\telse if (!this._methods[method].check._schema) {\n\t\t\t\tconsole.error(new Date(), 'No Check Schema For Method ' + method);\n\n\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'No Check Function For Method ' + method);\n\t\t\t\t\n\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\thasError: true,\n\t\t\t\t\tdata: 'Internal Error'\n\t\t\t\t};\n\n\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\tLogMethodLatencies.deleteOne({_id: id_methodLatency});\n\t\t\t\t}\n\t\n\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\t\n\t\t\t\treturn;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tlet valObj = {};\n\t\t\t\tlet valKeys = Object.keys(this._methods[method].check._schema);\n\n\t\t\t\tlet rootKeys = valKeys.filter(a => !a.includes('.'));\n\t\t\t\t\n\t\t\t\tfor (let i = 0; i < methodData.length; i++) {\n\t\t\t\t\tvalObj[rootKeys[i]] = methodData[i];\n\t\t\t\t}\n\n\t\t\t\ttry {\n\t\t\t\t\tthis._methods[method].check.validate(valObj);\n\t\t\t\t}\n\t\t\t\tcatch (errors) {\n\t\t\t\t\tif (errors) {\n\t\t\t\t\t\tconsole.error(new Date(), 'Error in Method Check (' + method + ')', errors);\n\n\t\t\t\t\t\tif (method !== 'processAirdropDistribution') {\n\t\t\t\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Match Error On Method ' + method + '\\n\\nData Being Checked\\n' + JSON.stringify(valObj, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(errors, null, 2));\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\t\thasError: true,\n\t\t\t\t\t\t\tdata: 'Internal Error'\n\t\t\t\t\t\t};\n\t\t\t\t\t\t\n\t\t\t\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\n\t\t\t\t\t\tif (id_methodLatency) {\n\t\t\t\t\t\t\tLogMethodLatencies.deleteOne({_id: id_methodLatency});\n\t\t\t\t\t\t}\n\t\t\t\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Method', method, ws['user'] || '', ws['id_socket'] || '', methodData);\n\t\tthis._methods[method].function.call(Object.assign({}, this, MethodManager.prototype, {id_user: ws['id_user'], user: ws['user'], id_ws: ws['id_socket']}), ...methodData)\n\t\t.then(async (res) => {\n\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\n\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\tmessageId: messageId,\n\t\t\t\thasError: false,\n\t\t\t\tdata: res\n\t\t\t};\n\n\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\n\t\t\tif (id_methodLatency) {\n\t\t\t\tlet latency = await LogMethodLatencies.findById(id_methodLatency);\n\n\t\t\t\tif (latency) {\n\t\t\t\t\tLogMethodLatencies.updateOne({_id: id_methodLatency}, {$set: {date_end: new Date(), latency_ms: moment().diff(moment(latency.date_start), 'milliseconds', true)}});\n\t\t\t\t}\n\t\t\t}\n\t\t}, err => {\n\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\tmessageId: messageId,\n\t\t\t\thasError: true,\n\t\t\t\tdata: err\n\t\t\t};\n\n\t\t\tthis.sendWS(ws, messageDate, method, methodData, serverRes);\n\n\t\t\tif (id_methodLatency) {\n\t\t\t\tLogMethodLatencies.deleteOne({_id: id_methodLatency});\n\t\t\t}\n\n\t\t\tif (method !== 'processAirdropDistribution') {\n\t\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Error Detected During Method ' + method + ' - (callMethod)\\n\\nData \\n' + JSON.stringify(methodData, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(err, null, 2));\n\t\t\t}\n\t\t});\n\t}\n\n\t// Call/run method internal (No Emit on Socket)\n\tpublic callMethodInternal(method, ...methodData: any[]): Promise<any> {\n\t\tthis._debugCallMethodInternalHits += 1;\n\t\t\n\t\tif (!this._methods[method]) {\n\t\t\tconsole.log('No Method: ' + method);\n\t\t\treturn null;\n\t\t}\n\n\t\tif ((methodData.length > 1 || (methodData[0] && typeof(methodData[0]) !== 'function')) && !this._methods[method].skipValidation) {\n\t\t\tif (!this._methods[method].check) {\n\t\t\t\tconsole.error(new Date(), 'No Check Function For Method ' + method);\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\telse if (!this._methods[method].check._schema) {\n\t\t\t\tconsole.error(new Date(), 'No Check Schema For Method ' + method);\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\n\t\tif (method !== 'insertSubscriptionLog' && method !== 'getDataURIfromURL' && method !== 'processAirdropDistribution') {\n\t\t\tLogs.insertOne({\n\t\t\t\t_id: objectIdHexString(),\n\t\t\t\ttype: 'callMethodInternal',\n\t\t\t\tcollection: '',\n\t\t\t\tid_document: '',\n\t\t\t\tpayload: getBinarySize(JSON.stringify([methodData])) < 200000 ? JSON.stringify([methodData], null, 2) : 'Too Big',\n\t\t\t\tmethod: method,\n\t\t\t\tid_user: this['id_user'] || '',\n\t\t\t\tuser: this['user'] || '',\n\t\t\t\tmessageId: 0,\n\t\t\t\troute: ''\n\t\t\t});\n\t\t}\n\n\t\tlet functionMethodData = typeof(methodData[methodData.length - 1]) === 'function' ? methodData.slice(0, -1) : methodData;\n\n\t\tlet monitor = this._monitorManagerFunction.startMonitorFunction('Internal Method', method, this['user'] || '', '', functionMethodData);\n\t\tlet promise = this._methods[method].function.call(Object.assign({}, this, MethodManager.prototype), ...functionMethodData)\n\t\t.then(res => {\n\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\treturn res;\n\t\t}, methodErrs => {\n\t\t\tthis._monitorManagerFunction.finishMonitorFunction(monitor);\n\t\t\tthis.sendEmail('dev@resolveio.com', 'SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], 'Error Detected During Method ' + method + ' - (callMethodInternal)\\n\\nData \\n' + JSON.stringify(methodData, null, 2) + '\\n\\nErrors\\n' + JSON.stringify(methodErrs, null, 2));\n\t\t\treturn methodErrs;\n\t\t});\n\n\t\tif (methodData[methodData.length - 1] && typeof(methodData[methodData.length - 1]) === 'function') {\n\t\t\tpromise.then(res => methodData[methodData.length - 1](null, res), err => methodData[methodData.length - 1](err, null));\n\t\t}\n\t\t\n\t\treturn promise;\n\t}\n\n\tprivate sendWS(ws: WebSocket, messageDate: Date, method: string, methodData: any[], data: ServerResponseModel) {\n\t\tthis._sendQueue.splice(0, 0, {\n\t\t\tid_ws: ws['id_socket'],\n\t\t\tmethod: method,\n\t\t\tmethodData: methodData,\n\t\t\tdata: data,\n\t\t\tdate: messageDate\n\t\t});\n\t}\n\n\tpublic sendEmail(sendTo: string, subject: string, text?: string, html?: string, attachments?: any[], send_from?: string, reply_to?: string, local_override = false) {\n\t\treturn new Promise(async (resolve, reject) => {\n\t\t\tif ((this.serverConfig['ROOT_URL'].match(new RegExp(/https\\:\\/\\/dev\\./)) || this.serverConfig['ROOT_URL'].match(new RegExp(/https\\:\\/\\/www\\.dev\\./)) || this.serverConfig['ROOT_URL'] === 'http://localhost:4200') && !sendTo.match(new RegExp(/\\@resolveio\\.com/))) {\n\t\t\t\tsendTo = 'dev@resolveio.com';\n\t\t\t}\n\n\t\t\tif (sendTo) {\n\t\t\t\tif (this.serverConfig['ROOT_URL'] !== 'http://localhost:4200' || local_override) {\n\t\t\t\t\tthis._mailer.sendMail({\n\t\t\t\t\t\treplyTo: reply_to !== null && reply_to !== undefined ? reply_to : (this.serverConfig['MAIL_REPLY_TO'] || undefined), //orders@acefluids.com\n\t\t\t\t\t\tfrom: send_from ? send_from : this.serverConfig.MAIL_FROM,\n\t\t\t\t\t\tto: sendTo,\n\t\t\t\t\t\tsubject: (this.serverConfig['ROOT_URL'].match(new RegExp(/https\\:\\/\\/dev\\./)) || this.serverConfig['ROOT_URL'].match(new RegExp(/https\\:\\/\\/www\\.dev\\./)) ? '(DEV SERVER) - ' : '') + subject,\n\t\t\t\t\t\ttext: text,\n\t\t\t\t\t\thtml: html,\n\t\t\t\t\t\tattachments: attachments\n\t\t\t\t\t}, (err, info) => {\n\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\tconsole.log(err);\n\n\t\t\t\t\t\t\tEmailHistories.create({\n\t\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\t\t__v: 0,\n\t\t\t\t\t\t\t\tdate: new Date(),\n\t\t\t\t\t\t\t\tid_user: this['id_user'] || '',\n\t\t\t\t\t\t\t\tuser: this['user'] || '',\n\t\t\t\t\t\t\t\temail: sendTo,\n\t\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\t\tverified: false\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tEmailHistories.create({\n\t\t\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\t\t\t__v: 0,\n\t\t\t\t\t\t\t\tdate: new Date(),\n\t\t\t\t\t\t\t\tid_user: this['id_user'] || '',\n\t\t\t\t\t\t\t\tuser: this['user'] || '',\n\t\t\t\t\t\t\t\temail: sendTo,\n\t\t\t\t\t\t\t\tsuccess: true,\n\t\t\t\t\t\t\t\tverified: false\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tconsole.log('Send email', sendTo, subject, text, html, attachments, send_from);\n\t\t\t\t}\n\n\t\t\t\tresolve(true);\n\t\t\t}\n\t\t});\n\t}\n\n\tpublic getAWS(): AWS {\n\t\treturn this._aws;\n\t}\n\n\tpublic readFile(fileName) {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tif (fs.existsSync(path.join(__dirname, ('../private/' + fileName)))) {\n\t\t\t\tfs.readFile(path.join(__dirname, ('../private/' + fileName)), 'utf-8', (err, res) => { \n\t\t\t\t\tif (err) {\n\t\t\t\t\t\treject(err);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tresolve(res);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (fs.existsSync(path.join(this.clientDir, ('./private/' + fileName)))) {\n\t\t\t\t\tfs.readFile(path.join(this.clientDir, ('./private/' + fileName)), 'utf-8', (err, res) => { \n\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\treject(err);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tresolve(res);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n\n\tpublic readImage(fileName) {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tif (fs.existsSync(path.join(__dirname, ('../private/' + fileName)))) {\n\t\t\t\tfs.readFile(path.join(__dirname, ('../private/' + fileName)), 'base64', (err, res) => { \n\t\t\t\t\tif (err) {\n\t\t\t\t\t\treject(err);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tresolve(res);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (fs.existsSync(path.join(this.clientDir, ('./private/' + fileName)))) {\n\t\t\t\t\tfs.readFile(path.join(this.clientDir, ('./private/' + fileName)), 'base64', (err, res) => { \n\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\treject(err);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tresolve(res);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n}"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@resolveio/server-lib",
3
- "version": "20.1.11",
3
+ "version": "20.1.13",
4
4
  "description": "",
5
5
  "scripts": {
6
6
  "package": "./build_package.sh",
package/util/common.d.ts CHANGED
@@ -3,6 +3,7 @@ export declare function buildRbSchema(rbSchema: any): any;
3
3
  export declare function buildRbLookups(rbLookups: LookupTables[], defaultSchema: object, default_checked_array?: string[]): object;
4
4
  export declare function throwErr(err: any, lkp: any, lookupNode: any, newPropertyName?: string): void;
5
5
  export declare function roundPrecision(value: number, precision?: number): number;
6
+ export declare function round(value: any, precision?: number): number;
6
7
  export declare function floorPrecision(value: number, precision?: number): number;
7
8
  export declare function deepCopy(value: any): any;
8
9
  export declare function dateReviver(key: any, value: any): any;
package/util/common.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var __assign=this&&this.__assign||function(){return(__assign=Object.assign||function(e){for(var t,r=1,o=arguments.length;r<o;r++)for(var n in t=arguments[r])Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e}).apply(this,arguments)},__spreadArray=this&&this.__spreadArray||function(e,t,r){if(r||2===arguments.length)for(var o,n=0,i=t.length;n<i;n++)!o&&n in t||((o=o||Array.prototype.slice.call(t,0,n))[n]=t[n]);return e.concat(o||Array.prototype.slice.call(t))},rusDiff=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.mergeDeep=exports.isObject=exports.toTitleCase=exports.randomString=exports.pad=exports.getBinarySize=exports.deepDiffDetails=exports.applyMongoUpdate=exports.getDeepDiff=exports.mergeUpdates=exports.getMongoMergeUpdatedDoc=exports.getMongoUpdates=exports.dateReviver=exports.deepCopy=exports.floorPrecision=exports.roundPrecision=exports.throwErr=exports.buildRbLookups=exports.buildRbSchema=void 0,require("rus-diff")),deepDiff=require("deep-diff").diff,deep_object_diff_1=require("deep-object-diff"),clone=require("clone"),moment=require("moment-timezone");function buildRbSchema(t){return Object.keys(t).forEach(function(e){t[e].type===Object?(t[e].type="Object",t[e].rbType="Object"):t[e].type===Array?(t[e].type="Array",t[e].rbType="Array"):t[e].type===String?(t[e].type="String",t[e].rbType="String"):t[e].type===Date?(t[e].type="Date",t[e].rbType="Date"):t[e].type===Number?(t[e].type="Number",t[e].rbType="Number"):t[e].type===Boolean&&(t[e].rbType="Boolean",t[e].type="Boolean")}),Object.keys(t).forEach(function(e){delete t[e].type}),t}function buildRbLookups(e,a,t){void 0===t&&(t=[]),e.forEach(function(e){var t,r="",o="",n="",i=toTitleCase(e.lookup.replace(/\_/g," "))+" ("+toTitleCase(e.local_key.replace("id_","").replace(/\_/g," ").replace(/\.\$\./g," -> ").replace(/\./g," -> "))+") (Lookup)",i=(e.local_key.match(/\./)?(t=e.local_key.replace(/\.\$/g,""),o=(n=e.local_key.replace(/^(.+\.).*$/,"$1")).replace(/\.$/,"")):t=e.local_key,n=n+i,a[e.local_key]?a[e.local_key].type!==String&&(r+="--local_key: '"+e.local_key+"' MUST be a String! "):r+="--local_key: '"+e.local_key+"' MUST be a valid schema path! ",{lookup_collection:e.lookup,lookup_collection_alias:i,local_key:t,field_path:o,lookup_as:n,lookup_key:"_id",type:"Object"});a[n]=i,r&&throwErr(r,e,i,n)});for(var r=0;r<t.length;r++)a[t[r]]={},a[t[r]].default_checked=!0,Object.assign(a[t[r]],a.tree[t[r]]);return a}function throwErr(e,t,r,o){void 0===o&&(o=""),console.log("------- ERROR thrown by rbLookups: "),console.log(e),console.log("---item: "),console.log(t),console.log("---Attempted to create rbSchema['"+o+"']: "),console.log(r),process.exit(1)}function roundPrecision(e,t){void 0===t&&(t=0);e=e.toString(),e.includes(".")&&("0"===e[0]&&(t+=1),t-=e.indexOf(".")),t=Math.pow(10,t);return Math.round(parseFloat(e)*t)/t}function floorPrecision(e,t){void 0===t&&(t=0);e=e.toString(),e.includes(".")&&("0"===e[0]&&(t+=1),t-=e.indexOf(".")),t=Math.pow(10,t);return Math.floor(parseFloat(e)*t)/t}function deepCopy(e){return clone(e)}function dateReviver(e,t){if("string"==typeof t){var r=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(t);if(r)return new Date(Date.UTC(+r[1],+r[2]-1,+r[3],+r[4],+r[5],+r[6].split(".")[0],+r[6].split(".")[1]))}return t}function getMongoUpdates(e,t,r){e.createdAt&&(t.createdAt=e.createdAt),e.updatedAt&&(t.updatedAt=e.updatedAt);e=rusDiff.diff(e,t);return e?(e.$set&&!Object.keys(e.$set).length&&delete e.$set,r&&(e.$inc={__v:1})):r&&(e={$inc:{__v:1}}),e}function getMongoMergeUpdatedDoc(e,t,r){var o=deepCopy(r),t=(o.__v=t.__v,getDeepDiff(r,t));return applyMongoUpdate(o,mergeUpdates(getDeepDiff(r,e),t)),o}function mergeUpdates(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var r={$set:{},$unset:{},$inc:{},$push:{},$pull:{}};return e.filter(Boolean).forEach(function(e){e.forEach(function(e){var t=e.path.join(".");switch(e.kind){case"E":handleEditedChange(r,t,e);break;case"A":handleArrayChange(r,t,e)}})}),r}function handleEditedChange(e,t,r){"number"==typeof r.rhs&&(t.includes("quantity")||t.includes("qty"))?e.$inc[t]=(e.$inc[t]||0)+r.rhs-r.lhs:e.$set[t]=r.rhs}function handleArrayChange(e,t,r){"N"===r.item.kind?(e.$push[t]=e.$push[t]||[],e.$push[t].some(function(e){return JSON.stringify(e)===JSON.stringify(r.item.rhs)})||e.$push[t].push(r.item.rhs)):"D"===r.item.kind&&(e.$pull[t]=e.$pull[t]||[],e.$pull[t].some(function(e){return JSON.stringify(e)===JSON.stringify(r.item.lhs)})||e.$pull[t].push(r.item.lhs))}function getDeepDiff(e,t){return delete e._id,delete e.__v,e.updatedAt&&delete e.updatedAt,e.createdAt&&delete e.createdAt,delete t._id,delete t.__v,t.updatedAt&&delete t.updatedAt,t.createdAt&&delete t.createdAt,deepDiff(e,t)}function applyMongoUpdate(e,t){var r=deepCopy(e);return t&&(t.$rename&&handleRename(e,t.$rename),t.$set&&handleSet(e,t.$set),t.$inc&&handleInc(e,t.$inc),t.$unset&&handleUnset(e,t.$unset),t.$pull&&handlePull(e,r,t.$pull),t.$push)&&handlePush(e,t.$push),e}function handleRename(e,t){for(var r in t){var o=t[r],n=resolve(e,r),i=n[0],n=n[1],a=resolve(e,o),l=a[0],a=a[1];i&&1===n.length?l&&1===a.length?(l[a[0]]=i[n[0]],delete i[n[0]]):logError(l,a,e,o):logError(i,n,e,r)}}function handleSet(e,t){for(var r in t){var o=t[r],n=resolve(e,r,{force:!0}),i=n[0],n=n[1];i&&1===n.length?i[n[0]]=o:logError(i,n,e,r)}}function handleInc(e,t){for(var r in t){var o=t[r],n=resolve(e,r,{force:!0}),i=n[0],n=n[1];i&&1===n.length?i[n[0]]=(i[n[0]]||0)+o:logError(i,n,e,r)}}function handleUnset(e,t){for(var r in t){var o=resolve(e,r),n=o[0],o=o[1];n&&1===o.length?delete n[o[0]]:logError(n,o,e,r)}}function handlePull(i,a,e){for(var l in e)for(var t=0,r=e[l];t<r.length;t++)!function(t){var e=resolve(i,l),r=e[0],e=e[1],o=resolve(a,l),n=o[0],o=o[1];r&&1===e.length?r[e[0]].splice(n[o[0]].findIndex(function(e){return JSON.stringify(e)===JSON.stringify(t)}),1):logError(r,e,i,l)}(r[t])}function handlePush(e,t){for(var r in t)for(var o=0,n=t[r];o<n.length;o++){var i=n[o],a=resolve(e,r),l=a[0],a=a[1];l&&1===a.length?l[a[0]].push(i):logError(l,a,e,r)}}function logError(e,t,r,o){console.log("Error",e+"/"+t+" - couldn't resolve for "+JSON.stringify(r)+" "+o)}function resolve(e,t,r){void 0===r&&(r={});for(var o=arrize(t),n=[],i=(0<o.length&&n.unshift(o.pop()),e);0<o.length;){var a=o.shift();if(void 0===i[a]){if(!r.force){n.unshift(a),n=o.concat(n);break}var l="number"==typeof o[0],s=0===o.length&&"number"==typeof n[0];i[a]=l||s?[]:{}}i=i[a]}return[i,n]}function arrize(e,t){return void 0===t&&(t="."),Array.isArray(e)?e.slice():null==e||!1===e||""===e?[]:e.toString().split(t).map(function(e){return[void 0,null,!1,""].includes(e)?null:e.toString()}).filter(function(e){return null!==e})}function deepDiffDetails(e,t){var r=deepCopy(e),o=deepCopy(t),n=(0,deep_object_diff_1.detailedDiff)(r,o),i="",l=function(t){return t instanceof Date?moment(t).format("llll"):"object"==typeof t&&null!==t?(Object.keys(t).filter(function(e){return e.startsWith("_id")||e.startsWith("id_")}).forEach(function(e){delete t[e]}),JSON.stringify(t)):"string"==typeof t?'"'.concat(t,'"'):String(t)},s=function(o,n){if(null===o||null===n||"object"!=typeof o||"object"!=typeof n)return"from: ".concat(l(o)," to: ").concat(l(n));if(Array.isArray(o)||Array.isArray(n)){for(var e=Array.isArray(o)?o:[],t=Array.isArray(n)?n:[],r=[],i=Math.max(e.length,t.length),a=0;a<i;a++)e[a]&&!t[a]?r.push("Removed at index ".concat(a,": ").concat(l(e[a]))):!e[a]&&t[a]?r.push("Added at index ".concat(a,": ").concat(l(t[a]))):e[a]&&t[a]&&JSON.stringify(e[a])!==JSON.stringify(t[a])&&r.push("Changed at index ".concat(a,": {").concat(s(e[a],t[a]),"}"));return r.join(", ")}return Object.keys(__assign(__assign({},o),n)).filter(function(e){return!e.startsWith("_id")&&!e.startsWith("id_")}).map(function(e){var t=o?o[e]:void 0,r=n?n[e]:void 0;return"".concat(toTitleCase(e),": ").concat(s(t,r))}).join(", ")};return["added","deleted","updated"].forEach(function(t){var e;0<Object.keys(n[t]).length&&(e=Object.keys(n[t]).filter(function(e){return"added"===t||("deleted"===t?!n.added[e]:!n.added[e]&&!n.deleted[e])}).filter(function(e){return!e.startsWith("_id")&&!e.startsWith("id_")}).map(function(e){return"\n".concat(toTitleCase(e),": ").concat(s(r[e],o[e]))}).join(","),i+=e?"".concat(e):"")}),i}function getBinarySize(e){return e?Buffer.byteLength(e,"utf8"):0}function pad(e,t){for(var r=e+"";r.length<t;)r="0"+r;return r}function randomString(e,t){for(var r="",o=e;0<o;--o)r+=t[Math.floor(Math.random()*t.length)];return r}function toTitleCase(e){return e.replace(/\w\S*/g,function(e){return e.charAt(0).toUpperCase()+e.substr(1).toLowerCase()})}function isObject(e){return e&&"object"==typeof e&&!Array.isArray(e)}function mergeDeep(e){for(var t,r=[],o=1;o<arguments.length;o++)r[o-1]=arguments[o];if(!r.length)return e;var n=r.shift();if(isObject(e)&&isObject(n))for(var i in n)isObject(n[i])?(e[i]||Object.assign(e,((t={})[i]={},t)),mergeDeep(e[i],n[i])):Object.assign(e,((t={})[i]=n[i],t));return mergeDeep.apply(void 0,__spreadArray([e],r,!1))}exports.buildRbSchema=buildRbSchema,exports.buildRbLookups=buildRbLookups,exports.throwErr=throwErr,exports.roundPrecision=roundPrecision,exports.floorPrecision=floorPrecision,exports.deepCopy=deepCopy,exports.dateReviver=dateReviver,exports.getMongoUpdates=getMongoUpdates,exports.getMongoMergeUpdatedDoc=getMongoMergeUpdatedDoc,exports.mergeUpdates=mergeUpdates,exports.getDeepDiff=getDeepDiff,exports.applyMongoUpdate=applyMongoUpdate,exports.deepDiffDetails=deepDiffDetails,exports.getBinarySize=getBinarySize,exports.pad=pad,exports.randomString=randomString,exports.toTitleCase=toTitleCase,exports.isObject=isObject,exports.mergeDeep=mergeDeep;
1
+ "use strict";var __assign=this&&this.__assign||function(){return(__assign=Object.assign||function(e){for(var t,r=1,o=arguments.length;r<o;r++)for(var n in t=arguments[r])Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e}).apply(this,arguments)},__spreadArray=this&&this.__spreadArray||function(e,t,r){if(r||2===arguments.length)for(var o,n=0,i=t.length;n<i;n++)!o&&n in t||((o=o||Array.prototype.slice.call(t,0,n))[n]=t[n]);return e.concat(o||Array.prototype.slice.call(t))},rusDiff=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.mergeDeep=exports.isObject=exports.toTitleCase=exports.randomString=exports.pad=exports.getBinarySize=exports.deepDiffDetails=exports.applyMongoUpdate=exports.getDeepDiff=exports.mergeUpdates=exports.getMongoMergeUpdatedDoc=exports.getMongoUpdates=exports.dateReviver=exports.deepCopy=exports.floorPrecision=exports.round=exports.roundPrecision=exports.throwErr=exports.buildRbLookups=exports.buildRbSchema=void 0,require("rus-diff")),deepDiff=require("deep-diff").diff,deep_object_diff_1=require("deep-object-diff"),clone=require("clone"),moment=require("moment-timezone");function buildRbSchema(t){return Object.keys(t).forEach(function(e){t[e].type===Object?(t[e].type="Object",t[e].rbType="Object"):t[e].type===Array?(t[e].type="Array",t[e].rbType="Array"):t[e].type===String?(t[e].type="String",t[e].rbType="String"):t[e].type===Date?(t[e].type="Date",t[e].rbType="Date"):t[e].type===Number?(t[e].type="Number",t[e].rbType="Number"):t[e].type===Boolean&&(t[e].rbType="Boolean",t[e].type="Boolean")}),Object.keys(t).forEach(function(e){delete t[e].type}),t}function buildRbLookups(e,a,t){void 0===t&&(t=[]),e.forEach(function(e){var t,r="",o="",n="",i=toTitleCase(e.lookup.replace(/\_/g," "))+" ("+toTitleCase(e.local_key.replace("id_","").replace(/\_/g," ").replace(/\.\$\./g," -> ").replace(/\./g," -> "))+") (Lookup)",i=(e.local_key.match(/\./)?(t=e.local_key.replace(/\.\$/g,""),o=(n=e.local_key.replace(/^(.+\.).*$/,"$1")).replace(/\.$/,"")):t=e.local_key,n=n+i,a[e.local_key]?a[e.local_key].type!==String&&(r+="--local_key: '"+e.local_key+"' MUST be a String! "):r+="--local_key: '"+e.local_key+"' MUST be a valid schema path! ",{lookup_collection:e.lookup,lookup_collection_alias:i,local_key:t,field_path:o,lookup_as:n,lookup_key:"_id",type:"Object"});a[n]=i,r&&throwErr(r,e,i,n)});for(var r=0;r<t.length;r++)a[t[r]]={},a[t[r]].default_checked=!0,Object.assign(a[t[r]],a.tree[t[r]]);return a}function throwErr(e,t,r,o){void 0===o&&(o=""),console.log("------- ERROR thrown by rbLookups: "),console.log(e),console.log("---item: "),console.log(t),console.log("---Attempted to create rbSchema['"+o+"']: "),console.log(r),process.exit(1)}function roundPrecision(e,t){void 0===t&&(t=0);e=e.toString(),e.includes(".")&&("0"===e[0]&&(t+=1),t-=e.indexOf(".")),t=Math.pow(10,t);return Math.round(parseFloat(e)*t)/t}function round(e,t){void 0===t&&(t=2);t=Math.pow(10,t);return Math.round(e*t+1e-6)/t}function floorPrecision(e,t){void 0===t&&(t=0);e=e.toString(),e.includes(".")&&("0"===e[0]&&(t+=1),t-=e.indexOf(".")),t=Math.pow(10,t);return Math.floor(parseFloat(e)*t)/t}function deepCopy(e){return clone(e)}function dateReviver(e,t){if("string"==typeof t){var r=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(t);if(r)return new Date(Date.UTC(+r[1],+r[2]-1,+r[3],+r[4],+r[5],+r[6].split(".")[0],+r[6].split(".")[1]))}return t}function getMongoUpdates(e,t,r){e.createdAt&&(t.createdAt=e.createdAt),e.updatedAt&&(t.updatedAt=e.updatedAt);e=rusDiff.diff(e,t);return e?(e.$set&&!Object.keys(e.$set).length&&delete e.$set,r&&(e.$inc={__v:1})):r&&(e={$inc:{__v:1}}),e}function getMongoMergeUpdatedDoc(e,t,r){var o=deepCopy(r),t=(o.__v=t.__v,getDeepDiff(r,t));return applyMongoUpdate(o,mergeUpdates(getDeepDiff(r,e),t)),o}function mergeUpdates(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var r={$set:{},$unset:{},$inc:{},$push:{},$pull:{}};return e.filter(Boolean).forEach(function(e){e.forEach(function(e){var t=e.path.join(".");switch(e.kind){case"E":handleEditedChange(r,t,e);break;case"A":handleArrayChange(r,t,e)}})}),r}function handleEditedChange(e,t,r){"number"==typeof r.rhs&&(t.includes("quantity")||t.includes("qty"))?e.$inc[t]=(e.$inc[t]||0)+r.rhs-r.lhs:e.$set[t]=r.rhs}function handleArrayChange(e,t,r){"N"===r.item.kind?(e.$push[t]=e.$push[t]||[],e.$push[t].some(function(e){return JSON.stringify(e)===JSON.stringify(r.item.rhs)})||e.$push[t].push(r.item.rhs)):"D"===r.item.kind&&(e.$pull[t]=e.$pull[t]||[],e.$pull[t].some(function(e){return JSON.stringify(e)===JSON.stringify(r.item.lhs)})||e.$pull[t].push(r.item.lhs))}function getDeepDiff(e,t){return delete e._id,delete e.__v,e.updatedAt&&delete e.updatedAt,e.createdAt&&delete e.createdAt,delete t._id,delete t.__v,t.updatedAt&&delete t.updatedAt,t.createdAt&&delete t.createdAt,deepDiff(e,t)}function applyMongoUpdate(e,t){var r=deepCopy(e);return t&&(t.$rename&&handleRename(e,t.$rename),t.$set&&handleSet(e,t.$set),t.$inc&&handleInc(e,t.$inc),t.$unset&&handleUnset(e,t.$unset),t.$pull&&handlePull(e,r,t.$pull),t.$push)&&handlePush(e,t.$push),e}function handleRename(e,t){for(var r in t){var o=t[r],n=resolve(e,r),i=n[0],n=n[1],a=resolve(e,o),l=a[0],a=a[1];i&&1===n.length?l&&1===a.length?(l[a[0]]=i[n[0]],delete i[n[0]]):logError(l,a,e,o):logError(i,n,e,r)}}function handleSet(e,t){for(var r in t){var o=t[r],n=resolve(e,r,{force:!0}),i=n[0],n=n[1];i&&1===n.length?i[n[0]]=o:logError(i,n,e,r)}}function handleInc(e,t){for(var r in t){var o=t[r],n=resolve(e,r,{force:!0}),i=n[0],n=n[1];i&&1===n.length?i[n[0]]=(i[n[0]]||0)+o:logError(i,n,e,r)}}function handleUnset(e,t){for(var r in t){var o=resolve(e,r),n=o[0],o=o[1];n&&1===o.length?delete n[o[0]]:logError(n,o,e,r)}}function handlePull(i,a,e){for(var l in e)for(var t=0,r=e[l];t<r.length;t++)!function(t){var e=resolve(i,l),r=e[0],e=e[1],o=resolve(a,l),n=o[0],o=o[1];r&&1===e.length?r[e[0]].splice(n[o[0]].findIndex(function(e){return JSON.stringify(e)===JSON.stringify(t)}),1):logError(r,e,i,l)}(r[t])}function handlePush(e,t){for(var r in t)for(var o=0,n=t[r];o<n.length;o++){var i=n[o],a=resolve(e,r),l=a[0],a=a[1];l&&1===a.length?l[a[0]].push(i):logError(l,a,e,r)}}function logError(e,t,r,o){console.log("Error",e+"/"+t+" - couldn't resolve for "+JSON.stringify(r)+" "+o)}function resolve(e,t,r){void 0===r&&(r={});for(var o=arrize(t),n=[],i=(0<o.length&&n.unshift(o.pop()),e);0<o.length;){var a=o.shift();if(void 0===i[a]){if(!r.force){n.unshift(a),n=o.concat(n);break}var l="number"==typeof o[0],s=0===o.length&&"number"==typeof n[0];i[a]=l||s?[]:{}}i=i[a]}return[i,n]}function arrize(e,t){return void 0===t&&(t="."),Array.isArray(e)?e.slice():null==e||!1===e||""===e?[]:e.toString().split(t).map(function(e){return[void 0,null,!1,""].includes(e)?null:e.toString()}).filter(function(e){return null!==e})}function deepDiffDetails(e,t){var r=deepCopy(e),o=deepCopy(t),n=(0,deep_object_diff_1.detailedDiff)(r,o),i="",l=function(t){return t instanceof Date?moment(t).format("llll"):"object"==typeof t&&null!==t?(Object.keys(t).filter(function(e){return e.startsWith("_id")||e.startsWith("id_")}).forEach(function(e){delete t[e]}),JSON.stringify(t)):"string"==typeof t?'"'.concat(t,'"'):String(t)},s=function(o,n){if(null===o||null===n||"object"!=typeof o||"object"!=typeof n)return"from: ".concat(l(o)," to: ").concat(l(n));if(Array.isArray(o)||Array.isArray(n)){for(var e=Array.isArray(o)?o:[],t=Array.isArray(n)?n:[],r=[],i=Math.max(e.length,t.length),a=0;a<i;a++)e[a]&&!t[a]?r.push("Removed at index ".concat(a,": ").concat(l(e[a]))):!e[a]&&t[a]?r.push("Added at index ".concat(a,": ").concat(l(t[a]))):e[a]&&t[a]&&JSON.stringify(e[a])!==JSON.stringify(t[a])&&r.push("Changed at index ".concat(a,": {").concat(s(e[a],t[a]),"}"));return r.join(", ")}return Object.keys(__assign(__assign({},o),n)).filter(function(e){return!e.startsWith("_id")&&!e.startsWith("id_")}).map(function(e){var t=o?o[e]:void 0,r=n?n[e]:void 0;return"".concat(toTitleCase(e),": ").concat(s(t,r))}).join(", ")};return["added","deleted","updated"].forEach(function(t){var e;0<Object.keys(n[t]).length&&(e=Object.keys(n[t]).filter(function(e){return"added"===t||("deleted"===t?!n.added[e]:!n.added[e]&&!n.deleted[e])}).filter(function(e){return!e.startsWith("_id")&&!e.startsWith("id_")}).map(function(e){return"\n".concat(toTitleCase(e),": ").concat(s(r[e],o[e]))}).join(","),i+=e?"".concat(e):"")}),i}function getBinarySize(e){return e?Buffer.byteLength(e,"utf8"):0}function pad(e,t){for(var r=e+"";r.length<t;)r="0"+r;return r}function randomString(e,t){for(var r="",o=e;0<o;--o)r+=t[Math.floor(Math.random()*t.length)];return r}function toTitleCase(e){return e.replace(/\w\S*/g,function(e){return e.charAt(0).toUpperCase()+e.substr(1).toLowerCase()})}function isObject(e){return e&&"object"==typeof e&&!Array.isArray(e)}function mergeDeep(e){for(var t,r=[],o=1;o<arguments.length;o++)r[o-1]=arguments[o];if(!r.length)return e;var n=r.shift();if(isObject(e)&&isObject(n))for(var i in n)isObject(n[i])?(e[i]||Object.assign(e,((t={})[i]={},t)),mergeDeep(e[i],n[i])):Object.assign(e,((t={})[i]=n[i],t));return mergeDeep.apply(void 0,__spreadArray([e],r,!1))}exports.buildRbSchema=buildRbSchema,exports.buildRbLookups=buildRbLookups,exports.throwErr=throwErr,exports.roundPrecision=roundPrecision,exports.round=round,exports.floorPrecision=floorPrecision,exports.deepCopy=deepCopy,exports.dateReviver=dateReviver,exports.getMongoUpdates=getMongoUpdates,exports.getMongoMergeUpdatedDoc=getMongoMergeUpdatedDoc,exports.mergeUpdates=mergeUpdates,exports.getDeepDiff=getDeepDiff,exports.applyMongoUpdate=applyMongoUpdate,exports.deepDiffDetails=deepDiffDetails,exports.getBinarySize=getBinarySize,exports.pad=pad,exports.randomString=randomString,exports.toTitleCase=toTitleCase,exports.isObject=isObject,exports.mergeDeep=mergeDeep;
2
2
  //# sourceMappingURL=common.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/util/common.ts"],"names":["rusDiff","require","deepDiff","diff","deep_object_diff_1","clone","moment","buildRbSchema","rbSchema","Object","keys","forEach","key","type","rbType","Array","String","Date","Number","Boolean","buildRbLookups","rbLookups","defaultSchema","default_checked_array","lkp","localKey","errString","localKeyDir","localKeyDirDot","collectionAlias","toTitleCase","lookup","replace","local_key","lookupNode","match","newPropertyName","lookup_collection","lookup_collection_alias","field_path","lookup_as","lookup_key","throwErr","ii","length","assign","err","console","log","process","exit","roundPrecision","value","precision","stringValue","toString","includes","indexOf","exponent","Math","pow","round","parseFloat","floorPrecision","floor","deepCopy","dateReviver","a","exec","UTC","split","getMongoUpdates","currDoc","modifiedDoc","incVersion","createdAt","updatedAt","updates","$set","$inc","__v","getMongoMergeUpdatedDoc","f_doc","currentDoc","oldDoc","upDoc","diff_1","getDeepDiff","applyMongoUpdate","mergeUpdates","updatesToMerge","_i","arguments","merged","$unset","$push","$pull","filter","anUpdate","change","path","join","kind","handleEditedChange","handleArrayChange","rhs","lhs","item","some","JSON","stringify","push","doc1","doc2","_id","uDoc","delta","orig","$rename","handleRename","handleSet","handleInc","handleUnset","handlePull","handlePush","renameMap","k","v","_a","resolve","o1","n1","_b","o2","n2","logError","setMap","force","o","n","incMap","unsetMap","pullMap","pathk","pullValues_1","vk","splice","findIndex","z","pushMap","pushValues_1","options","stack","arrize","last","e","unshift","pop","shift","concat","isNextNum","isLastNum","glue","isArray","slice","map","deepDiffDetails","object1","object2","obj1","obj2","detailedDiff","diffString","formatValue","format","startsWith","formatObjectDiff","customArrayDiff","arr1","arr2","arrayDiffResults","maxLength","max","i","__assign","obj1Val","undefined","obj2Val","diffType","getBinarySize","string","Buffer","byteLength","pad","num","size","s","randomString","chars","result","random","str","txt","charAt","toUpperCase","substr","toLowerCase","isObject","mergeDeep","target","sources","source","apply","__spreadArray","exports"],"mappings":"yeAAIA,S,+cAAUC,QAAQ,UAAU,GAC5BC,SAAWD,QAAQ,WAAW,EAAEE,KACpCC,mBAAAH,QAAA,kBAAA,EAEII,MAAQJ,QAAQ,OAAO,EAC3BK,OAAAL,QAAA,iBAAA,EAEA,SAAgBM,cAAcC,GAgC7B,OA/BAC,OAAOC,KAAKF,CAAQ,EAAEG,QAAQ,SAAAC,GACzBJ,EAASI,GAAKC,OAASJ,QAC1BD,EAASI,GAAKC,KAAO,SACrBL,EAASI,GAAKE,OAAS,UAEfN,EAASI,GAAKC,OAASE,OAC/BP,EAASI,GAAKC,KAAO,QACrBL,EAASI,GAAKE,OAAS,SAEfN,EAASI,GAAKC,OAASG,QAC/BR,EAASI,GAAKC,KAAO,SACrBL,EAASI,GAAKE,OAAS,UAEfN,EAASI,GAAKC,OAASI,MAC/BT,EAASI,GAAKC,KAAO,OACrBL,EAASI,GAAKE,OAAS,QAEfN,EAASI,GAAKC,OAASK,QAC/BV,EAASI,GAAKC,KAAO,SACrBL,EAASI,GAAKE,OAAS,UAEfN,EAASI,GAAKC,OAASM,UAC/BX,EAASI,GAAKE,OAAS,UACvBN,EAASI,GAAKC,KAAO,UAEvB,CAAC,EAEDJ,OAAOC,KAAKF,CAAQ,EAAEG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Z,OAAOqK,EAER,IAAME,EAASD,EAAQpD,MAAK,EAE5B,GAAIiD,SAASE,CAAM,GAAKF,SAASI,CAAM,EACtC,IAAK,IAAMvM,KAAOuM,EACbJ,SAASI,EAAOvM,EAAI,GAClBqM,EAAOrM,IACXH,OAAOoC,OAAOoK,IAAMjF,EAAA,IAAKpH,GAAM,GAAEoH,EAAA,EAElCgF,UAAUC,EAAOrM,GAAMuM,EAAOvM,EAAI,GAGlCH,OAAOoC,OAAOoK,IAAM7E,EAAA,IAAKxH,GAAMuM,EAAOvM,GAAIwH,EAAA,EAK7C,OAAO4E,UAASI,MAAA,KAAA,EAAAC,cAAA,CAACJ,GAAWC,EAAO,CAAA,CAAA,CAAA,CACpC,CAvhBAI,QAAA/M,cAAAA,cAmCA+M,QAAAlM,eAAAA,eAqDAkM,QAAA5K,SAAAA,SAWA4K,QAAAnK,eAAAA,eAeAmK,QAAAvJ,eAAAA,eAeAuJ,QAAArJ,SAAAA,SAIAqJ,QAAApJ,YAAAA,YAUAoJ,QAAA/I,gBAAAA,gBA+BA+I,QAAArI,wBAAAA,wBAUAqI,QAAA7H,aAAAA,aAmDA6H,QAAA/H,YAAAA,YA0BA+H,QAAA9H,iBAAAA,iBAqJA8H,QAAAhD,gBAAAA,gBAyEAgD,QAAAzB,cAAAA,cASAyB,QAAArB,IAAAA,IAMAqB,QAAAjB,aAAAA,aAMAiB,QAAAxL,YAAAA,YAMAwL,QAAAP,SAAAA,SAIAO,QAAAN,UAAAA","file":"common.js","sourcesContent":["let rusDiff = require('rus-diff');\nlet deepDiff = require('deep-diff').diff;\nimport { detailedDiff } from 'deep-object-diff';\nimport { LookupTables } from '../models/report-builder.model';\nlet clone = require('clone');\nimport * as moment from 'moment-timezone';\n\nexport function buildRbSchema(rbSchema: any) {\n\tObject.keys(rbSchema).forEach(key => {\n\t\tif (rbSchema[key].type === Object) {\n\t\t\trbSchema[key].type = 'Object';\n\t\t\trbSchema[key].rbType = 'Object';\n\t\t}\n\t\telse if (rbSchema[key].type === Array) {\n\t\t\trbSchema[key].type = 'Array';\n\t\t\trbSchema[key].rbType = 'Array';\n\t\t}\n\t\telse if (rbSchema[key].type === String) {\n\t\t\trbSchema[key].type = 'String';\n\t\t\trbSchema[key].rbType = 'String';\n\t\t}\n\t\telse if (rbSchema[key].type === Date) {\n\t\t\trbSchema[key].type = 'Date';\n\t\t\trbSchema[key].rbType = 'Date';\n\t\t}\n\t\telse if (rbSchema[key].type === Number) {\n\t\t\trbSchema[key].type = 'Number';\n\t\t\trbSchema[key].rbType = 'Number';\n\t\t}\n\t\telse if (rbSchema[key].type === Boolean) {\n\t\t\trbSchema[key].rbType = 'Boolean';\n\t\t\trbSchema[key].type = 'Boolean';\n\t\t}\n\t});\n\n\tObject.keys(rbSchema).forEach(key => {\n\t\tdelete rbSchema[key].type;\n\t});\n\n\treturn rbSchema;\n}\n\nexport function buildRbLookups(rbLookups: LookupTables[], defaultSchema: object, default_checked_array: string[] = []) {\n\t// Remember: lkp.local_key will be removed later on, because it has 'id_'\n\t\n\trbLookups.forEach(lkp => {\n\t\tlet errString = '';\n\t\tlet localKey, newPropertyName;\n\t\tlet localKeyDir = '';\n\t\tlet localKeyDirDot = '';\n\t\tlet collectionAlias = toTitleCase(lkp.lookup.replace(/\\_/g, ' ')) + ' (' + toTitleCase(lkp.local_key.replace('id_', '').replace(/\\_/g, ' ').replace(/\\.\\$\\./g, ' -> ').replace(/\\./g, ' -> ')) + ') (Lookup)';\n\n\t\tif (lkp.local_key.match(/\\./)) {\n\t\t\tlocalKey = lkp.local_key.replace(/\\.\\$/g, '');\n\t\t\tlocalKeyDirDot = lkp.local_key.replace(/^(.+\\.).*$/, '$1');\n\t\t\tlocalKeyDir = localKeyDirDot.replace(/\\.$/, '');\n\t\t}\n\t\telse {\n\t\t\t// local_key is a root leaf node.\n\t\t\tlocalKey = lkp.local_key;\n\t\t}\n\t\tnewPropertyName = localKeyDirDot + collectionAlias;\n\t\t\n\t\tif (!defaultSchema[lkp.local_key]) {\n\t\t\terrString += '--local_key: \\'' + lkp.local_key + '\\' MUST be a valid schema path! ';\n\t\t}\n\t\telse if (defaultSchema[lkp.local_key].type !== String) {\n\t\t\terrString += '--local_key: \\'' + lkp.local_key + '\\' MUST be a String! ';\n\t\t}\n\t\tlet lookupNode = {\n\t\t\tlookup_collection: lkp.lookup,\n\t\t\tlookup_collection_alias: collectionAlias,\n\t\t\tlocal_key: localKey,\n\t\t\tfield_path: localKeyDir,\n\t\t\tlookup_as: newPropertyName,\n\t\t\tlookup_key: '_id',\n\t\t\ttype: 'Object',\n\t\t};\n\n\t\tdefaultSchema[newPropertyName] = lookupNode;\n\n\t\tif (errString) {\n\t\t\tthrowErr(errString, lkp, lookupNode, newPropertyName);\n\t\t}\n\t});\n\n\tfor (let ii = 0; ii < default_checked_array.length; ii++) {\n\t\tdefaultSchema[default_checked_array[ii]] = {};\n\t\tdefaultSchema[default_checked_array[ii]]['default_checked'] = true;\n\t\tObject.assign(defaultSchema[default_checked_array[ii]], defaultSchema['tree'][default_checked_array[ii]]);\n\t}\n\n\treturn defaultSchema;\n}\n\nexport function throwErr(err: any, lkp, lookupNode, newPropertyName = '') {\n\t// err could be from a try/throw/catch\n\tconsole.log('------- ERROR thrown by rbLookups: ');\n\tconsole.log(err);\n\tconsole.log('---item: ');\n\tconsole.log(lkp);\n\tconsole.log('---Attempted to create rbSchema[\\'' + newPropertyName + '\\']: ');\n\tconsole.log(lookupNode);\n\tprocess.exit(1);\n}\n\nexport function roundPrecision(value: number, precision = 0) {\n\tlet stringValue = value.toString();\n\t\n\tif (stringValue.includes('.')) {\n\t\tif (stringValue[0] === '0') {\n\t\t\tprecision += 1;\n\t\t}\n\t\t\n\t\tprecision -= stringValue.indexOf('.');\n\t}\n\n\tconst exponent = Math.pow(10, precision);\n\treturn Math.round(parseFloat(stringValue) * exponent) / exponent;\n}\n\nexport function floorPrecision(value: number, precision = 0) {\n\tlet stringValue = value.toString();\n\t\n\tif (stringValue.includes('.')) {\n\t\tif (stringValue[0] === '0') {\n\t\t\tprecision += 1;\n\t\t}\n\t\t\n\t\tprecision -= stringValue.indexOf('.');\n\t}\n\n\tconst exponent = Math.pow(10, precision);\n\treturn Math.floor(parseFloat(stringValue) * exponent) / exponent;\n}\n\nexport function deepCopy(value) {\n\treturn clone(value);\n}\n\nexport function dateReviver(key, value) {\n\tif (typeof value === 'string') {\n\t\tlet a = /^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2}(?:\\.\\d*)?)Z$/.exec(value);\n\t\tif (a) {\n\t\t\treturn new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6].split('.')[0], +a[6].split('.')[1]));\n\t\t}\n\t}\n\treturn value;\n}\n\nexport function getMongoUpdates(currDoc, modifiedDoc, incVersion) {\n\tif (currDoc.createdAt) {\n\t\tmodifiedDoc.createdAt = currDoc.createdAt;\n\t}\n\n\tif (currDoc.updatedAt) {\n\t\tmodifiedDoc.updatedAt = currDoc.updatedAt;\n\t}\n\n\tlet updates = rusDiff.diff(currDoc, modifiedDoc);\n\n\tif (updates) {\n\t\tif (updates.$set && !Object.keys(updates.$set).length) {\n\t\t\tdelete updates.$set;\n\t\t}\n\n\t\tif (incVersion) {\n\t\t\tupdates.$inc = {__v: 1};\n\t\t}\n\t}\n\telse {\n\t\tif (incVersion) {\n\t\t\tupdates = {\n\t\t\t\t$inc: {__v: 1}\n\t\t\t};\n\t\t}\n\t}\n\n\treturn updates;\n}\n\nexport function getMongoMergeUpdatedDoc(f_doc, currentDoc, oldDoc) {\n\tlet upDoc = deepCopy(oldDoc);\n\tupDoc.__v = currentDoc.__v;\n\tlet diff_1 = getDeepDiff(oldDoc, currentDoc);\n\tlet diff_2 = getDeepDiff(oldDoc, f_doc);\n\tlet updates = mergeUpdates(diff_2, diff_1);\n\tapplyMongoUpdate(upDoc, updates);\n\treturn upDoc;\n}\n\nexport function mergeUpdates(...updatesToMerge) {\n const merged = {\n $set: {},\n $unset: {},\n $inc: {},\n $push: {},\n $pull: {}\n };\n\n updatesToMerge.filter(Boolean).forEach(anUpdate => {\n anUpdate.forEach(change => {\n const path = change.path.join('.');\n\n switch (change.kind) {\n case 'E':\n handleEditedChange(merged, path, change);\n break;\n case 'A':\n handleArrayChange(merged, path, change);\n break;\n default:\n break;\n }\n });\n });\n\n return merged;\n}\n\nfunction handleEditedChange(merged, path, change) {\n if (typeof(change.rhs) === 'number' && (path.includes('quantity') || path.includes('qty'))) {\n merged.$inc[path] = (merged.$inc[path] || 0) + change.rhs - change.lhs;\n } else {\n merged.$set[path] = change.rhs;\n }\n}\n\nfunction handleArrayChange(merged, path, change) {\n if (change.item.kind === 'N') {\n merged.$push[path] = merged.$push[path] || [];\n if (!merged.$push[path].some(a => JSON.stringify(a) === JSON.stringify(change.item.rhs))) {\n merged.$push[path].push(change.item.rhs);\n }\n } else if (change.item.kind === 'D') {\n merged.$pull[path] = merged.$pull[path] || [];\n if (!merged.$pull[path].some(a => JSON.stringify(a) === JSON.stringify(change.item.lhs))) {\n merged.$pull[path].push(change.item.lhs);\n }\n }\n}\n\nexport function getDeepDiff(doc1, doc2) {\n\tdelete doc1._id;\n\tdelete doc1.__v;\n\n\tif (doc1.updatedAt) {\n\t\tdelete doc1.updatedAt;\n\t}\n\n\tif (doc1.createdAt) {\n\t\tdelete doc1.createdAt;\n\t}\n\n\tdelete doc2._id;\n\tdelete doc2.__v;\n\n\tif (doc2.updatedAt) {\n\t\tdelete doc2.updatedAt;\n\t}\n\n\tif (doc2.createdAt) {\n\t\tdelete doc2.createdAt;\n\t}\n\n\treturn deepDiff(doc1, doc2);\n}\n\nexport function applyMongoUpdate(uDoc: any, delta: any): any {\n const orig = deepCopy(uDoc);\n\n if (delta) {\n if (delta.$rename) handleRename(uDoc, delta.$rename);\n if (delta.$set) handleSet(uDoc, delta.$set);\n if (delta.$inc) handleInc(uDoc, delta.$inc);\n if (delta.$unset) handleUnset(uDoc, delta.$unset);\n if (delta.$pull) handlePull(uDoc, orig, delta.$pull);\n if (delta.$push) handlePush(uDoc, delta.$push);\n }\n\n return uDoc;\n}\n\nfunction handleRename(uDoc: any, renameMap: any) {\n for (const k in renameMap) {\n const v = renameMap[k];\n const [o1, n1] = resolve(uDoc, k);\n const [o2, n2] = resolve(uDoc, v);\n if (o1 && n1.length === 1) {\n if (o2 && n2.length === 1) {\n o2[n2[0]] = o1[n1[0]];\n delete o1[n1[0]];\n } else {\n logError(o2, n2, uDoc, v);\n }\n } else {\n logError(o1, n1, uDoc, k);\n }\n }\n}\n\nfunction handleSet(uDoc: any, setMap: any) {\n for (const k in setMap) {\n const v = setMap[k];\n const [o, n] = resolve(uDoc, k, { force: true });\n if (o && n.length === 1) {\n o[n[0]] = v;\n } else {\n logError(o, n, uDoc, k);\n }\n }\n}\n\nfunction handleInc(uDoc: any, incMap: any) {\n for (const k in incMap) {\n const v = incMap[k];\n const [o, n] = resolve(uDoc, k, { force: true });\n if (o && n.length === 1) {\n o[n[0]] = (o[n[0]] || 0) + v;\n } else {\n logError(o, n, uDoc, k);\n }\n }\n}\n\nfunction handleUnset(uDoc: any, unsetMap: any) {\n for (const k in unsetMap) {\n const [o, n] = resolve(uDoc, k);\n if (o && n.length === 1) {\n delete o[n[0]];\n } else {\n logError(o, n, uDoc, k);\n }\n }\n}\n\nfunction handlePull(uDoc: any, orig: any, pullMap: any) {\n for (const pathk in pullMap) {\n const pullValues = pullMap[pathk];\n for (let vk of pullValues) {\n const [o, n] = resolve(uDoc, pathk);\n const [o2, n2] = resolve(orig, pathk);\n if (o && n.length === 1) {\n o[n[0]].splice((<Array<any>>o2[n2[0]]).findIndex(z => JSON.stringify(z) === JSON.stringify(vk)), 1);\n } else {\n logError(o, n, uDoc, pathk);\n }\n }\n }\n}\n\nfunction handlePush(uDoc: any, pushMap: any) {\n for (const pathk in pushMap) {\n const pushValues = pushMap[pathk];\n for (let vk of pushValues) {\n const [o, n] = resolve(uDoc, pathk);\n if (o && n.length === 1) {\n o[n[0]].push(vk);\n } else {\n logError(o, n, uDoc, pathk);\n }\n }\n }\n}\n\nfunction logError(o: any, n: any, uDoc: any, key: any) {\n console.log('Error', o + '/' + n + ' - couldn\\'t resolve for ' + JSON.stringify(uDoc) + ' ' + key);\n}\n\nfunction resolve(a: any, path: string, options: any = {}): [any, any] {\n const stack = arrize(path);\n let last = [];\n\n if (stack.length > 0) {\n last.unshift(stack.pop());\n }\n\n let e = a;\n while (stack.length > 0) {\n const k = stack.shift();\n if (e[k] !== void 0) {\n e = e[k];\n } else {\n if (!options.force) {\n last.unshift(k);\n last = stack.concat(last);\n break;\n }\n const isNextNum = typeof stack[0] === 'number';\n const isLastNum = stack.length === 0 && typeof last[0] === 'number';\n e[k] = isNextNum || isLastNum ? [] : {};\n e = e[k];\n }\n }\n\n return [e, last];\n}\n\nfunction arrize(path: any, glue: string = '.'): string[] {\n if (Array.isArray(path)) {\n return path.slice();\n }\n\n if (path === void 0 || path === null || path === false || path === '') {\n return [];\n }\n\n return path.toString().split(glue)\n .map(e => {\n if ([void 0, null, false, ''].includes(e)) {\n return null;\n }\n return e.toString();\n })\n .filter(e => e !== null);\n}\n\nexport function deepDiffDetails(object1: Object, object2: Object): string {\n let obj1 = deepCopy(object1);\n\tlet obj2 = deepCopy(object2);\n\n\tlet diff = detailedDiff(obj1, obj2);\n\tlet diffString = '';\n\n\tconst formatValue = (value: any): string => {\n\t\tif (value instanceof Date) {\n\t\t\treturn moment(value).format('llll');\n\t\t} \n\t\telse if (typeof value === 'object' && value !== null) {\n\t\t\tObject.keys(value).filter(a => a.startsWith('_id') || a.startsWith('id_')).forEach(key => {\n\t\t\t\tdelete value[key];\n\t\t\t});\n\t\t\treturn JSON.stringify(value); // Pretty print objects\n\t\t} \n\t\telse {\n\t\t\treturn typeof value === 'string' ? `\"${value}\"` : String(value);\n\t\t}\n\t};\n\n\tconst customArrayDiff = (arr1: any[], arr2: any[]): string => {\n let arrayDiffResults = [];\n const maxLength = Math.max(arr1.length, arr2.length);\n\n for (let i = 0; i < maxLength; i++) {\n if (arr1[i] && !arr2[i]) {\n arrayDiffResults.push(`Removed at index ${i}: ${formatValue(arr1[i])}`);\n } \n\t\t\telse if (!arr1[i] && arr2[i]) {\n arrayDiffResults.push(`Added at index ${i}: ${formatValue(arr2[i])}`);\n } \n\t\t\telse if (arr1[i] && arr2[i] && JSON.stringify(arr1[i]) !== JSON.stringify(arr2[i])) {\n arrayDiffResults.push(`Changed at index ${i}: {${formatObjectDiff(arr1[i], arr2[i])}}`);\n }\n }\n\n return arrayDiffResults.join(', ');\n };\n\n\tconst formatObjectDiff = (obj1: any, obj2: any): string => {\n\t\tif (obj1 === null || obj2 === null || typeof obj1 !== 'object' || typeof obj2 !== 'object') {\n\t\t\treturn `from: ${formatValue(obj1)} to: ${formatValue(obj2)}`;\n\t\t}\n\n\t\tif (Array.isArray(obj1) || Array.isArray(obj2)) {\n\t\t\treturn customArrayDiff(Array.isArray(obj1) ? obj1 : [], Array.isArray(obj2) ? obj2 : []);\n\t\t}\n\n\t\treturn Object.keys({...obj1, ...obj2}).filter(a => !a.startsWith('_id') && !a.startsWith('id_')).map(key => {\n\t\t\tconst obj1Val = obj1 ? obj1[key] : undefined;\n\t\t\tconst obj2Val = obj2 ? obj2[key] : undefined;\n\t\t\treturn `${toTitleCase(key)}: ${formatObjectDiff(obj1Val, obj2Val)}`;\n\t\t}).join(', ');\n\t};\n\n\t// Handle each diff type\n\t['added', 'deleted', 'updated'].forEach(diffType => {\n\t\tif (Object.keys(diff[diffType]).length > 0) {\n\t\t\tconst updates = Object.keys(diff[diffType])\n\t\t\t\t.filter(key => diffType === 'added' ? true : (diffType === 'deleted' ? !diff['added'][key] : !diff['added'][key] && !diff['deleted'][key]))\n\t\t\t\t.filter(key => !key.startsWith('_id') && !key.startsWith('id_'))\n\t\t\t\t.map(key => `\\n${toTitleCase(key)}: ${formatObjectDiff(obj1[key], obj2[key])}`)\n\t\t\t\t.join(',');\n\n\t\t\tdiffString += updates ? `${updates}` : '';\n\t\t}\n\t});\n\n\treturn diffString;\n}\n\nexport function getBinarySize(string) {\n\tif (string) {\n\t\treturn Buffer.byteLength(string, 'utf8');\n\t}\n\telse {\n\t\treturn 0;\n\t}\n}\n\nexport function pad(num, size) {\n\tlet s = num + '';\n\twhile (s.length < size) { s = '0' + s; }\n\treturn s;\n}\n\nexport function randomString(length, chars) {\n\tlet result = '';\n\tfor (let i = length; i > 0; --i) { result += chars[Math.floor(Math.random() * chars.length)]; }\n\treturn result;\n}\n\nexport function toTitleCase(str) {\n\treturn str.replace(/\\w\\S*/g, function(txt){\n\t\treturn txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();\n\t});\n}\n\nexport function isObject(item) {\n\treturn (item && typeof item === 'object' && !Array.isArray(item));\n}\n\nexport function mergeDeep(target, ...sources) {\n\tif (!sources.length) {\n\t\treturn target;\n\t}\n\tconst source = sources.shift();\n\n\tif (isObject(target) && isObject(source)) {\n\t\tfor (const key in source) {\n\t\t\tif (isObject(source[key])) {\n\t\t\t\tif (!target[key]) {\n\t\t\t\t\tObject.assign(target, { [key]: {} });\n\t\t\t\t}\n\t\t\t\tmergeDeep(target[key], source[key]);\n\t\t\t} \n\t\t\telse {\n\t\t\t\tObject.assign(target, { [key]: source[key] });\n\t\t\t}\n\t\t}\n\t}\n\n\treturn mergeDeep(target, ...sources);\n}"]}
1
+ {"version":3,"sources":["../../src/util/common.ts"],"names":["rusDiff","require","deepDiff","diff","deep_object_diff_1","clone","moment","buildRbSchema","rbSchema","Object","keys","forEach","key","type","rbType","Array","String","Date","Number","Boolean","buildRbLookups","rbLookups","defaultSchema","default_checked_array","lkp","localKey","errString","localKeyDir","localKeyDirDot","collectionAlias","toTitleCase","lookup","replace","local_key","lookupNode","match","newPropertyName","lookup_collection","lookup_collection_alias","field_path","lookup_as","lookup_key","throwErr","ii","length","assign","err","console","log","process","exit","roundPrecision","value","precision","stringValue","toString","includes","indexOf","exponent","Math","pow","round","parseFloat","power","floorPrecision","floor","deepCopy","dateReviver","a","exec","UTC","split","getMongoUpdates","currDoc","modifiedDoc","incVersion","createdAt","updatedAt","updates","$set","$inc","__v","getMongoMergeUpdatedDoc","f_doc","currentDoc","oldDoc","upDoc","diff_1","getDeepDiff","applyMongoUpdate","mergeUpdates","updatesToMerge","_i","arguments","merged","$unset","$push","$pull","filter","anUpdate","change","path","join","kind","handleEditedChange","handleArrayChange","rhs","lhs","item","some","JSON","stringify","push","doc1","doc2","_id","uDoc","delta","orig","$rename","handleRename","handleSet","handleInc","handleUnset","handlePull","handlePush","renameMap","k","v","_a","resolve","o1","n1","_b","o2","n2","logError","setMap","force","o","n","incMap","unsetMap","pullMap","pathk","pullValues_1","vk","splice","findIndex","z","pushMap","pushValues_1","options","stack","arrize","last","e","unshift","pop","shift","concat","isNextNum","isLastNum","glue","isArray","slice","map","deepDiffDetails","object1","object2","obj1","obj2","detailedDiff","diffString","formatValue","format","startsWith","formatObjectDiff","customArrayDiff","arr1","arr2","arrayDiffResults","maxLength","max","i","__assign","obj1Val","undefined","obj2Val","diffType","getBinarySize","string","Buffer","byteLength","pad","num","size","s","randomString","chars","result","random","str","txt","charAt","toUpperCase","substr","toLowerCase","isObject","mergeDeep","target","sources","source","apply","__spreadArray","exports"],"mappings":"yeAAIA,S,6dAAUC,QAAQ,UAAU,GAC5BC,SAAWD,QAAQ,WAAW,EAAEE,KACpCC,mBAAAH,QAAA,kBAAA,EAEII,MAAQJ,QAAQ,OAAO,EAC3BK,OAAAL,QAAA,iBAAA,EAEA,SAAgBM,cAAcC,GAgC7B,OA/BAC,OAAOC,KAAKF,CAAQ,EAAEG,QAAQ,SAAAC,GACzBJ,EAASI,GAAKC,OAASJ,QAC1BD,EAASI,GAAKC,KAAO,SACrBL,EAASI,GAAKE,OAAS,UAEfN,EAASI,GAAKC,OAASE,OAC/BP,EAASI,GAAKC,KAAO,QACrBL,EAASI,GAAKE,OAAS,SAEfN,EAASI,GAAKC,OAASG,QAC/BR,EAASI,GAAKC,KAAO,SACrBL,EAASI,GAA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+H,QAAA9H,iBAAAA,iBAqJA8H,QAAAhD,gBAAAA,gBAyEAgD,QAAAzB,cAAAA,cASAyB,QAAArB,IAAAA,IAMAqB,QAAAjB,aAAAA,aAMAiB,QAAAzL,YAAAA,YAMAyL,QAAAP,SAAAA,SAIAO,QAAAN,UAAAA","file":"common.js","sourcesContent":["let rusDiff = require('rus-diff');\nlet deepDiff = require('deep-diff').diff;\nimport { detailedDiff } from 'deep-object-diff';\nimport { LookupTables } from '../models/report-builder.model';\nlet clone = require('clone');\nimport * as moment from 'moment-timezone';\n\nexport function buildRbSchema(rbSchema: any) {\n\tObject.keys(rbSchema).forEach(key => {\n\t\tif (rbSchema[key].type === Object) {\n\t\t\trbSchema[key].type = 'Object';\n\t\t\trbSchema[key].rbType = 'Object';\n\t\t}\n\t\telse if (rbSchema[key].type === Array) {\n\t\t\trbSchema[key].type = 'Array';\n\t\t\trbSchema[key].rbType = 'Array';\n\t\t}\n\t\telse if (rbSchema[key].type === String) {\n\t\t\trbSchema[key].type = 'String';\n\t\t\trbSchema[key].rbType = 'String';\n\t\t}\n\t\telse if (rbSchema[key].type === Date) {\n\t\t\trbSchema[key].type = 'Date';\n\t\t\trbSchema[key].rbType = 'Date';\n\t\t}\n\t\telse if (rbSchema[key].type === Number) {\n\t\t\trbSchema[key].type = 'Number';\n\t\t\trbSchema[key].rbType = 'Number';\n\t\t}\n\t\telse if (rbSchema[key].type === Boolean) {\n\t\t\trbSchema[key].rbType = 'Boolean';\n\t\t\trbSchema[key].type = 'Boolean';\n\t\t}\n\t});\n\n\tObject.keys(rbSchema).forEach(key => {\n\t\tdelete rbSchema[key].type;\n\t});\n\n\treturn rbSchema;\n}\n\nexport function buildRbLookups(rbLookups: LookupTables[], defaultSchema: object, default_checked_array: string[] = []) {\n\t// Remember: lkp.local_key will be removed later on, because it has 'id_'\n\t\n\trbLookups.forEach(lkp => {\n\t\tlet errString = '';\n\t\tlet localKey, newPropertyName;\n\t\tlet localKeyDir = '';\n\t\tlet localKeyDirDot = '';\n\t\tlet collectionAlias = toTitleCase(lkp.lookup.replace(/\\_/g, ' ')) + ' (' + toTitleCase(lkp.local_key.replace('id_', '').replace(/\\_/g, ' ').replace(/\\.\\$\\./g, ' -> ').replace(/\\./g, ' -> ')) + ') (Lookup)';\n\n\t\tif (lkp.local_key.match(/\\./)) {\n\t\t\tlocalKey = lkp.local_key.replace(/\\.\\$/g, '');\n\t\t\tlocalKeyDirDot = lkp.local_key.replace(/^(.+\\.).*$/, '$1');\n\t\t\tlocalKeyDir = localKeyDirDot.replace(/\\.$/, '');\n\t\t}\n\t\telse {\n\t\t\t// local_key is a root leaf node.\n\t\t\tlocalKey = lkp.local_key;\n\t\t}\n\t\tnewPropertyName = localKeyDirDot + collectionAlias;\n\t\t\n\t\tif (!defaultSchema[lkp.local_key]) {\n\t\t\terrString += '--local_key: \\'' + lkp.local_key + '\\' MUST be a valid schema path! ';\n\t\t}\n\t\telse if (defaultSchema[lkp.local_key].type !== String) {\n\t\t\terrString += '--local_key: \\'' + lkp.local_key + '\\' MUST be a String! ';\n\t\t}\n\t\tlet lookupNode = {\n\t\t\tlookup_collection: lkp.lookup,\n\t\t\tlookup_collection_alias: collectionAlias,\n\t\t\tlocal_key: localKey,\n\t\t\tfield_path: localKeyDir,\n\t\t\tlookup_as: newPropertyName,\n\t\t\tlookup_key: '_id',\n\t\t\ttype: 'Object',\n\t\t};\n\n\t\tdefaultSchema[newPropertyName] = lookupNode;\n\n\t\tif (errString) {\n\t\t\tthrowErr(errString, lkp, lookupNode, newPropertyName);\n\t\t}\n\t});\n\n\tfor (let ii = 0; ii < default_checked_array.length; ii++) {\n\t\tdefaultSchema[default_checked_array[ii]] = {};\n\t\tdefaultSchema[default_checked_array[ii]]['default_checked'] = true;\n\t\tObject.assign(defaultSchema[default_checked_array[ii]], defaultSchema['tree'][default_checked_array[ii]]);\n\t}\n\n\treturn defaultSchema;\n}\n\nexport function throwErr(err: any, lkp, lookupNode, newPropertyName = '') {\n\t// err could be from a try/throw/catch\n\tconsole.log('------- ERROR thrown by rbLookups: ');\n\tconsole.log(err);\n\tconsole.log('---item: ');\n\tconsole.log(lkp);\n\tconsole.log('---Attempted to create rbSchema[\\'' + newPropertyName + '\\']: ');\n\tconsole.log(lookupNode);\n\tprocess.exit(1);\n}\n\nexport function roundPrecision(value: number, precision = 0) {\n\tlet stringValue = value.toString();\n\t\n\tif (stringValue.includes('.')) {\n\t\tif (stringValue[0] === '0') {\n\t\t\tprecision += 1;\n\t\t}\n\t\t\n\t\tprecision -= stringValue.indexOf('.');\n\t}\n\n\tconst exponent = Math.pow(10, precision);\n\treturn Math.round(parseFloat(stringValue) * exponent) / exponent;\n}\n\nexport function round(value, precision = 2) {\n\tconst power = Math.pow(10, precision);\n\tconst adjustment = 1e-6;\n\treturn Math.round( (value * power) + adjustment) / power;\n}\n\nexport function floorPrecision(value: number, precision = 0) {\n\tlet stringValue = value.toString();\n\t\n\tif (stringValue.includes('.')) {\n\t\tif (stringValue[0] === '0') {\n\t\t\tprecision += 1;\n\t\t}\n\t\t\n\t\tprecision -= stringValue.indexOf('.');\n\t}\n\n\tconst exponent = Math.pow(10, precision);\n\treturn Math.floor(parseFloat(stringValue) * exponent) / exponent;\n}\n\nexport function deepCopy(value) {\n\treturn clone(value);\n}\n\nexport function dateReviver(key, value) {\n\tif (typeof value === 'string') {\n\t\tlet a = /^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2}(?:\\.\\d*)?)Z$/.exec(value);\n\t\tif (a) {\n\t\t\treturn new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6].split('.')[0], +a[6].split('.')[1]));\n\t\t}\n\t}\n\treturn value;\n}\n\nexport function getMongoUpdates(currDoc, modifiedDoc, incVersion) {\n\tif (currDoc.createdAt) {\n\t\tmodifiedDoc.createdAt = currDoc.createdAt;\n\t}\n\n\tif (currDoc.updatedAt) {\n\t\tmodifiedDoc.updatedAt = currDoc.updatedAt;\n\t}\n\n\tlet updates = rusDiff.diff(currDoc, modifiedDoc);\n\n\tif (updates) {\n\t\tif (updates.$set && !Object.keys(updates.$set).length) {\n\t\t\tdelete updates.$set;\n\t\t}\n\n\t\tif (incVersion) {\n\t\t\tupdates.$inc = {__v: 1};\n\t\t}\n\t}\n\telse {\n\t\tif (incVersion) {\n\t\t\tupdates = {\n\t\t\t\t$inc: {__v: 1}\n\t\t\t};\n\t\t}\n\t}\n\n\treturn updates;\n}\n\nexport function getMongoMergeUpdatedDoc(f_doc, currentDoc, oldDoc) {\n\tlet upDoc = deepCopy(oldDoc);\n\tupDoc.__v = currentDoc.__v;\n\tlet diff_1 = getDeepDiff(oldDoc, currentDoc);\n\tlet diff_2 = getDeepDiff(oldDoc, f_doc);\n\tlet updates = mergeUpdates(diff_2, diff_1);\n\tapplyMongoUpdate(upDoc, updates);\n\treturn upDoc;\n}\n\nexport function mergeUpdates(...updatesToMerge) {\n const merged = {\n $set: {},\n $unset: {},\n $inc: {},\n $push: {},\n $pull: {}\n };\n\n updatesToMerge.filter(Boolean).forEach(anUpdate => {\n anUpdate.forEach(change => {\n const path = change.path.join('.');\n\n switch (change.kind) {\n case 'E':\n handleEditedChange(merged, path, change);\n break;\n case 'A':\n handleArrayChange(merged, path, change);\n break;\n default:\n break;\n }\n });\n });\n\n return merged;\n}\n\nfunction handleEditedChange(merged, path, change) {\n if (typeof(change.rhs) === 'number' && (path.includes('quantity') || path.includes('qty'))) {\n merged.$inc[path] = (merged.$inc[path] || 0) + change.rhs - change.lhs;\n } else {\n merged.$set[path] = change.rhs;\n }\n}\n\nfunction handleArrayChange(merged, path, change) {\n if (change.item.kind === 'N') {\n merged.$push[path] = merged.$push[path] || [];\n if (!merged.$push[path].some(a => JSON.stringify(a) === JSON.stringify(change.item.rhs))) {\n merged.$push[path].push(change.item.rhs);\n }\n } else if (change.item.kind === 'D') {\n merged.$pull[path] = merged.$pull[path] || [];\n if (!merged.$pull[path].some(a => JSON.stringify(a) === JSON.stringify(change.item.lhs))) {\n merged.$pull[path].push(change.item.lhs);\n }\n }\n}\n\nexport function getDeepDiff(doc1, doc2) {\n\tdelete doc1._id;\n\tdelete doc1.__v;\n\n\tif (doc1.updatedAt) {\n\t\tdelete doc1.updatedAt;\n\t}\n\n\tif (doc1.createdAt) {\n\t\tdelete doc1.createdAt;\n\t}\n\n\tdelete doc2._id;\n\tdelete doc2.__v;\n\n\tif (doc2.updatedAt) {\n\t\tdelete doc2.updatedAt;\n\t}\n\n\tif (doc2.createdAt) {\n\t\tdelete doc2.createdAt;\n\t}\n\n\treturn deepDiff(doc1, doc2);\n}\n\nexport function applyMongoUpdate(uDoc: any, delta: any): any {\n const orig = deepCopy(uDoc);\n\n if (delta) {\n if (delta.$rename) handleRename(uDoc, delta.$rename);\n if (delta.$set) handleSet(uDoc, delta.$set);\n if (delta.$inc) handleInc(uDoc, delta.$inc);\n if (delta.$unset) handleUnset(uDoc, delta.$unset);\n if (delta.$pull) handlePull(uDoc, orig, delta.$pull);\n if (delta.$push) handlePush(uDoc, delta.$push);\n }\n\n return uDoc;\n}\n\nfunction handleRename(uDoc: any, renameMap: any) {\n for (const k in renameMap) {\n const v = renameMap[k];\n const [o1, n1] = resolve(uDoc, k);\n const [o2, n2] = resolve(uDoc, v);\n if (o1 && n1.length === 1) {\n if (o2 && n2.length === 1) {\n o2[n2[0]] = o1[n1[0]];\n delete o1[n1[0]];\n } else {\n logError(o2, n2, uDoc, v);\n }\n } else {\n logError(o1, n1, uDoc, k);\n }\n }\n}\n\nfunction handleSet(uDoc: any, setMap: any) {\n for (const k in setMap) {\n const v = setMap[k];\n const [o, n] = resolve(uDoc, k, { force: true });\n if (o && n.length === 1) {\n o[n[0]] = v;\n } else {\n logError(o, n, uDoc, k);\n }\n }\n}\n\nfunction handleInc(uDoc: any, incMap: any) {\n for (const k in incMap) {\n const v = incMap[k];\n const [o, n] = resolve(uDoc, k, { force: true });\n if (o && n.length === 1) {\n o[n[0]] = (o[n[0]] || 0) + v;\n } else {\n logError(o, n, uDoc, k);\n }\n }\n}\n\nfunction handleUnset(uDoc: any, unsetMap: any) {\n for (const k in unsetMap) {\n const [o, n] = resolve(uDoc, k);\n if (o && n.length === 1) {\n delete o[n[0]];\n } else {\n logError(o, n, uDoc, k);\n }\n }\n}\n\nfunction handlePull(uDoc: any, orig: any, pullMap: any) {\n for (const pathk in pullMap) {\n const pullValues = pullMap[pathk];\n for (let vk of pullValues) {\n const [o, n] = resolve(uDoc, pathk);\n const [o2, n2] = resolve(orig, pathk);\n if (o && n.length === 1) {\n o[n[0]].splice((<Array<any>>o2[n2[0]]).findIndex(z => JSON.stringify(z) === JSON.stringify(vk)), 1);\n } else {\n logError(o, n, uDoc, pathk);\n }\n }\n }\n}\n\nfunction handlePush(uDoc: any, pushMap: any) {\n for (const pathk in pushMap) {\n const pushValues = pushMap[pathk];\n for (let vk of pushValues) {\n const [o, n] = resolve(uDoc, pathk);\n if (o && n.length === 1) {\n o[n[0]].push(vk);\n } else {\n logError(o, n, uDoc, pathk);\n }\n }\n }\n}\n\nfunction logError(o: any, n: any, uDoc: any, key: any) {\n console.log('Error', o + '/' + n + ' - couldn\\'t resolve for ' + JSON.stringify(uDoc) + ' ' + key);\n}\n\nfunction resolve(a: any, path: string, options: any = {}): [any, any] {\n const stack = arrize(path);\n let last = [];\n\n if (stack.length > 0) {\n last.unshift(stack.pop());\n }\n\n let e = a;\n while (stack.length > 0) {\n const k = stack.shift();\n if (e[k] !== void 0) {\n e = e[k];\n } else {\n if (!options.force) {\n last.unshift(k);\n last = stack.concat(last);\n break;\n }\n const isNextNum = typeof stack[0] === 'number';\n const isLastNum = stack.length === 0 && typeof last[0] === 'number';\n e[k] = isNextNum || isLastNum ? [] : {};\n e = e[k];\n }\n }\n\n return [e, last];\n}\n\nfunction arrize(path: any, glue: string = '.'): string[] {\n if (Array.isArray(path)) {\n return path.slice();\n }\n\n if (path === void 0 || path === null || path === false || path === '') {\n return [];\n }\n\n return path.toString().split(glue)\n .map(e => {\n if ([void 0, null, false, ''].includes(e)) {\n return null;\n }\n return e.toString();\n })\n .filter(e => e !== null);\n}\n\nexport function deepDiffDetails(object1: Object, object2: Object): string {\n let obj1 = deepCopy(object1);\n\tlet obj2 = deepCopy(object2);\n\n\tlet diff = detailedDiff(obj1, obj2);\n\tlet diffString = '';\n\n\tconst formatValue = (value: any): string => {\n\t\tif (value instanceof Date) {\n\t\t\treturn moment(value).format('llll');\n\t\t} \n\t\telse if (typeof value === 'object' && value !== null) {\n\t\t\tObject.keys(value).filter(a => a.startsWith('_id') || a.startsWith('id_')).forEach(key => {\n\t\t\t\tdelete value[key];\n\t\t\t});\n\t\t\treturn JSON.stringify(value); // Pretty print objects\n\t\t} \n\t\telse {\n\t\t\treturn typeof value === 'string' ? `\"${value}\"` : String(value);\n\t\t}\n\t};\n\n\tconst customArrayDiff = (arr1: any[], arr2: any[]): string => {\n let arrayDiffResults = [];\n const maxLength = Math.max(arr1.length, arr2.length);\n\n for (let i = 0; i < maxLength; i++) {\n if (arr1[i] && !arr2[i]) {\n arrayDiffResults.push(`Removed at index ${i}: ${formatValue(arr1[i])}`);\n } \n\t\t\telse if (!arr1[i] && arr2[i]) {\n arrayDiffResults.push(`Added at index ${i}: ${formatValue(arr2[i])}`);\n } \n\t\t\telse if (arr1[i] && arr2[i] && JSON.stringify(arr1[i]) !== JSON.stringify(arr2[i])) {\n arrayDiffResults.push(`Changed at index ${i}: {${formatObjectDiff(arr1[i], arr2[i])}}`);\n }\n }\n\n return arrayDiffResults.join(', ');\n };\n\n\tconst formatObjectDiff = (obj1: any, obj2: any): string => {\n\t\tif (obj1 === null || obj2 === null || typeof obj1 !== 'object' || typeof obj2 !== 'object') {\n\t\t\treturn `from: ${formatValue(obj1)} to: ${formatValue(obj2)}`;\n\t\t}\n\n\t\tif (Array.isArray(obj1) || Array.isArray(obj2)) {\n\t\t\treturn customArrayDiff(Array.isArray(obj1) ? obj1 : [], Array.isArray(obj2) ? obj2 : []);\n\t\t}\n\n\t\treturn Object.keys({...obj1, ...obj2}).filter(a => !a.startsWith('_id') && !a.startsWith('id_')).map(key => {\n\t\t\tconst obj1Val = obj1 ? obj1[key] : undefined;\n\t\t\tconst obj2Val = obj2 ? obj2[key] : undefined;\n\t\t\treturn `${toTitleCase(key)}: ${formatObjectDiff(obj1Val, obj2Val)}`;\n\t\t}).join(', ');\n\t};\n\n\t// Handle each diff type\n\t['added', 'deleted', 'updated'].forEach(diffType => {\n\t\tif (Object.keys(diff[diffType]).length > 0) {\n\t\t\tconst updates = Object.keys(diff[diffType])\n\t\t\t\t.filter(key => diffType === 'added' ? true : (diffType === 'deleted' ? !diff['added'][key] : !diff['added'][key] && !diff['deleted'][key]))\n\t\t\t\t.filter(key => !key.startsWith('_id') && !key.startsWith('id_'))\n\t\t\t\t.map(key => `\\n${toTitleCase(key)}: ${formatObjectDiff(obj1[key], obj2[key])}`)\n\t\t\t\t.join(',');\n\n\t\t\tdiffString += updates ? `${updates}` : '';\n\t\t}\n\t});\n\n\treturn diffString;\n}\n\nexport function getBinarySize(string) {\n\tif (string) {\n\t\treturn Buffer.byteLength(string, 'utf8');\n\t}\n\telse {\n\t\treturn 0;\n\t}\n}\n\nexport function pad(num, size) {\n\tlet s = num + '';\n\twhile (s.length < size) { s = '0' + s; }\n\treturn s;\n}\n\nexport function randomString(length, chars) {\n\tlet result = '';\n\tfor (let i = length; i > 0; --i) { result += chars[Math.floor(Math.random() * chars.length)]; }\n\treturn result;\n}\n\nexport function toTitleCase(str) {\n\treturn str.replace(/\\w\\S*/g, function(txt){\n\t\treturn txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();\n\t});\n}\n\nexport function isObject(item) {\n\treturn (item && typeof item === 'object' && !Array.isArray(item));\n}\n\nexport function mergeDeep(target, ...sources) {\n\tif (!sources.length) {\n\t\treturn target;\n\t}\n\tconst source = sources.shift();\n\n\tif (isObject(target) && isObject(source)) {\n\t\tfor (const key in source) {\n\t\t\tif (isObject(source[key])) {\n\t\t\t\tif (!target[key]) {\n\t\t\t\t\tObject.assign(target, { [key]: {} });\n\t\t\t\t}\n\t\t\t\tmergeDeep(target[key], source[key]);\n\t\t\t} \n\t\t\telse {\n\t\t\t\tObject.assign(target, { [key]: source[key] });\n\t\t\t}\n\t\t}\n\t}\n\n\treturn mergeDeep(target, ...sources);\n}"]}