@resolveio/server-lib 20.4.81 → 20.4.82
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.
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var __extends=this&&this.__extends||function(){var t=function(e,n){return(t=Object.setPrototypeOf||({__proto__:[]}instanceof Array?function(e,n){e.__proto__=n}:function(e,n){for(var t in n)Object.prototype.hasOwnProperty.call(n,t)&&(e[t]=n[t])}))(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function __(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(__.prototype=n.prototype,new __)}}(),__assign=this&&this.__assign||function(){return(__assign=Object.assign||function(e){for(var n,t=1,o=arguments.length;t<o;t++)for(var i in n=arguments[t])Object.prototype.hasOwnProperty.call(n,i)&&(e[i]=n[i]);return e}).apply(this,arguments)},__awaiter=this&&this.__awaiter||function(e,o,i,r){return new(i=i||Promise)(function(t,n){function fulfilled(e){try{step(r.next(e))}catch(e){n(e)}}function rejected(e){try{step(r.throw(e))}catch(e){n(e)}}function step(e){var n;e.done?t(e.value):((n=e.value)instanceof i?n:new i(function(e){e(n)})).then(fulfilled,rejected)}step((r=r.apply(e,o||[])).next())})},__generator=this&&this.__generator||function(o,i){var r,a,s,c={label:0,sent:function(){if(1&s[0])throw s[1];return s[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(t){return function(e){var n=[t,e];if(r)throw new TypeError("Generator is already executing.");for(;c=l&&n[l=0]?0:c;)try{if(r=1,a&&(s=2&n[0]?a.return:n[0]?a.throw||((s=a.return)&&s.call(a),0):a.next)&&!(s=s.call(a,n[1])).done)return s;switch(a=0,(n=s?[2&n[0],s.value]:n)[0]){case 0:case 1:s=n;break;case 4:return c.label++,{value:n[1],done:!1};case 5:c.label++,a=n[1],n=[0];continue;case 7:n=c.ops.pop(),c.trys.pop();continue;default:if(!(s=0<(s=c.trys).length&&s[s.length-1])&&(6===n[0]||2===n[0])){c=0;continue}if(3===n[0]&&(!s||n[1]>s[0]&&n[1]<s[3]))c.label=n[1];else if(6===n[0]&&c.label<s[1])c.label=s[1],s=n;else{if(!(s&&c.label<s[2])){s[2]&&c.ops.pop(),c.trys.pop();continue}c.label=s[2],c.ops.push(n)}}n=i.call(o,c)}catch(e){n=[6,e],a=0}finally{r=s=0}if(5&n[0])throw n[1];return{value:n[0]?n[1]:void 0,done:!0}}}},__read=this&&this.__read||function(e,n){var t="function"==typeof Symbol&&e[Symbol.iterator];if(!t)return e;var o,i,r=t.call(e),a=[];try{for(;(void 0===n||0<n--)&&!(o=r.next()).done;)a.push(o.value)}catch(e){i={error:e}}finally{try{o&&!o.done&&(t=r.return)&&t.call(r)}finally{if(i)throw i.error}}return a},__spreadArray=this&&this.__spreadArray||function(e,n,t){if(t||2===arguments.length)for(var o,i=0,r=n.length;i<r;i++)!o&&i in n||((o=o||Array.prototype.slice.call(n,0,i))[i]=n[i]);return e.concat(o||Array.prototype.slice.call(n))},__values=this&&this.__values||function(e){var n="function"==typeof Symbol&&Symbol.iterator,t=n&&e[n],o=0;if(t)return t.call(e);if(e&&"number"==typeof e.length)return{next:function(){return{value:(e=e&&o>=e.length?void 0:e)&&e[o++],done:!e}}};throw new TypeError(n?"Object is not iterable.":"Symbol.iterator is not defined.")},simpl_schema_1=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.objectIdHexString=exports.MongoManagerUserCollection=exports.MongoManagerCollection=exports.MongoManagerModel=exports.MongoManager=void 0,require("simpl-schema")),mongodb_1=require("mongodb"),index_1=require("../index"),user_collection_1=require("../collections/user.collection"),common_1=require("../util/common"),NodeCache=require("node-cache"),crypto=require("crypto"),scmp=require("scmp"),monitor_manager_1=require("./monitor.manager"),os_1=require("os"),numCPUs=(0,os_1.cpus)().length,v8=require("v8"),async_1=require("async"),MongoManager=function(){function MongoManager(e){this._collections=[],this._cacheMap=[],this._operationInProgress=new Map,this._heapSize=v8.getHeapStatistics()/numCPUs,this._serverCollections=[],this._serverConfig=null,this._isWorkersEnabled=!1,this._isWorkerInstance=!1,this._serverConfig=e,this._nodeCache=new NodeCache({stdTTL:0,checkperiod:0}),this._isWorkersEnabled="true"===process.env.IS_WORKERS_ENABLED,this._isWorkerInstance="true"===process.env.IS_WORKER_INSTANCE,this.setCacheLimit(),this.initServerCollections(),this._isWorkersEnabled&&this._isWorkerInstance&&this.setupChangeStream()}return MongoManager.prototype.setCacheLimit=function(){this._isWorkersEnabled?this._heapLimit=this._isWorkerInstance?.8*this._heapSize:.4*this._heapSize:this._heapLimit=.3*this._heapSize},MongoManager.prototype.initServerCollections=function(){return __awaiter(this,void 0,void 0,function(){var n;return __generator(this,function(e){switch(e.label){case 0:return[4,index_1.ResolveIOServer.getMainDB().listCollections().toArray()];case 1:return n=e.sent(),this._serverCollections=n,[2]}})})},MongoManager.prototype.getServerCollections=function(){return this._serverCollections},MongoManager.prototype.registerCollection=function(n){var e=this;n.collectionOptions&&n.collectionOptions.timeseries&&n.collectionOptions.timeseries.timeField&&this._serverCollections.some(function(e){return e.name===n.collectionName&&"collection"===e.type})&&index_1.ResolveIOServer.getMainDB().dropCollection(n.collectionName).then(function(){e.createCollection(n)}),this._collections.push(n)},MongoManager.prototype.createCollection=function(e){index_1.ResolveIOServer.getMainDB().createCollection(e.collectionName,e.collectionOptions)},MongoManager.prototype.collections=function(){return this._collections},MongoManager.prototype.collection=function(n){return this._collections.find(function(e){return e.collectionName===n})},MongoManager.prototype.delay=function(n){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(e){return[2,new Promise(function(e){return setTimeout(e,n)})]})})},MongoManager.prototype.find=function(i,r,a){return void 0===r&&(r={}),__awaiter(this,void 0,void 0,function(){var n,t,o=this;return __generator(this,function(e){return n=this.generateCacheKey([i],"find",[r,a]),void 0!==(t=this.getFromCache(n))?(index_1.ResolveIOServer.getMainServer().getSubscriptionManager()&&index_1.ResolveIOServer.getMainServer().getSubscriptionManager().getEnableDebug()&&console.log(new Date,"Mongo Find - Cache",i),[2,t]):this._operationInProgress.has(n)?(index_1.ResolveIOServer.getMainServer().getSubscriptionManager()&&index_1.ResolveIOServer.getMainServer().getSubscriptionManager().getEnableDebug()&&console.log(new Date,"Mongo Find - Already running",i),[2,this._operationInProgress.get(n).promise]):(index_1.ResolveIOServer.getMainServer().getSubscriptionManager()&&index_1.ResolveIOServer.getMainServer().getSubscriptionManager().getEnableDebug()&&console.log(new Date,"Mongo Find - Running",i),t=this.executeFind(i,r,a,n),this._operationInProgress.set(n,{promise:t,invalidatedDuringExecution:!1,collections:[i]}),t.finally(function(){index_1.ResolveIOServer.getMainServer().getSubscriptionManager()&&index_1.ResolveIOServer.getMainServer().getSubscriptionManager().getEnableDebug()&&console.log(new Date,"Mongo Find - Done",i),o._operationInProgress.delete(n)}),[2,t])})})},MongoManager.prototype.executeFind=function(o,i,r,a){return __awaiter(this,void 0,void 0,function(){var n,t;return __generator(this,function(e){switch(e.label){case 0:return n=index_1.ResolveIOServer.getMainDB().collection(o),t=new monitor_manager_1.MonitorMongo("find",o,JSON.stringify([i,r])),[4,n.find(i,r).toArray()];case 1:return n=e.sent(),t.finish(),this._operationInProgress.get(a).invalidatedDuringExecution||this.addToCache([o],a,n),[2,n]}})})},MongoManager.prototype.findOne=function(i,r,a){return void 0===r&&(r={}),__awaiter(this,void 0,void 0,function(){var n,t,o=this;return __generator(this,function(e){return n=this.generateCacheKey([i],"findOne",[r,a]),void 0!==(t=this.getFromCache(n))?(index_1.ResolveIOServer.getMainServer().getSubscriptionManager()&&index_1.ResolveIOServer.getMainServer().getSubscriptionManager().getEnableDebug()&&console.log(new Date,"Mongo FindOne - Cache",i),[2,t]):this._operationInProgress.has(n)?(index_1.ResolveIOServer.getMainServer().getSubscriptionManager()&&index_1.ResolveIOServer.getMainServer().getSubscriptionManager().getEnableDebug()&&console.log(new Date,"Mongo FindOne - Already running",i),[2,this._operationInProgress.get(n).promise]):(index_1.ResolveIOServer.getMainServer().getSubscriptionManager()&&index_1.ResolveIOServer.getMainServer().getSubscriptionManager().getEnableDebug()&&console.log(new Date,"Mongo FindOne - Running",i),t=this.executeFindOne(i,r,a,n),this._operationInProgress.set(n,{promise:t,invalidatedDuringExecution:!1,collections:[i]}),t.finally(function(){index_1.ResolveIOServer.getMainServer().getSubscriptionManager()&&index_1.ResolveIOServer.getMainServer().getSubscriptionManager().getEnableDebug()&&console.log(new Date,"Mongo FindOne - Done",i),o._operationInProgress.delete(n)}),[2,t])})})},MongoManager.prototype.executeFindOne=function(o,i,r,a){return __awaiter(this,void 0,void 0,function(){var n,t;return __generator(this,function(e){switch(e.label){case 0:return n=index_1.ResolveIOServer.getMainDB().collection(o),t=new monitor_manager_1.MonitorMongo("findOne",o,JSON.stringify([i,r])),[4,n.findOne(i,r)];case 1:return n=e.sent(),t.finish(),this._operationInProgress.get(a).invalidatedDuringExecution||this.addToCache([o],a,n),[2,n]}})})},MongoManager.prototype.aggregate=function(r,a,s){return __awaiter(this,void 0,void 0,function(){var n,t,o,i=this;return __generator(this,function(e){return n=__spreadArray([r],__read(a.flatMap(function(e){var n;return null!=(n=e.$lookup)&&n.from?[e.$lookup.from]:[]})),!1),t=this.generateCacheKey(n,"aggregate",[a,s]),void 0!==(o=this.getFromCache(t))?(index_1.ResolveIOServer.getMainServer().getSubscriptionManager()&&index_1.ResolveIOServer.getMainServer().getSubscriptionManager().getEnableDebug()&&console.log(new Date,"Mongo Agg - Cache",n),[2,o]):this._operationInProgress.has(t)?(index_1.ResolveIOServer.getMainServer().getSubscriptionManager()&&index_1.ResolveIOServer.getMainServer().getSubscriptionManager().getEnableDebug()&&console.log(new Date,"Mongo Agg - Already running",n),[2,this._operationInProgress.get(t).promise]):(index_1.ResolveIOServer.getMainServer().getSubscriptionManager()&&index_1.ResolveIOServer.getMainServer().getSubscriptionManager().getEnableDebug()&&console.log(new Date,"Mongo Agg - Running",n),o=this.executeAggregate(r,a,s,t,n),this._operationInProgress.set(t,{promise:o,invalidatedDuringExecution:!1,collections:n}),o.finally(function(){index_1.ResolveIOServer.getMainServer().getSubscriptionManager()&&index_1.ResolveIOServer.getMainServer().getSubscriptionManager().getEnableDebug()&&console.log(new Date,"Mongo Agg - Done",n),i._operationInProgress.delete(t)}),[2,o])})})},MongoManager.prototype.executeAggregate=function(o,i,r,a,s){return __awaiter(this,void 0,void 0,function(){var n,t;return __generator(this,function(e){switch(e.label){case 0:return n=index_1.ResolveIOServer.getMainDB().collection(o),t=new monitor_manager_1.MonitorMongo("aggregate",o,JSON.stringify([i,r])),[4,n.aggregate(i,r).toArray()];case 1:return n=e.sent(),t.finish(),this._operationInProgress.get(a).invalidatedDuringExecution||this.addToCache(s,a,n),[2,n]}})})},MongoManager.prototype.countDocuments=function(i,r,a){return void 0===r&&(r={}),__awaiter(this,void 0,void 0,function(){var n,t,o=this;return __generator(this,function(e){return n=this.generateCacheKey([i],"countDocuments",[r,a]),void 0!==(t=this.getFromCache(n))?[2,t]:this._operationInProgress.has(n)?[2,this._operationInProgress.get(n).promise]:(t=this.executeCountDocuments(i,r,a,n),this._operationInProgress.set(n,{promise:t,invalidatedDuringExecution:!1,collections:[i]}),t.finally(function(){return o._operationInProgress.delete(n)}),[2,t])})})},MongoManager.prototype.executeCountDocuments=function(o,i,r,a){return __awaiter(this,void 0,void 0,function(){var n,t;return __generator(this,function(e){switch(e.label){case 0:return n=index_1.ResolveIOServer.getMainDB().collection(o),t=new monitor_manager_1.MonitorMongo("countDocuments",o,JSON.stringify([i,r])),[4,n.countDocuments(i,r)];case 1:return n=e.sent(),t.finish(),this._operationInProgress.get(a).invalidatedDuringExecution||this.addToCache([o],a,n),[2,n]}})})},MongoManager.prototype.generateCacheKey=function(e,n,t){e=JSON.stringify({collections:e,functionName:n,args:t});return crypto.createHash("sha256").update(e).digest("hex")},MongoManager.prototype.getFromCache=function(n){try{var e=this._nodeCache.get(n);if(e)return JSON.parse(e,common_1.dateReviver)}catch(e){this._nodeCache.del(n)}},MongoManager.prototype.addToCache=function(e,n,t){var o,i;if((0,common_1.getBinarySize)(JSON.stringify(t))<1e6&&!e.includes("logs")&&!e.includes("log-method-latencies")&&!e.includes("log-subscriptions")&&!e.find(function(e){return e.endsWith(".versions")})&&!e.find(function(e){return e.startsWith("monitor-")})){var r=this._nodeCache.getStats().vsize;if(r>this._heapLimit){var a=0,s=this._nodeCache.keys();try{for(var c=__values(s),l=c.next();!l.done;l=c.next()){var d=l.value;if(this._nodeCache.del(d),a+=1,(r=this._nodeCache.getStats().vsize)<.75*this._heapLimit)break}}catch(e){o={error:e}}finally{try{l&&!l.done&&(i=c.return)&&i.call(c)}finally{if(o)throw o.error}}console.log("Query Cache: Too Big, - Deleted: "+a+" - "+r)}this._nodeCache.set(n,JSON.stringify(t)),this._cacheMap.push({collections:e,key:n})}},MongoManager.prototype.invalidateQueryCache=function(n){var t,e,o,i,r=this._cacheMap.filter(function(e){return e.collections.includes(n)});index_1.ResolveIOServer.getMainServer().getSubscriptionManager()&&index_1.ResolveIOServer.getMainServer().getSubscriptionManager().getEnableDebug()&&console.log(new Date,"Mongo Invalidate Cache",n);try{for(var a=__values(r),s=a.next();!s.done;s=a.next()){var c=s.value;this._nodeCache.del(c.key),this._operationInProgress.has(c.key)&&(this._operationInProgress.get(c.key).invalidatedDuringExecution=!0,index_1.ResolveIOServer.getMainServer().getSubscriptionManager())&&index_1.ResolveIOServer.getMainServer().getSubscriptionManager().getEnableDebug()&&console.log(new Date,"Mongo Invalidated During Execution",c.collections)}}catch(e){t={error:e}}finally{try{s&&!s.done&&(e=a.return)&&e.call(a)}finally{if(t)throw t.error}}try{for(var l=__values(this._operationInProgress.entries()),d=l.next();!d.done;d=l.next()){var g=__read(d.value,2),u=(g[0],g[1]);u.collections.includes(n)&&(u.invalidatedDuringExecution=!0,index_1.ResolveIOServer.getMainServer().getSubscriptionManager())&&index_1.ResolveIOServer.getMainServer().getSubscriptionManager().getEnableDebug()&&console.log(new Date,"Mongo Invalidated During Execution (No cache)",u.collections)}}catch(e){o={error:e}}finally{try{d&&!d.done&&(i=l.return)&&i.call(l)}finally{if(o)throw o.error}}this._cacheMap=this._cacheMap.filter(function(e){return!e.collections.includes(n)})},MongoManager.prototype.setupChangeStream=function(){var n=this,t=index_1.ResolveIOServer.getMainDB().watch([{$match:{$and:[{"ns.coll":{$nin:["logs","log-method-latencies","log-subscriptions"]}},{"ns.coll":{$not:/.*\.versions$/}},{"ns.coll":{$not:/^monitor-/}}]}}],{fullDocument:"updateLookup"});t.on("change",function(t){return __awaiter(n,void 0,void 0,function(){var n;return __generator(this,function(e){return t.ns&&t.ns.coll&&(n=t.ns.coll,this.collection(n))&&this.invalidateQueryCache(n),[2]})})}),t.on("error",function(e){console.log(new Date,"Mongo change stream error. Restart..."),t.close(),setTimeout(function(){return n.setupChangeStream()},5e3)}),t.on("close",function(){console.log(new Date,"Mongo change stream closed. Restarting..."),setTimeout(function(){return n.setupChangeStream()},5e3)})},MongoManager}(),MongoManagerModel=(exports.MongoManager=MongoManager,function(e){var n;this.collection_main=null,this.collection_version=null,"users"===e.collectionName?this.collection_main=new MongoManagerUserCollection(e):this.collection_main=new MongoManagerCollection(e),e.useVersionCollection&&(this.collection_main.useVersions=!0,(n=(0,common_1.deepCopy)(e.schema))._id.type="Object",n._id.blackbox=!0,n={collectionName:e.collectionName+".versions",schema:n,useVersionCollection:!1,useReportBuilder:!1,reportBuilderLookupTables:[],timestamps:!0,createLogs:!1,checkSchema:!1,collectionOptions:null},"users"===e.collectionName?this.collection_version=new MongoManagerUserCollection(n):this.collection_version=new MongoManagerCollection(n),this.collection_version.createIndex({"_id._id":1,"_id.__v":1}),this.collection_main.versionCollection=e.collectionName+".versions")}),MongoManagerCollection=(exports.MongoManagerModel=MongoManagerModel,function(){function MongoManagerCollection(e){var n,t=this,o=(this.collectionName="",this.checkSchema=!1,this.simplschema=null,this.rbSchema=null,this.timestamps=!1,this.useVersions=!1,this.versionCollection="",this.createLogs=!0,this.useRB=!1,this.collectionName=e.collectionName,this.simplschema=new simpl_schema_1.default(e.schema),this.timestamps=e.timestamps,this.createLogs=e.createLogs,this.checkSchema=e.checkSchema,this.collectionOptions=e.collectionOptions,e.useReportBuilder&&(this.useRB=!0,n=(0,common_1.deepCopy)(e.schema),e=(0,common_1.buildRbLookups)(e.reportBuilderLookupTables,n,[]),this.rbSchema=(0,common_1.buildRbSchema)(e)),setInterval(function(){index_1.ResolveIOServer&&index_1.ResolveIOServer.getMainServer()&&index_1.ResolveIOServer.getMongoManager()&&index_1.ResolveIOServer.getMongoManager().getServerCollections().length&&(index_1.ResolveIOServer.getMongoManager().registerCollection(t),clearInterval(o))},1))}var e;return MongoManagerCollection.prototype.extractIndexNameFromError=function(e){var n=e.match(/Index already exists with a different name: (\S+)/);return(n=!n||n.length<=1?e.match(/existing index:.*name: "([^"]+)"/):n)&&1<n.length?n[1]:null},MongoManagerCollection.prototype.aggregate=function(i,r,e){var a=this;return void 0===e&&(e=!1),new Promise(function(n,t){var o;e?(o=new monitor_manager_1.MonitorMongo("aggregate",a.collectionName,JSON.stringify([i,r])),index_1.ResolveIOServer.getMainDB().collection(a.collectionName,a.collectionOptions).aggregate(i,r).toArray().then(function(e){o.finish(),n(e)},function(e){o.finish(),console.log(new Date,"Error Aggregate",a.collectionName,i,r,e),t(e)})):index_1.ResolveIOServer.getMongoManager().aggregate(a.collectionName,i,r).then(function(e){n(e)},function(e){t(e)})})},MongoManagerCollection.prototype.aggregateCount=function(r,a){return __awaiter(this,void 0,void 0,function(){var i=this;return __generator(this,function(e){return[2,new Promise(function(n,t){var o=new monitor_manager_1.MonitorMongo("aggregateCount",i.collectionName,JSON.stringify([r,a]));index_1.ResolveIOServer.getMainDB().collection(i.collectionName,i.collectionOptions).aggregate(r,a).toArray().then(function(e){o.finish(),n(e.length)},function(e){o.finish(),console.log(new Date,"Error Aggregate",i.collectionName,r,a,e),t(0)})})]})})},MongoManagerCollection.prototype.aggregateCursor=function(e,n){var t=new monitor_manager_1.MonitorMongo("aggregateCursor",this.collectionName,JSON.stringify([e,n])),e=index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).aggregate(e,n);return e.on("close",function(e){return t.finish(),e}),e},MongoManagerCollection.prototype.aggregateStream=function(e,n,t){var o=new monitor_manager_1.MonitorMongo("aggregateStream",this.collectionName,JSON.stringify([e,n,t])),e=index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).aggregate(e,n).stream(t);return e.on("end",function(e){return o.finish(),e}).on("error",function(e){return o.finish(),e}).on("close",function(e){return o.finish(),e}),e},MongoManagerCollection.prototype.bulkWrite=function(y,I,w,x,N){return void 0===w&&(w=!1),void 0===x&&(x=!1),void 0===N&&(N=!1),__awaiter(this,void 0,void 0,function(){var n,t,o,i,r,a,s,c,l,d,g,u,_,h,v,m,f,p,M,O,S;return __generator(this,function(e){switch(e.label){case 0:if(!y.length)return[2,null];n=1e3,t=0,e.label=1;case 1:if(!(t<y.length))return[3,18];o=y.slice(t,t+n),i=[],r=[];try{for(O=void 0,a=__values(o),s=a.next();!s.done;s=a.next()){if(c=s.value,l=Object.keys(c)[0],d=c[l],this.checkSchema&&!w){if(g=this.simplschema.newContext(),u=void 0,"insertOne"===l)u=g.validate(d.document);else if("replaceOne"===l)u=g.validate(d.replacement);else if("updateOne"===l||"updateMany"===l)u=g.validate(d.update,{modifier:!0});else{if("deleteOne"!==l&&"deleteMany"!==l)throw new Error("Unsupported operation type: ".concat(l));u=!0}if(!u)throw new Error("Schema validation failed for ".concat(l,": ").concat(JSON.stringify(g.validationErrors())))}if("insertOne"===l)this.timestamps&&(d.document.createdAt=new Date,d.document.updatedAt=new Date),!x&&this.createLogs&&i.push({insertOne:{document:{_id:objectIdHexString(),type:"document",collection:this.collectionName,id_document:d.document._id||objectIdHexString(),payload:(0,common_1.getBinarySize)(JSON.stringify(d.document))<2e5?JSON.stringify(d.document,null,2):"Too Big",method:"insertOne",id_user:"",user:"",messageId:0,route:"",createdAt:new Date}}}),!N&&this.useVersions&&(_=__assign(__assign({},d.document),{__v:0,_id:{_id:d.document._id||objectIdHexString(),__v:0}}),r.push({insertOne:{document:_}})),c[l].document=d.document;else if("updateOne"===l||"updateMany"===l)this.timestamps&&(d.update.$set||(d.update.$set={}),d.update.$set.updatedAt=new Date),!N&&this.useVersions&&(d.update.$inc||(d.update.$inc={}),d.update.$inc.__v=1),!x&&this.createLogs&&i.push({insertOne:{document:{_id:objectIdHexString(),type:"document",collection:this.collectionName,id_document:d.filter._id||null,payload:(0,common_1.getBinarySize)(JSON.stringify(d.update))<2e5?JSON.stringify(d.update,null,2):"Too Big",method:l,id_user:"",user:"",messageId:0,route:"",createdAt:new Date}}}),!N&&this.useVersions&&r.push({filter:d.filter});else if("replaceOne"===l)this.timestamps&&(d.replacement.updatedAt=new Date),!N&&this.useVersions&&(d.replacement.__v=(d.replacement.__v||0)+1),!x&&this.createLogs&&i.push({insertOne:{document:{_id:objectIdHexString(),type:"document",collection:this.collectionName,id_document:d.filter._id||null,payload:(0,common_1.getBinarySize)(JSON.stringify(d.replacement))<2e5?JSON.stringify(d.replacement,null,2):"Too Big",method:"replaceOne",id_user:"",user:"",messageId:0,route:"",createdAt:new Date}}}),!N&&this.useVersions&&r.push({filter:d.filter}),c[l].replacement=d.replacement;else{if("deleteOne"!==l&&"deleteMany"!==l)throw new Error("Unsupported operation type: ".concat(l));!x&&this.createLogs&&i.push({insertOne:{document:{_id:objectIdHexString(),type:"document",collection:this.collectionName,id_document:d.filter._id||null,payload:(0,common_1.getBinarySize)(JSON.stringify(d.filter))<2e5?JSON.stringify(d.filter,null,2):"Too Big",method:l,id_user:"",user:"",messageId:0,route:"",createdAt:new Date}}}),!N&&this.useVersions&&r.push({filter:d.filter})}}}catch(e){O={error:e}}finally{try{s&&!s.done&&(S=a.return)&&S.call(a)}finally{if(O)throw O.error}}if(h=[],!(!N&&this.useVersions&&0<r.length))return[3,7];e.label=2;case 2:return e.trys.push([2,6,,7]),v=r.map(function(e){return e.filter}),[4,index_1.ResolveIOServer.getMainDB().collection(this.collectionName).find({$or:v}).toArray()];case 3:return(h=e.sent(),0<(v=h.map(function(e){return{insertOne:{document:__assign(__assign({},e),{_id:{_id:e._id,__v:e.__v}})}}})).length)?[4,index_1.ResolveIOServer.getMainDB().collection(this.versionCollection).bulkWrite(v,{ordered:!1})]:[3,5];case 4:e.sent(),e.label=5;case 5:return[3,7];case 6:return f=e.sent(),console.error("Error during version creation:",f),[3,7];case 7:return m=new monitor_manager_1.MonitorMongo("bulkWrite",this.collectionName,JSON.stringify([o,I])),[4,index_1.ResolveIOServer.getMainDB().collection(this.collectionName).bulkWrite(o,I)];case 8:return(e.sent(),m.finish(),!x&&this.createLogs&&0<i.length)?[4,index_1.ResolveIOServer.getMainDB().collection("logs").bulkWrite(i)]:[3,10];case 9:e.sent(),e.label=10;case 10:if(N||!this.useVersions)return[3,16];e.label=11;case 11:return e.trys.push([11,15,,16]),f=h.map(function(e){return e._id}),p=[{$match:{"_id._id":{$in:f}}},{$sort:{"_id._id":1,"_id.__v":-1}},{$group:{_id:"$_id._id",versions:{$push:"$_id"}}},{$project:{versionsToDelete:{$slice:["$versions",5,{$size:"$versions"}]}}},{$unwind:"$versionsToDelete"},{$replaceRoot:{newRoot:{_id:"$versionsToDelete"}}}],[4,index_1.ResolveIOServer.getMainDB().collection(this.versionCollection).aggregate(p).toArray()];case 12:return 0<(p=e.sent()).length?[4,index_1.ResolveIOServer.getMainDB().collection(this.versionCollection).deleteMany({_id:{$in:p.map(function(e){return e._id})}})]:[3,14];case 13:e.sent(),e.label=14;case 14:return[3,16];case 15:return M=e.sent(),console.error("Error during version cleanup:",M),[3,16];case 16:return t+=n,[4,new Promise(function(e){return setImmediate(e)})];case 17:return e.sent(),index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(this.collectionName),[3,1];case 18:return[2,{ok:1}]}})})},MongoManagerCollection.prototype.countDocuments=function(a,s,c){var e=this;return void 0===a&&(a={}),void 0===c&&(c=!1),new Promise(function(i,r){return __awaiter(e,void 0,void 0,function(){var n,t,o=this;return __generator(this,function(e){switch(e.label){case 0:return(e.trys.push([0,4,,5]),0===Object.keys(a).length)?[4,index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).estimatedDocumentCount(s)]:[3,2];case 1:return t=e.sent(),i(t),[3,3];case 2:c?(n=new monitor_manager_1.MonitorMongo("countDocuments",this.collectionName,JSON.stringify([a,s])),index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).countDocuments(a,s).then(function(e){n.finish(),i(e)},function(e){n.finish(),console.log(new Date,"Error Count Documents",o.collectionName,a,s,e),r(e)})):index_1.ResolveIOServer.getMongoManager().countDocuments(this.collectionName,a,s).then(function(e){return i(e)},function(e){return r(e)}),e.label=3;case 3:return[3,5];case 4:return t=e.sent(),console.log(new Date,"Error Count Documents (Stats)",this.collectionName,a,s,t),r(t),[3,5];case 5:return[2]}})})})},MongoManagerCollection.prototype.create=function(e,n){return Array.isArray(e)?1===e.length?this.insertOne(e[0],n):this.insertMany(e,n):this.insertOne(e,n)},MongoManagerCollection.prototype.createIndex=function(i,r){var e=this;return new Promise(function(t,o){return __awaiter(e,void 0,void 0,function(){var n;return __generator(this,function(e){switch(e.label){case 0:return e.trys.push([0,2,,3]),[4,index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).indexes()];case 1:return(n=e.sent(),n.some(function(e){return JSON.stringify(e.key)===JSON.stringify(i)}))?[2,t("Index already exists")]:(MongoManagerCollection.indexQueue.push({action:"createIndex",collection:this,specs:[i],options:r},function(e,n){e?o(e):t(n)}),[3,3]);case 2:return n=e.sent(),o(n),[3,3];case 3:return[2]}})})})},MongoManagerCollection.prototype.createIndexes=function(r,a){var e=this;return new Promise(function(o,i){return __awaiter(e,void 0,void 0,function(){var t,n;return __generator(this,function(e){switch(e.label){case 0:return e.trys.push([0,2,,3]),[4,index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).indexes()];case 1:return(t=e.sent(),0===(n=r.filter(function(n){return!t.some(function(e){return JSON.stringify(e.key)===JSON.stringify(n.key)})})).length)?[2,o(["All indexes already exist"])]:(MongoManagerCollection.indexQueue.push({action:"createIndexes",collection:this,specs:[n],options:a},function(e,n){e?i(e):o(n)}),[3,3]);case 2:return n=e.sent(),i(n),[3,3];case 3:return[2]}})})})},MongoManagerCollection.prototype.deleteMany=function(l,d,g){var e=this;return void 0===l&&(l={}),void 0===g&&(g=!1),new Promise(function(s,c){return __awaiter(e,void 0,void 0,function(){var n,t,o,i,r,a=this;return __generator(this,function(e){switch(e.label){case 0:return!this.createLogs||g?[3,2]:[4,this.find(l)];case 1:for(n=e.sent(),t=0;t<n.length;t++)o=n[t],index_1.ResolveIOServer.getMainDB().collection("logs").insertOne({_id:objectIdHexString(),type:"document",collection:this.collectionName,id_document:o._id,payload:(0,common_1.getBinarySize)(JSON.stringify([o,l,d]))<2e5?JSON.stringify([o,l,d],null,2):"Too Big",method:"deleteMany",id_user:"",user:"",messageId:0,route:"",createdAt:new Date}),this.useVersions&&((i=(0,common_1.deepCopy)(o))._id={_id:o._id,__v:o.__v},index_1.ResolveIOServer.getMongoManager().collection(this.versionCollection).replaceOne({_id:{_id:o._id,__v:o.__v}},i,{upsert:!0}),index_1.ResolveIOServer.getMongoManager().collection(this.versionCollection).deleteMany({$and:[{"_id._id":o._id},{"_id.__v":{$lt:o.__v-1}}]}));e.label=2;case 2:return r=new monitor_manager_1.MonitorMongo("deleteMany",this.collectionName,JSON.stringify([l,d])),index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).deleteMany(l,d).then(function(e){r.finish(),e.acknowledged?(index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(a.collectionName),s(e.deletedCount)):c(e.acknowledged)},function(e){r.finish(),console.log(new Date,"Error Delete Many",a.collectionName,l,d,e),c(e)}),[2]}})})})},MongoManagerCollection.prototype.deleteOne=function(a,s,c){var e=this;return void 0===a&&(a={}),void 0===c&&(c=!1),new Promise(function(r,o){return __awaiter(e,void 0,void 0,function(){var i,n,t=this;return __generator(this,function(e){return this.createLogs&&!c?(i=new monitor_manager_1.MonitorMongo("findOneAndDelete",this.collectionName,JSON.stringify([a,s])),index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).findOneAndDelete(a,s).then(function(o){return __awaiter(t,void 0,void 0,function(){var n,t;return __generator(this,function(e){return i.finish(),(n=o.value)?(this.createLogs&&!c&&index_1.ResolveIOServer.getMainDB().collection("logs").insertOne({_id:objectIdHexString(),type:"document",collection:this.collectionName,id_document:n._id,payload:(0,common_1.getBinarySize)(JSON.stringify([n,a,s]))<2e5?JSON.stringify([n,a,s],null,2):"Too Big",method:"deleteOne",id_user:"",user:"",messageId:0,route:"",createdAt:new Date}),this.useVersions&&((t=(0,common_1.deepCopy)(n))._id={_id:n._id,__v:n.__v},index_1.ResolveIOServer.getMongoManager().collection(this.versionCollection).replaceOne({_id:{_id:n._id,__v:n.__v}},t,{upsert:!0}),index_1.ResolveIOServer.getMongoManager().collection(this.versionCollection).deleteMany({$and:[{"_id._id":n._id},{"_id.__v":{$lt:n.__v-1}}]})),index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(this.collectionName),r(1)):r(0),[2]})})},function(e){i.finish(),console.log(new Date,"Error Find One And Delete",t.collectionName,a,s,e),o(e)})):(n=new monitor_manager_1.MonitorMongo("deleteOne",this.collectionName,JSON.stringify([a,s])),index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).deleteOne(a,s).then(function(e){n.finish(),e.acknowledged?(index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(t.collectionName),r(e.deletedCount)):o(e.acknowledged)},function(e){n.finish(),console.log(new Date,"Error Delete One",t.collectionName,a,s,e),o(e)})),[2]})})})},MongoManagerCollection.prototype.distinct=function(e,i,r){var a=this;return new Promise(function(n,t){var o=new monitor_manager_1.MonitorMongo("distinct",a.collectionName,JSON.stringify([e,i,r]));index_1.ResolveIOServer.getMainDB().collection(a.collectionName,a.collectionOptions).distinct(e,i,r).then(function(e){o.finish(),n(e)},function(e){o.finish(),console.log(new Date,"Error Distinct",a.collectionName,i,r,e),t(e)})})},MongoManagerCollection.prototype.drop=function(i){var r=this;return new Promise(function(n,t){var o=new monitor_manager_1.MonitorMongo("drop",r.collectionName,JSON.stringify([i]));index_1.ResolveIOServer.getMainDB().collection(r.collectionName,r.collectionOptions).drop(i).then(function(e){o.finish(),n(e)},function(e){o.finish(),console.log(new Date,"Error Count Documents",r.collectionName,i,e),t(e)})})},MongoManagerCollection.prototype.dropIndex=function(i,r){var a=this;return new Promise(function(n,t){var o=new monitor_manager_1.MonitorMongo("dropIndex",a.collectionName,JSON.stringify([i,r]));index_1.ResolveIOServer.getMainDB().collection(a.collectionName,a.collectionOptions).dropIndex(i,r).then(function(e){o.finish(),n(e)},function(e){o.finish(),console.log(new Date,"Error Drop Index",a.collectionName,i,r,e),t(e)})})},MongoManagerCollection.prototype.dropIndexes=function(i){var r=this;return new Promise(function(n,t){var o=new monitor_manager_1.MonitorMongo("dropIndexes",r.collectionName,JSON.stringify([i]));index_1.ResolveIOServer.getMainDB().collection(r.collectionName,r.collectionOptions).dropIndexes(i).then(function(e){o.finish(),n(e)},function(e){o.finish(),console.log(new Date,"Error Drop Indexes",r.collectionName,i,e),t(e)})})},MongoManagerCollection.prototype.find=function(r,a,s){var e=this;return void 0===r&&(r={}),void 0===s&&(s=!1),new Promise(function(o,i){return __awaiter(e,void 0,void 0,function(){var n,t=this;return __generator(this,function(e){return s?(n=new monitor_manager_1.MonitorMongo("find",this.collectionName,JSON.stringify([r,a])),index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).find(r,a).toArray().then(function(e){n.finish(),o(e)},function(e){n.finish(),console.log(new Date,"Error Find",t.collectionName,r,a,e),i(e)})):index_1.ResolveIOServer.getMongoManager().find(this.collectionName,r,a).then(function(e){o(e)},function(e){i(e)}),[2]})})})},MongoManagerCollection.prototype.findById=function(i,r){var a=this;return new Promise(function(n,t){var o=new monitor_manager_1.MonitorMongo("findById",a.collectionName,JSON.stringify([{_id:i},r]));index_1.ResolveIOServer.getMainDB().collection(a.collectionName,a.collectionOptions).findOne({_id:i},r).then(function(e){o.finish(),n(e)},function(e){o.finish(),console.log(new Date,"Error Find By Id",a.collectionName,{_id:i},r,e),t(e)})})},MongoManagerCollection.prototype.findCount=function(i,r){var a=this;return void 0===i&&(i={}),new Promise(function(n,t){var o=new monitor_manager_1.MonitorMongo("findCount",a.collectionName,JSON.stringify([i,r]));index_1.ResolveIOServer.getMainDB().collection(a.collectionName,a.collectionOptions).find(i,r).count().then(function(e){o.finish(),n(e)},function(e){o.finish(),console.log(new Date,"Error Find Count",a.collectionName,i,r,e),t(e)})})},MongoManagerCollection.prototype.findCursor=function(e,n){void 0===e&&(e={});var t=new monitor_manager_1.MonitorMongo("findCursor",this.collectionName,JSON.stringify([e,n])),o=index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).find(e,n);return o.on("close",function(e){return t.finish(),o.removeAllListeners(),e}),o},MongoManagerCollection.prototype.findStream=function(e,n,t){void 0===e&&(e={});var o=new monitor_manager_1.MonitorMongo("findStream",this.collectionName,JSON.stringify([e,n,t])),e=index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).find(e,n).stream(t);return e.on("end",function(e){return o.finish(),e}).on("error",function(e){return o.finish(),e}).on("close",function(e){return o.finish(),e}),e},MongoManagerCollection.prototype.findOne=function(i,r,e){var a=this;return void 0===i&&(i={}),void 0===e&&(e=!1),new Promise(function(n,t){var o;e?(o=new monitor_manager_1.MonitorMongo("findOne",a.collectionName,JSON.stringify([i,r])),index_1.ResolveIOServer.getMainDB().collection(a.collectionName,a.collectionOptions).findOne(i,r).then(function(e){o.finish(),n(e)},function(e){o.finish(),console.log(new Date,"Error Find One",a.collectionName,i,r,e),t(e)})):index_1.ResolveIOServer.getMongoManager().findOne(a.collectionName,i,r).then(function(e){n(e)},function(e){t(e)})})},MongoManagerCollection.prototype.findOneAndDelete=function(r,a,s){var e=this;return void 0===r&&(r={}),void 0===s&&(s=!1),new Promise(function(i,n){return __awaiter(e,void 0,void 0,function(){var t,o=this;return __generator(this,function(e){return t=new monitor_manager_1.MonitorMongo("findOneAndDelete",this.collectionName,JSON.stringify([r,a])),index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).findOneAndDelete(r,a).then(function(e){t.finish();var n,e=e.value;e?(o.createLogs&&!s&&index_1.ResolveIOServer.getMainDB().collection("logs").insertOne({_id:objectIdHexString(),type:"document",collection:o.collectionName,id_document:e._id,payload:(0,common_1.getBinarySize)(JSON.stringify([e,r,a]))<2e5?JSON.stringify([e,r,a],null,2):"Too Big",method:"findOneAndDelete",id_user:"",user:"",messageId:0,route:"",createdAt:new Date}),o.useVersions&&((n=(0,common_1.deepCopy)(e))._id={_id:e._id,__v:e.__v},index_1.ResolveIOServer.getMongoManager().collection(o.versionCollection).replaceOne({_id:{_id:e._id,__v:e.__v}},n,{upsert:!0})),index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(o.collectionName),i(e)):i(null)},function(e){t.finish(),console.log(new Date,"Error Find One And Delete",o.collectionName,r,a,e),n(e)}),[2]})})})},MongoManagerCollection.prototype.findOneAndReplace=function(s,c,l,d,g){var e=this;return void 0===s&&(s={}),void 0===d&&(d=!1),void 0===g&&(g=!1),new Promise(function(r,a){return __awaiter(e,void 0,void 0,function(){var n,t,o,i=this;return __generator(this,function(e){return!this.checkSchema||g||(n=this.simplschema.newContext(),n.validate(c))?(t=new Date,this.timestamps&&(c.updatedAt=t),l&&l.upsert&&(c._id||(c._id=objectIdHexString()),this.useVersions&&(c.__v=0),this.timestamps)&&!c.createdAt&&(c.createdAt=t),o=new monitor_manager_1.MonitorMongo("findOneAndReplace",this.collectionName,JSON.stringify([s,c,l])),index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).findOneAndReplace(s,c,l).then(function(e){o.finish();var n,e=e.value;e?(i.createLogs&&!d&&index_1.ResolveIOServer.getMainDB().collection("logs").insertOne({_id:objectIdHexString(),type:"document",collection:i.collectionName,id_document:e._id,payload:(0,common_1.getBinarySize)(JSON.stringify([e,s,c,l]))<2e5?JSON.stringify([e,s,c,l],null,2):"Too Big",method:"findOneAndReplace",id_user:"",user:"",messageId:0,route:"",createdAt:new Date}),i.useVersions&&((n=(0,common_1.deepCopy)(e))._id={_id:e._id,__v:e.__v},index_1.ResolveIOServer.getMongoManager().collection(i.versionCollection).replaceOne({_id:{_id:e._id,__v:e.__v}},n,{upsert:!0})),index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(i.collectionName),r(e)):r(null)},function(e){o.finish(),console.log(new Date,"Error Find One And Replace",i.collectionName,s,l,e),a(e)})):(console.log(new Date,this.collectionName,"Schema Errors - findOneAndReplace",n.validationErrors()),index_1.ResolveIOServer.getMainServer().getMethodManager().callMethodInternal.call(index_1.ResolveIOServer.getMainServer().getMethodManager(),"insertErrorLog","Schema Failed on findOneAndReplace - "+this.collectionName,[n.validationErrors(),c]),a(n.validationErrors())),[2]})})})},MongoManagerCollection.prototype.findOneAndUpdate=function(s,c,l,d,g){var e=this;return void 0===s&&(s={}),void 0===d&&(d=!1),void 0===g&&(g=!1),new Promise(function(r,a){return __awaiter(e,void 0,void 0,function(){var n,t,o,i=this;return __generator(this,function(e){return!this.checkSchema||g||(n=this.simplschema.newContext(),n.validate(c,{modifier:!0}))?(this.timestamps&&(t=new Date,c.$set?c.$set.updatedAt=t:c.$set={updatedAt:t}),l&&l.upsert&&(c.$setOnInsert?(c.$setOnInsert._id||(c.$setOnInsert._id=objectIdHexString()),this.timestamps&&!c.$setOnInsert.createdAt&&(c.$setOnInsert.createdAt=new Date)):this.timestamps?c.$setOnInsert={_id:objectIdHexString(),createdAt:new Date}:c.$setOnInsert={_id:objectIdHexString()}),o=new monitor_manager_1.MonitorMongo("findOneAndUpdate",this.collectionName,JSON.stringify([s,c,l])),index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).findOneAndUpdate(s,c,l).then(function(e){o.finish();var n,e=e.value;e?(i.createLogs&&!d&&index_1.ResolveIOServer.getMainDB().collection("logs").insertOne({_id:objectIdHexString(),type:"document",collection:i.collectionName,id_document:e._id,payload:(0,common_1.getBinarySize)(JSON.stringify([e,s,c,l]))<2e5?JSON.stringify([e,s,c,l],null,2):"Too Big",method:"findOneAndUpdate",id_user:"",user:"",messageId:0,route:"",createdAt:new Date}),i.useVersions&&((n=(0,common_1.deepCopy)(e))._id={_id:e._id,__v:e.__v},index_1.ResolveIOServer.getMongoManager().collection(i.versionCollection).replaceOne({_id:{_id:e._id,__v:e.__v}},n,{upsert:!0})),index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(i.collectionName),r(e)):r(null)},function(e){o.finish(),console.log(new Date,"Error Find One And Update",i.collectionName,s,l,e),a(e)})):(console.log(new Date,this.collectionName,"Schema Errors - findOneAndUpdate",n.validationErrors()),index_1.ResolveIOServer.getMainServer().getMethodManager().callMethodInternal.call(index_1.ResolveIOServer.getMainServer().getMethodManager(),"insertErrorLog","Schema Failed on findOneAndUpdate - "+this.collectionName,[n.validationErrors(),c]),a(n.validationErrors())),[2]})})})},MongoManagerCollection.prototype.indexes=function(i){var r=this;return new Promise(function(n,t){var o=new monitor_manager_1.MonitorMongo("indexes",r.collectionName,JSON.stringify([i]));index_1.ResolveIOServer.getMainDB().collection(r.collectionName,r.collectionOptions).indexes(i).then(function(e){o.finish(),n(e)},function(e){o.finish(),console.log(new Date,"Error Indexes",r.collectionName,i,e),t(e)})})},MongoManagerCollection.prototype.indexExists=function(i,r){var a=this;return new Promise(function(n,t){var o=new monitor_manager_1.MonitorMongo("indexExists",a.collectionName,JSON.stringify([i,r]));index_1.ResolveIOServer.getMainDB().collection(a.collectionName,a.collectionOptions).indexExists(i,r).then(function(e){o.finish(),n(e)},function(e){o.finish(),console.log(new Date,"Error Index Exists",a.collectionName,i,r,e),t(e)})})},MongoManagerCollection.prototype.insertMany=function(d,g,u,_,h){var e=this;return void 0===u&&(u=!1),void 0===_&&(_=!1),void 0===h&&(h=!1),new Promise(function(c,l){return __awaiter(e,void 0,void 0,function(){var t,n,o,i,r,a,s=this;return __generator(this,function(e){if(d.length){for(t=[],this.checkSchema&&!_&&d.forEach(function(e){var n=s.simplschema.newContext();n.validate(e)?t.push(!0):(console.log(new Date,s.collectionName,"Schema Errors - insertMany",n.validationErrors()),index_1.ResolveIOServer.getMainServer().getMethodManager().callMethodInternal.call(index_1.ResolveIOServer.getMainServer().getMethodManager(),"insertErrorLog","Schema Failed on insertMany - "+s.collectionName,[n.validationErrors(),e]),t.push(!1))}),n=this.checkSchema?d.filter(function(e,n){return t[n]}):d,o=0;o<n.length;o++)(i=n[o])._id||(i._id=objectIdHexString()),this.timestamps&&(r=new Date,i.createdAt||(i.createdAt=r),i.updatedAt||(i.updatedAt=r)),this.useVersions&&!i.hasOwnProperty("__v")&&(i.__v=0),this.createLogs&&!u&&index_1.ResolveIOServer.getMainDB().collection("logs").insertOne({_id:objectIdHexString(),type:"document",collection:this.collectionName,id_document:i._id,payload:(0,common_1.getBinarySize)(JSON.stringify([i,g]))<2e5?JSON.stringify([i,g],null,2):"Too Big",method:"insertMany",id_user:"",user:"",messageId:0,route:"",createdAt:new Date});n.length&&(a=null,h||(a=new monitor_manager_1.MonitorMongo("insertMany",this.collectionName,JSON.stringify([n,g]))),index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).insertMany(n,g).then(function(e){a&&a.finish(),e.acknowledged?(index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(s.collectionName),c(n)):l(e.acknowledged)},function(e){a&&a.finish(),console.log(new Date,"Error Insert Many",s.collectionName,n,g,e),l(e)}))}else c([]);return[2]})})})},MongoManagerCollection.prototype.insertOne=function(s,c,l,d){var e=this;return void 0===l&&(l=!1),void 0===d&&(d=!1),new Promise(function(r,a){return __awaiter(e,void 0,void 0,function(){var n,t,o,i=this;return __generator(this,function(e){return s._id||(s._id=objectIdHexString()),!this.checkSchema||d||(n=this.simplschema.newContext(),n.validate(s))?(this.timestamps&&(t=new Date,s.createdAt||(s.createdAt=t),s.updatedAt||(s.updatedAt=t)),this.createLogs&&!l&&index_1.ResolveIOServer.getMainDB().collection("logs").insertOne({_id:objectIdHexString(),type:"document",collection:this.collectionName,id_document:s._id,payload:(0,common_1.getBinarySize)(JSON.stringify([s,c]))<2e5?JSON.stringify([s,c],null,2):"Too Big",method:"insertOne",id_user:"",user:"",messageId:0,route:"",createdAt:new Date}),this.useVersions&&!s.hasOwnProperty("__v")&&(s.__v=0),o=new monitor_manager_1.MonitorMongo("insertOne",this.collectionName,JSON.stringify([s,c])),index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).insertOne(s,c).then(function(e){o.finish(),e.acknowledged?(index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(i.collectionName),r(s)):a(e.acknowledged)},function(e){o.finish(),console.log(new Date,"Error Insert One",i.collectionName,s,c,e),a(e)})):(console.log(new Date,this.collectionName,"Schema Errors - insertOne",n.validationErrors()),index_1.ResolveIOServer.getMainServer().getMethodManager().callMethodInternal.call(index_1.ResolveIOServer.getMainServer().getMethodManager(),"insertErrorLog","Schema Failed on insertOne - "+this.collectionName,[n.validationErrors(),s]),a(n.validationErrors())),[2]})})})},MongoManagerCollection.prototype.listIndexes=function(e){var n=new monitor_manager_1.MonitorMongo("listIndexes",this.collectionName,JSON.stringify([e])),e=index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).listIndexes(e);return e.on("close",function(e){return n.finish(),e}),e},MongoManagerCollection.prototype.rename=function(i,r){var a=this;return new Promise(function(n,t){var o=new monitor_manager_1.MonitorMongo("rename",a.collectionName,JSON.stringify([i,r]));index_1.ResolveIOServer.getMainDB().collection(a.collectionName,a.collectionOptions).rename(i,r).then(function(e){o.finish(),n(e)},function(e){o.finish(),console.log(new Date,"Error Rename",a.collectionName,i,r,e),t(e)})})},MongoManagerCollection.prototype.replaceOne=function(v,m,f,p,M,O){var e=this;return void 0===p&&(p=!1),void 0===M&&(M=!1),void 0===O&&(O=null),new Promise(function(_,h){return __awaiter(e,void 0,void 0,function(){var n,t,o,i,r,a,s,c,l,d,g,u=this;return __generator(this,function(e){switch(e.label){case 0:return!this.checkSchema||M||(t=this.simplschema.newContext(),t.validate(m))?(n=new Date,this.timestamps&&(m.updatedAt=n),this.useVersions?O?[3,2]:[4,this.findOne(v,null,!0)]:[3,8]):(console.log(new Date,this.collectionName,"Schema Errors - replaceOne",t.validationErrors()),index_1.ResolveIOServer.getMainServer().getMethodManager().callMethodInternal.call(index_1.ResolveIOServer.getMainServer().getMethodManager(),"insertErrorLog","Schema Failed on replaceOne - "+this.collectionName,[t.validationErrors(),m]),h(t.validationErrors()),[2]);case 1:O=e.sent(),e.label=2;case 2:return O?(this.timestamps&&!m.createdAt&&O.createdAt&&(m.createdAt=O.createdAt),O.__v!==m.__v?[3,3]:(m.__v+=1,(t=(0,common_1.deepCopy)(O))._id={_id:O._id,__v:O.__v},index_1.ResolveIOServer.getMongoManager().collection(this.versionCollection).replaceOne({_id:{_id:O._id,__v:O.__v}},t,{upsert:!0}),4<=O.__v&&index_1.ResolveIOServer.getMongoManager().collection(this.versionCollection).deleteMany({$and:[{"_id._id":O._id},{"_id.__v":{$lt:O.__v-4}}]}),this.createLogs&&!p&&index_1.ResolveIOServer.getMainDB().collection("logs").insertOne({_id:objectIdHexString(),type:"document",collection:this.collectionName,id_document:O._id,payload:(0,common_1.getBinarySize)(JSON.stringify([O,v,m,f]))<2e5?JSON.stringify([O,v,m,f],null,2):"Too Big",method:"replaceOne",id_user:"",user:"",messageId:0,route:"",createdAt:new Date}),o=new monitor_manager_1.MonitorMongo("replaceOne",this.collectionName,JSON.stringify([v,m,f])),index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).replaceOne(v,m,f).then(function(e){o.finish(),e.acknowledged?(index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(u.collectionName),_(e.modifiedCount)):h(e.acknowledged)},function(e){o.finish(),console.log(new Date,"Error Replace One",u.collectionName,v,m,f,e),h(e)}),[3,5])):[3,6];case 3:return console.log("invalid version - "+this.collectionName,O.__v,m.__v),[4,index_1.ResolveIOServer.getMongoManager().collection(this.versionCollection).findOne({_id:{_id:O._id,__v:m.__v}},null,!0)];case 4:(i=e.sent())?(r=O._id,a=O.__v,(s=(0,common_1.getMongoMergeUpdatedDoc)(m,O,i))._id=r,s.__v=a+1,this.createLogs&&!p&&index_1.ResolveIOServer.getMainDB().collection("logs").insertOne({_id:objectIdHexString(),type:"document",collection:this.collectionName,id_document:r,payload:(0,common_1.getBinarySize)(JSON.stringify(["invalidVersion - merge",O,v,s,f]))<2e5?JSON.stringify(["invalidVersion - merge",O,v,s,f],null,2):"Too Big",method:"replaceOne",id_user:"",user:"",messageId:0,route:"",createdAt:new Date}),c=new monitor_manager_1.MonitorMongo("replaceOne",this.collectionName,JSON.stringify([v,s,f])),index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).replaceOne(v,s,f).then(function(e){c.finish(),e.acknowledged?(index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(u.collectionName),_(e.modifiedCount)):h(e.acknowledged)},function(e){c.finish(),console.log(new Date,"Error Replace One",u.collectionName,v,s,f,e),h(e)})):h("Invalid Version And Could Not Find History - DB: "+O.__v+", Trying to update with :"+m.__v),e.label=5;case 5:return[3,7];case 6:f&&f.upsert?(this.timestamps&&(m.createdAt=n),m._id||(m._id=objectIdHexString()),m.__v=0,this.createLogs&&!p&&index_1.ResolveIOServer.getMainDB().collection("logs").insertOne({_id:objectIdHexString(),type:"document",collection:this.collectionName,id_document:m._id,payload:(0,common_1.getBinarySize)(JSON.stringify(["upsert",v,m,f]))<2e5?JSON.stringify(["upsert",v,m,f],null,2):"Too Big",method:"replaceOne",id_user:"",user:"",messageId:0,route:"",createdAt:new Date}),l=new monitor_manager_1.MonitorMongo("replaceOne",this.collectionName,JSON.stringify([v,m,f])),index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).replaceOne(v,m,f).then(function(e){l.finish(),e.acknowledged?(index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(u.collectionName),_(e.modifiedCount)):h(e.acknowledged)},function(e){l.finish(),console.log(new Date,"Error Replace One",u.collectionName,v,m,f,e),h(e)})):h("No Document"),e.label=7;case 7:return[3,9];case 8:f&&f.upsert&&(this.timestamps&&!m.createdAt&&(m.createdAt=n),m._id||(m._id=objectIdHexString()),m.__v=0),this.createLogs&&!p?(f?f.returnDocument="before":f={returnDocument:"before"},d=new monitor_manager_1.MonitorMongo("findOneAndReplace",this.collectionName,JSON.stringify([v,m,f])),index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).findOneAndReplace(v,m,f).then(function(e){d.finish();e=e.value;e?index_1.ResolveIOServer.getMainDB().collection("logs").insertOne({_id:objectIdHexString(),type:"document",collection:u.collectionName,id_document:e._id,payload:(0,common_1.getBinarySize)(JSON.stringify([e,v,m,f]))<2e5?JSON.stringify([e,v,m,f],null,2):"Too Big",method:"replaceOne",id_user:"",user:"",messageId:0,route:"",createdAt:new Date}):index_1.ResolveIOServer.getMainDB().collection("logs").insertOne({_id:objectIdHexString(),type:"document",collection:u.collectionName,id_document:m._id,payload:(0,common_1.getBinarySize)(JSON.stringify(["upsert",v,m,f]))<2e5?JSON.stringify(["upsert",v,m,f],null,2):"Too Big",method:"replaceOne",id_user:"",user:"",messageId:0,route:"",createdAt:new Date}),index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(u.collectionName),_(1)},function(e){d.finish(),console.log(new Date,"Error Find One And Replace",u.collectionName,v,m,f,e),h(e)})):(g=new monitor_manager_1.MonitorMongo("replaceOne",this.collectionName,JSON.stringify([v,m,f])),index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).replaceOne(v,m,f).then(function(e){g.finish(),e.acknowledged?(index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(u.collectionName),_(e.modifiedCount)):h(e.acknowledged)},function(e){g.finish(),console.log(new Date,"Error Replace One",u.collectionName,v,m,f,e),h(e)})),e.label=9;case 9:return[2]}})})})},MongoManagerCollection.prototype.updateMany=function(d,g,u,_,h,v){var e=this;return void 0===_&&(_=!1),void 0===h&&(h=!1),void 0===v&&(v=!1),new Promise(function(c,l){return __awaiter(e,void 0,void 0,function(){var n,t,o,i,r,a,s=this;return __generator(this,function(e){switch(e.label){case 0:return g.$inc&&"{}"!==JSON.stringify(g.$inc)||g.$set&&"{}"!==JSON.stringify(g.$set)||g.$setOnInsert&&"{}"!==JSON.stringify(g.$setOnInsert)||g.$unset&&"{}"!==JSON.stringify(g.$unset)?(this.timestamps&&(n=new Date,g.$set?g.$set.updatedAt=n:g.$set={updatedAt:n}),!this.checkSchema||h||(n=this.simplschema.newContext(),n.validate(g,{modifier:!0}))?this.useVersions&&!v||this.createLogs&&!_?[4,this.find(d)]:[3,2]:(console.log(new Date,this.collectionName,"Schema Errors - updateMany",n.validationErrors()),index_1.ResolveIOServer.getMainServer().getMethodManager().callMethodInternal.call(index_1.ResolveIOServer.getMainServer().getMethodManager(),"insertErrorLog","Schema Failed on updateMany - "+this.collectionName,[n.validationErrors(),g]),l(n.validationErrors()),[2])):(c(1),[2]);case 1:for(t=e.sent(),o=0;o<t.length;o++)i=t[o],this.createLogs&&!_&&index_1.ResolveIOServer.getMainDB().collection("logs").insertOne({_id:objectIdHexString(),type:"document",collection:this.collectionName,id_document:i._id,payload:(0,common_1.getBinarySize)(JSON.stringify([i,d,g,u]))<2e5?JSON.stringify([i,d,g,u],null,2):"Too Big",method:"updateMany",id_user:"",user:"",messageId:0,route:"",createdAt:new Date}),this.useVersions&&((r=(0,common_1.deepCopy)(i))._id={_id:i._id,__v:i.__v},index_1.ResolveIOServer.getMongoManager().collection(this.versionCollection).replaceOne({_id:{_id:i._id,__v:i.__v}},r,{upsert:!0}),4<=i.__v&&index_1.ResolveIOServer.getMongoManager().collection(this.versionCollection).deleteMany({$and:[{"_id._id":i._id},{"_id.__v":{$lt:i.__v-4}}]}),objectContainsPropertyDeep(g,"__v")||(g.$inc?g.$inc.__v||(g.$inc.__v=1):g.$inc={__v:1}));e.label=2;case 2:return a=new monitor_manager_1.MonitorMongo("updateMany",this.collectionName,JSON.stringify([d,g,u])),index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).updateMany(d,g,u).then(function(e){a.finish(),e.acknowledged?(index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(s.collectionName),c(e.modifiedCount)):l(e.acknowledged)},function(e){a.finish(),console.log(new Date,"Error Update Many",s.collectionName,d,g,u,e),l(e)}),[2]}})})})},MongoManagerCollection.prototype.updateOne=function(d,g,u,_,h){var e=this;return void 0===_&&(_=!1),void 0===h&&(h=!1),new Promise(function(c,l){return __awaiter(e,void 0,void 0,function(){var n,t,o,i,r,a,s=this;return __generator(this,function(e){switch(e.label){case 0:return!this.checkSchema||h||(t=this.simplschema.newContext(),t.validate(g,{modifier:!0}))?g.$inc&&"{}"!==JSON.stringify(g.$inc)||g.$set&&"{}"!==JSON.stringify(g.$set)||g.$setOnInsert&&"{}"!==JSON.stringify(g.$setOnInsert)||g.$unset&&"{}"!==JSON.stringify(g.$unset)?(n=new Date,this.timestamps&&(g.$set?g.$set.updatedAt=n:g.$set={updatedAt:n}),this.useVersions?[4,this.findOne(d,null,!0)]:[3,2]):(c(1),[2]):(console.log(new Date,this.collectionName,"Schema Errors - updateOne",t.validationErrors()),index_1.ResolveIOServer.getMainServer().getMethodManager().callMethodInternal.call(index_1.ResolveIOServer.getMainServer().getMethodManager(),"insertErrorLog","Schema Failed on updateOne - "+this.collectionName,[t.validationErrors(),g]),l(t.validationErrors()),[2]);case 1:return(n=e.sent())?(this.createLogs&&!_&&index_1.ResolveIOServer.getMainDB().collection("logs").insertOne({_id:objectIdHexString(),type:"document",collection:this.collectionName,id_document:n._id,payload:(0,common_1.getBinarySize)(JSON.stringify([n,d,g,u]))<2e5?JSON.stringify([n,d,g,u],null,2):"Too Big",method:"updateOne",id_user:"",user:"",messageId:0,route:"",createdAt:new Date}),(t=(0,common_1.deepCopy)(n))._id={_id:n._id,__v:n.__v},index_1.ResolveIOServer.getMongoManager().collection(this.versionCollection).replaceOne({_id:{_id:n._id,__v:n.__v}},t,{upsert:!0}),4<=n.__v&&index_1.ResolveIOServer.getMongoManager().collection(this.versionCollection).deleteMany({$and:[{"_id._id":n._id},{"_id.__v":{$lt:n.__v-4}}]}),objectContainsPropertyDeep(g,"__v")||(g.$inc?g.$inc.__v||(g.$inc.__v=1):g.$inc={__v:1}),o=new monitor_manager_1.MonitorMongo("updateOne",this.collectionName,JSON.stringify([d,g,u])),index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).updateOne(d,g,u).then(function(e){o.finish(),e.acknowledged?(index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(s.collectionName),c(e.modifiedCount)):l(e.acknowledged)},function(e){o.finish(),console.log(new Date,"Error Update One",s.collectionName,d,g,u,e),l(e)})):u&&u.upsert?(g.$setOnInsert?(g.$setOnInsert._id||(g.$setOnInsert._id=objectIdHexString()),this.timestamps&&!g.$setOnInsert.createdAt&&(g.$setOnInsert.createdAt=new Date)):this.timestamps?g.$setOnInsert={_id:objectIdHexString(),__v:0,createdAt:new Date}:g.$setOnInsert={_id:objectIdHexString(),__v:0},this.createLogs&&!_&&index_1.ResolveIOServer.getMainDB().collection("logs").insertOne({_id:objectIdHexString(),type:"document",collection:this.collectionName,id_document:g.$setOnInsert._id,payload:(0,common_1.getBinarySize)(JSON.stringify(["upsert",d,g,u]))<2e5?JSON.stringify(["upsert",d,g,u],null,2):"Too Big",method:"updateOne",id_user:"",user:"",messageId:0,route:"",createdAt:new Date}),i=new monitor_manager_1.MonitorMongo("updateOne",this.collectionName,JSON.stringify([d,g,u])),index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).updateOne(d,g,u).then(function(e){i.finish(),e.acknowledged?(index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(s.collectionName),c(e.modifiedCount)):l(e.acknowledged)},function(e){i.finish(),console.log(new Date,"Error Update One",s.collectionName,d,g,u,e),l(e)})):l("No Document"),[3,3];case 2:u&&u.upsert&&(g.$setOnInsert?(g.$setOnInsert._id||(g.$setOnInsert._id=objectIdHexString()),this.timestamps&&!g.$setOnInsert.createdAt&&(g.$setOnInsert.createdAt=new Date)):this.timestamps?g.$setOnInsert={_id:objectIdHexString(),createdAt:new Date}:g.$setOnInsert={_id:objectIdHexString()}),this.createLogs&&!_?(u?u.returnDocument="before":u={returnDocument:"before"},r=new monitor_manager_1.MonitorMongo("findOneAndUpdate",this.collectionName,JSON.stringify([d,g,u])),index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).findOneAndUpdate(d,g,u).then(function(e){r.finish();var n=e.value;n?(index_1.ResolveIOServer.getMainDB().collection("logs").insertOne({_id:objectIdHexString(),type:"document",collection:s.collectionName,id_document:n._id,payload:(0,common_1.getBinarySize)(JSON.stringify([n,d,g,u]))<2e5?JSON.stringify([n,d,g,u],null,2):"Too Big",method:"updateOne",id_user:"",user:"",messageId:0,route:"",createdAt:new Date}),c(e.ok)):g.$setOnInsert?(index_1.ResolveIOServer.getMainDB().collection("logs").insertOne({_id:objectIdHexString(),type:"document",collection:s.collectionName,id_document:g.$setOnInsert._id,payload:(0,common_1.getBinarySize)(JSON.stringify(["upsert",d,g,u]))<2e5?JSON.stringify(["upsert",d,g,u],null,2):"Too Big",method:"updateOne",id_user:"",user:"",messageId:0,route:"",createdAt:new Date}),index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(s.collectionName),c(e.ok)):c(0)},function(e){r.finish(),console.log(new Date,"Error Find One And Update",s.collectionName,d,g,u,e),l(e)})):(a=new monitor_manager_1.MonitorMongo("updateOne",this.collectionName,JSON.stringify([d,g,u])),index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).updateOne(d,g,u).then(function(e){a.finish(),e.acknowledged?(index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(s.collectionName),c(e.modifiedCount)):l(e.acknowledged)},function(e){a.finish(),console.log(new Date,"Error Update One",s.collectionName,d,g,u,e),l(e)})),e.label=3;case 3:return[2]}})})})},MongoManagerCollection.prototype.watchCollection=function(e,n){return void 0===e&&(e=[]),index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).watch(e,n)},(e=MongoManagerCollection).indexQueue=async_1.default.queue(function(d,g){return __awaiter(void 0,void 0,void 0,function(){var n,t,o,i,r,a,s,c,l;return __generator(e,function(e){switch(e.label){case 0:if(n=d.action,t=d.collection,o=d.specs,i=d.options,!(r=index_1.ResolveIOServer.getMainDB().collection(t.collectionName,t.collectionOptions)))return[2,g(new Error("Collection ".concat(t.collectionName," not found")))];a=new monitor_manager_1.MonitorMongo(n,t.collectionName,JSON.stringify([o,i])),e.label=1;case 1:return e.trys.push([1,3,,10]),[4,r[n].apply(r,__spreadArray(__spreadArray([],__read(o),!1),[i],!1))];case 2:return c=e.sent(),a.finish(),g(null,c),[3,10];case 3:if(85!==(s=e.sent()).code&&!s.message.includes("IndexOptionsConflict"))return[3,9];e.label=4;case 4:return(e.trys.push([4,8,,9]),l=t.extractIndexNameFromError(s.message))?[4,r.dropIndex(l)]:[3,7];case 5:return e.sent(),[4,r[n].apply(r,__spreadArray(__spreadArray([],__read(o),!1),[i],!1))];case 6:return c=e.sent(),a.finish(),g(null,c),[2];case 7:return[3,9];case 8:return l=e.sent(),g(l),[3,9];case 9:return a.finish(),g(s),[3,10];case 10:return[2]}})})},1),MongoManagerCollection}()),MongoManagerUserCollection=function(e){function MongoManagerUserCollection(){return null!==e&&e.apply(this,arguments)||this}return __extends(MongoManagerUserCollection,e),MongoManagerUserCollection.prototype.authenticate=function(a,t){var e=this;return new Promise(function(i,r){return __awaiter(e,void 0,void 0,function(){var n,o=this;return __generator(this,function(e){switch(e.label){case 0:return(n=Math.pow(100,Math.log(a.attempts+1)),n=n<3e5?n:3e5,a.last)?Date.now()-a.last.getTime()<n?(a.last=new Date,[4,user_collection_1.Users.updateOne({_id:a._id},{$set:{last:a.last}})]):[3,2]:[3,3];case 1:return e.sent(),i({data:null,error:"Attempt Too Soon"}),[2];case 2:return[3,4];case 3:a.last=new Date,e.label=4;case 4:return 5<=a.attempts?i({data:null,error:"Too Many Attempts"}):a.salt?pbkdf2(t,a.salt,{iterations:25e3,keylen:512,digestAlgorithm:"sha256"},function(n,t){return __awaiter(o,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return n?[2,r(n)]:scmp(t,Buffer.from(a.hash,"hex"))?(a.last=new Date,a.attempts=0,[4,user_collection_1.Users.updateOne({_id:a._id},{$set:{last:a.last,attempts:a.attempts}})]):[3,2];case 1:return e.sent(),i({data:a,error:""}),[3,4];case 2:return a.last=new Date,a.attempts=a.attempts+1,[4,user_collection_1.Users.updateOne({_id:a._id},{$set:{last:a.last,attempts:a.attempts}})];case 3:e.sent(),5<=a.attempts?i({data:null,error:"Too Many Attempts"}):i({data:null,error:"Invalid Username And Password"}),e.label=4;case 4:return[2]}})})}):i({data:null,error:"No Salt Value Stored"}),[2]}})})})},MongoManagerUserCollection.prototype.serializeUser=function(){return function(e,n){n(null,e.username)}},MongoManagerUserCollection.prototype.deserializeUser=function(){return function(e,n){user_collection_1.Users.findOne({username:e}).then(function(e){n(null,e)},function(e){n(e,null)})}},MongoManagerUserCollection.prototype.setPassword=function(r,a){var e=this;return new Promise(function(o,i){return __awaiter(e,void 0,void 0,function(){var n,t;return __generator(this,function(e){switch(e.label){case 0:return r?[3,1]:(i("No User"),[3,5]);case 1:return a?[3,2]:(i("No Password"),[3,5]);case 2:return[4,randomBytes(32)];case 3:return n=e.sent(),n=n.toString("hex"),[4,pbkdf2Promisified(a,n,{iterations:25e3,keylen:512,digestAlgorithm:"sha256"})];case 4:t=e.sent(),t=Buffer.from(t,"binary").toString("hex"),user_collection_1.Users.updateOne({_id:r._id},{$set:{hash:t,salt:n,services:{},attempts:0}}).then(function(e){return o(e)},function(e){return i(e)}),e.label=5;case 5:return[2]}})})})},MongoManagerUserCollection.prototype.changePassword=function(i,r,a){var e=this;return new Promise(function(t,o){return __awaiter(e,void 0,void 0,function(){var n;return __generator(this,function(e){switch(e.label){case 0:return i?[3,1]:(o("Missing User"),[3,4]);case 1:return r&&a?[3,2]:(o("Missing Password"),[3,4]);case 2:return[4,this.authenticate(i,r)];case 3:(n=e.sent()).data?this.setPassword(i,a).then(function(e){return t(e)},function(e){return o(e)}):o(n.error),e.label=4;case 4:return[2]}})})})},MongoManagerUserCollection.prototype.register=function(o,i){var e=this;return new Promise(function(n,t){return __awaiter(e,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return o.username?[3,1]:(t("Missing Username"),[3,5]);case 1:return[4,user_collection_1.Users.findOne({username:o.username})];case 2:return e.sent()?(t("Username Exists"),[3,5]):[3,3];case 3:return[4,user_collection_1.Users.findOne({email:o.email})];case 4:e.sent()?t("Email Exists"):(o.setPassword(i),n(o)),e.label=5;case 5:return[2]}})})})},MongoManagerUserCollection.prototype.resetAttempts=function(e){return user_collection_1.Users.updateOne({_id:e._id},{$set:{attempts:0}})},MongoManagerUserCollection}(exports.MongoManagerCollection=MongoManagerCollection);function objectIdHexString(){return(new mongodb_1.ObjectId).toHexString()}function pbkdf2(e,n,t,o){crypto.pbkdf2(e,n,t.iterations,t.keylen,t.digestAlgorithm,o)}function pbkdf2Promisified(e,n,i){return new Promise(function(t,o){return pbkdf2(e,n,i,function(e,n){return e?o(e):t(n)})})}function randomBytes(e){return new Promise(function(t,o){return crypto.randomBytes(e,function(e,n){return e?o(e):t(n)})})}function objectContainsPropertyDeep(e,n){var t=Object.keys(e);if(t.some(function(e){return e===n}))return!0;for(var o=0;o<t.length;o++){var i=t[o];if(e[i]&&"object"==typeof e[i]&&objectContainsPropertyDeep(e[i],n))return!0}return!1}exports.MongoManagerUserCollection=MongoManagerUserCollection,exports.objectIdHexString=objectIdHexString;
|
|
1
|
+
"use strict";var __extends=this&&this.__extends||function(){var t=function(e,n){return(t=Object.setPrototypeOf||({__proto__:[]}instanceof Array?function(e,n){e.__proto__=n}:function(e,n){for(var t in n)Object.prototype.hasOwnProperty.call(n,t)&&(e[t]=n[t])}))(e,n)};return function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function __(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(__.prototype=n.prototype,new __)}}(),__assign=this&&this.__assign||function(){return(__assign=Object.assign||function(e){for(var n,t=1,o=arguments.length;t<o;t++)for(var i in n=arguments[t])Object.prototype.hasOwnProperty.call(n,i)&&(e[i]=n[i]);return e}).apply(this,arguments)},__awaiter=this&&this.__awaiter||function(e,o,i,r){return new(i=i||Promise)(function(t,n){function fulfilled(e){try{step(r.next(e))}catch(e){n(e)}}function rejected(e){try{step(r.throw(e))}catch(e){n(e)}}function step(e){var n;e.done?t(e.value):((n=e.value)instanceof i?n:new i(function(e){e(n)})).then(fulfilled,rejected)}step((r=r.apply(e,o||[])).next())})},__generator=this&&this.__generator||function(o,i){var r,a,s,c={label:0,sent:function(){if(1&s[0])throw s[1];return s[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(t){return function(e){var n=[t,e];if(r)throw new TypeError("Generator is already executing.");for(;c=l&&n[l=0]?0:c;)try{if(r=1,a&&(s=2&n[0]?a.return:n[0]?a.throw||((s=a.return)&&s.call(a),0):a.next)&&!(s=s.call(a,n[1])).done)return s;switch(a=0,(n=s?[2&n[0],s.value]:n)[0]){case 0:case 1:s=n;break;case 4:return c.label++,{value:n[1],done:!1};case 5:c.label++,a=n[1],n=[0];continue;case 7:n=c.ops.pop(),c.trys.pop();continue;default:if(!(s=0<(s=c.trys).length&&s[s.length-1])&&(6===n[0]||2===n[0])){c=0;continue}if(3===n[0]&&(!s||n[1]>s[0]&&n[1]<s[3]))c.label=n[1];else if(6===n[0]&&c.label<s[1])c.label=s[1],s=n;else{if(!(s&&c.label<s[2])){s[2]&&c.ops.pop(),c.trys.pop();continue}c.label=s[2],c.ops.push(n)}}n=i.call(o,c)}catch(e){n=[6,e],a=0}finally{r=s=0}if(5&n[0])throw n[1];return{value:n[0]?n[1]:void 0,done:!0}}}},__read=this&&this.__read||function(e,n){var t="function"==typeof Symbol&&e[Symbol.iterator];if(!t)return e;var o,i,r=t.call(e),a=[];try{for(;(void 0===n||0<n--)&&!(o=r.next()).done;)a.push(o.value)}catch(e){i={error:e}}finally{try{o&&!o.done&&(t=r.return)&&t.call(r)}finally{if(i)throw i.error}}return a},__spreadArray=this&&this.__spreadArray||function(e,n,t){if(t||2===arguments.length)for(var o,i=0,r=n.length;i<r;i++)!o&&i in n||((o=o||Array.prototype.slice.call(n,0,i))[i]=n[i]);return e.concat(o||Array.prototype.slice.call(n))},__values=this&&this.__values||function(e){var n="function"==typeof Symbol&&Symbol.iterator,t=n&&e[n],o=0;if(t)return t.call(e);if(e&&"number"==typeof e.length)return{next:function(){return{value:(e=e&&o>=e.length?void 0:e)&&e[o++],done:!e}}};throw new TypeError(n?"Object is not iterable.":"Symbol.iterator is not defined.")},simpl_schema_1=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.objectIdHexString=exports.MongoManagerUserCollection=exports.MongoManagerCollection=exports.MongoManagerModel=exports.MongoManager=void 0,require("simpl-schema")),mongodb_1=require("mongodb"),index_1=require("../index"),user_collection_1=require("../collections/user.collection"),common_1=require("../util/common"),NodeCache=require("node-cache"),crypto=require("crypto"),scmp=require("scmp"),monitor_manager_1=require("./monitor.manager"),os_1=require("os"),numCPUs=(0,os_1.cpus)().length,v8=require("v8"),async_1=require("async"),MongoManager=function(){function MongoManager(e){this._collections=[],this._cacheMap=[],this._operationInProgress=new Map,this._heapSize=v8.getHeapStatistics()/numCPUs,this._serverCollections=[],this._serverConfig=null,this._isWorkersEnabled=!1,this._isWorkerInstance=!1,this._serverConfig=e,this._nodeCache=new NodeCache({stdTTL:0,checkperiod:0}),this._isWorkersEnabled="true"===process.env.IS_WORKERS_ENABLED,this._isWorkerInstance="true"===process.env.IS_WORKER_INSTANCE,this.setCacheLimit(),this.initServerCollections(),this._isWorkersEnabled&&this._isWorkerInstance&&this.setupChangeStream()}return MongoManager.prototype.setCacheLimit=function(){this._isWorkersEnabled?this._heapLimit=this._isWorkerInstance?.8*this._heapSize:.4*this._heapSize:this._heapLimit=.3*this._heapSize},MongoManager.prototype.initServerCollections=function(){return __awaiter(this,void 0,void 0,function(){var n;return __generator(this,function(e){switch(e.label){case 0:return[4,index_1.ResolveIOServer.getMainDB().listCollections().toArray()];case 1:return n=e.sent(),this._serverCollections=n,[2]}})})},MongoManager.prototype.getServerCollections=function(){return this._serverCollections},MongoManager.prototype.registerCollection=function(n){var e=this;n.collectionOptions&&n.collectionOptions.timeseries&&n.collectionOptions.timeseries.timeField&&this._serverCollections.some(function(e){return e.name===n.collectionName&&"collection"===e.type})&&index_1.ResolveIOServer.getMainDB().dropCollection(n.collectionName).then(function(){e.createCollection(n)}),this._collections.push(n)},MongoManager.prototype.createCollection=function(e){index_1.ResolveIOServer.getMainDB().createCollection(e.collectionName,e.collectionOptions)},MongoManager.prototype.collections=function(){return this._collections},MongoManager.prototype.collection=function(n){return this._collections.find(function(e){return e.collectionName===n})},MongoManager.prototype.delay=function(n){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(e){return[2,new Promise(function(e){return setTimeout(e,n)})]})})},MongoManager.prototype.find=function(i,r,a){return void 0===r&&(r={}),__awaiter(this,void 0,void 0,function(){var n,t,o=this;return __generator(this,function(e){return n=this.generateCacheKey([i],"find",[r,a]),void 0!==(t=this.getFromCache(n))?(index_1.ResolveIOServer.getMainServer().getSubscriptionManager()&&index_1.ResolveIOServer.getMainServer().getSubscriptionManager().getEnableDebug()&&console.log(new Date,"Mongo Find - Cache",i),[2,t]):this._operationInProgress.has(n)?(index_1.ResolveIOServer.getMainServer().getSubscriptionManager()&&index_1.ResolveIOServer.getMainServer().getSubscriptionManager().getEnableDebug()&&console.log(new Date,"Mongo Find - Already running",i),[2,this._operationInProgress.get(n).promise]):(index_1.ResolveIOServer.getMainServer().getSubscriptionManager()&&index_1.ResolveIOServer.getMainServer().getSubscriptionManager().getEnableDebug()&&console.log(new Date,"Mongo Find - Running",i),t=this.executeFind(i,r,a,n),this._operationInProgress.set(n,{promise:t,invalidatedDuringExecution:!1,collections:[i]}),t.finally(function(){index_1.ResolveIOServer.getMainServer().getSubscriptionManager()&&index_1.ResolveIOServer.getMainServer().getSubscriptionManager().getEnableDebug()&&console.log(new Date,"Mongo Find - Done",i),o._operationInProgress.delete(n)}),[2,t])})})},MongoManager.prototype.executeFind=function(o,i,r,a){return __awaiter(this,void 0,void 0,function(){var n,t;return __generator(this,function(e){switch(e.label){case 0:return n=index_1.ResolveIOServer.getMainDB().collection(o),t=new monitor_manager_1.MonitorMongo("find",o,JSON.stringify([i,r])),[4,n.find(i,r).toArray()];case 1:return n=e.sent(),t.finish(),this._operationInProgress.get(a).invalidatedDuringExecution||this.addToCache([o],a,n),[2,n]}})})},MongoManager.prototype.findOne=function(i,r,a){return void 0===r&&(r={}),__awaiter(this,void 0,void 0,function(){var n,t,o=this;return __generator(this,function(e){return n=this.generateCacheKey([i],"findOne",[r,a]),void 0!==(t=this.getFromCache(n))?(index_1.ResolveIOServer.getMainServer().getSubscriptionManager()&&index_1.ResolveIOServer.getMainServer().getSubscriptionManager().getEnableDebug()&&console.log(new Date,"Mongo FindOne - Cache",i),[2,t]):this._operationInProgress.has(n)?(index_1.ResolveIOServer.getMainServer().getSubscriptionManager()&&index_1.ResolveIOServer.getMainServer().getSubscriptionManager().getEnableDebug()&&console.log(new Date,"Mongo FindOne - Already running",i),[2,this._operationInProgress.get(n).promise]):(index_1.ResolveIOServer.getMainServer().getSubscriptionManager()&&index_1.ResolveIOServer.getMainServer().getSubscriptionManager().getEnableDebug()&&console.log(new Date,"Mongo FindOne - Running",i),t=this.executeFindOne(i,r,a,n),this._operationInProgress.set(n,{promise:t,invalidatedDuringExecution:!1,collections:[i]}),t.finally(function(){index_1.ResolveIOServer.getMainServer().getSubscriptionManager()&&index_1.ResolveIOServer.getMainServer().getSubscriptionManager().getEnableDebug()&&console.log(new Date,"Mongo FindOne - Done",i),o._operationInProgress.delete(n)}),[2,t])})})},MongoManager.prototype.executeFindOne=function(o,i,r,a){return __awaiter(this,void 0,void 0,function(){var n,t;return __generator(this,function(e){switch(e.label){case 0:return n=index_1.ResolveIOServer.getMainDB().collection(o),t=new monitor_manager_1.MonitorMongo("findOne",o,JSON.stringify([i,r])),[4,n.findOne(i,r)];case 1:return n=e.sent(),t.finish(),this._operationInProgress.get(a).invalidatedDuringExecution||this.addToCache([o],a,n),[2,n]}})})},MongoManager.prototype.aggregate=function(r,a,s){return __awaiter(this,void 0,void 0,function(){var n,t,o,i=this;return __generator(this,function(e){return n=__spreadArray([r],__read(a.flatMap(function(e){var n;return null!=(n=e.$lookup)&&n.from?[e.$lookup.from]:[]})),!1),t=this.generateCacheKey(n,"aggregate",[a,s]),void 0!==(o=this.getFromCache(t))?(index_1.ResolveIOServer.getMainServer().getSubscriptionManager()&&index_1.ResolveIOServer.getMainServer().getSubscriptionManager().getEnableDebug()&&console.log(new Date,"Mongo Agg - Cache",n),[2,o]):this._operationInProgress.has(t)?(index_1.ResolveIOServer.getMainServer().getSubscriptionManager()&&index_1.ResolveIOServer.getMainServer().getSubscriptionManager().getEnableDebug()&&console.log(new Date,"Mongo Agg - Already running",n),[2,this._operationInProgress.get(t).promise]):(index_1.ResolveIOServer.getMainServer().getSubscriptionManager()&&index_1.ResolveIOServer.getMainServer().getSubscriptionManager().getEnableDebug()&&console.log(new Date,"Mongo Agg - Running",n),o=this.executeAggregate(r,a,s,t,n),this._operationInProgress.set(t,{promise:o,invalidatedDuringExecution:!1,collections:n}),o.finally(function(){index_1.ResolveIOServer.getMainServer().getSubscriptionManager()&&index_1.ResolveIOServer.getMainServer().getSubscriptionManager().getEnableDebug()&&console.log(new Date,"Mongo Agg - Done",n),i._operationInProgress.delete(t)}),[2,o])})})},MongoManager.prototype.executeAggregate=function(o,i,r,a,s){return __awaiter(this,void 0,void 0,function(){var n,t;return __generator(this,function(e){switch(e.label){case 0:return n=index_1.ResolveIOServer.getMainDB().collection(o),t=new monitor_manager_1.MonitorMongo("aggregate",o,JSON.stringify([i,r])),[4,n.aggregate(i,r).toArray()];case 1:return n=e.sent(),t.finish(),this._operationInProgress.get(a).invalidatedDuringExecution||this.addToCache(s,a,n),[2,n]}})})},MongoManager.prototype.countDocuments=function(i,r,a){return void 0===r&&(r={}),__awaiter(this,void 0,void 0,function(){var n,t,o=this;return __generator(this,function(e){return n=this.generateCacheKey([i],"countDocuments",[r,a]),void 0!==(t=this.getFromCache(n))?[2,t]:this._operationInProgress.has(n)?[2,this._operationInProgress.get(n).promise]:(t=this.executeCountDocuments(i,r,a,n),this._operationInProgress.set(n,{promise:t,invalidatedDuringExecution:!1,collections:[i]}),t.finally(function(){return o._operationInProgress.delete(n)}),[2,t])})})},MongoManager.prototype.executeCountDocuments=function(o,i,r,a){return __awaiter(this,void 0,void 0,function(){var n,t;return __generator(this,function(e){switch(e.label){case 0:return n=index_1.ResolveIOServer.getMainDB().collection(o),t=new monitor_manager_1.MonitorMongo("countDocuments",o,JSON.stringify([i,r])),[4,n.countDocuments(i,r)];case 1:return n=e.sent(),t.finish(),this._operationInProgress.get(a).invalidatedDuringExecution||this.addToCache([o],a,n),[2,n]}})})},MongoManager.prototype.generateCacheKey=function(e,n,t){e=JSON.stringify({collections:e,functionName:n,args:t});return crypto.createHash("sha256").update(e).digest("hex")},MongoManager.prototype.getFromCache=function(n){try{var e=this._nodeCache.get(n);if(e)return JSON.parse(e,common_1.dateReviver)}catch(e){this._nodeCache.del(n)}},MongoManager.prototype.addToCache=function(e,n,t){var o,i;if((0,common_1.getBinarySize)(JSON.stringify(t))<1e6&&!e.includes("logs")&&!e.includes("log-method-latencies")&&!e.includes("log-subscriptions")&&!e.find(function(e){return e.endsWith(".versions")})&&!e.find(function(e){return e.startsWith("monitor-")})){var r=this._nodeCache.getStats().vsize;if(r>this._heapLimit){var a=0,s=this._nodeCache.keys();try{for(var c=__values(s),l=c.next();!l.done;l=c.next()){var d=l.value;if(this._nodeCache.del(d),a+=1,(r=this._nodeCache.getStats().vsize)<.75*this._heapLimit)break}}catch(e){o={error:e}}finally{try{l&&!l.done&&(i=c.return)&&i.call(c)}finally{if(o)throw o.error}}console.log("Query Cache: Too Big, - Deleted: "+a+" - "+r)}this._nodeCache.set(n,JSON.stringify(t)),this._cacheMap.push({collections:e,key:n})}},MongoManager.prototype.invalidateQueryCache=function(n){var t,e,o,i,r=this._cacheMap.filter(function(e){return e.collections.includes(n)});index_1.ResolveIOServer.getMainServer().getSubscriptionManager()&&index_1.ResolveIOServer.getMainServer().getSubscriptionManager().getEnableDebug()&&console.log(new Date,"Mongo Invalidate Cache",n);try{for(var a=__values(r),s=a.next();!s.done;s=a.next()){var c=s.value;this._nodeCache.del(c.key),this._operationInProgress.has(c.key)&&(this._operationInProgress.get(c.key).invalidatedDuringExecution=!0,index_1.ResolveIOServer.getMainServer().getSubscriptionManager())&&index_1.ResolveIOServer.getMainServer().getSubscriptionManager().getEnableDebug()&&console.log(new Date,"Mongo Invalidated During Execution",c.collections)}}catch(e){t={error:e}}finally{try{s&&!s.done&&(e=a.return)&&e.call(a)}finally{if(t)throw t.error}}try{for(var l=__values(this._operationInProgress.entries()),d=l.next();!d.done;d=l.next()){var g=__read(d.value,2),u=(g[0],g[1]);u.collections.includes(n)&&(u.invalidatedDuringExecution=!0,index_1.ResolveIOServer.getMainServer().getSubscriptionManager())&&index_1.ResolveIOServer.getMainServer().getSubscriptionManager().getEnableDebug()&&console.log(new Date,"Mongo Invalidated During Execution (No cache)",u.collections)}}catch(e){o={error:e}}finally{try{d&&!d.done&&(i=l.return)&&i.call(l)}finally{if(o)throw o.error}}this._cacheMap=this._cacheMap.filter(function(e){return!e.collections.includes(n)})},MongoManager.prototype.setupChangeStream=function(){var n=this,t=index_1.ResolveIOServer.getMainDB().watch([{$match:{$and:[{"ns.coll":{$nin:["logs","log-method-latencies","log-subscriptions"]}},{"ns.coll":{$not:/.*\.versions$/}},{"ns.coll":{$not:/^monitor-/}}]}}],{fullDocument:"updateLookup"});t.on("change",function(t){return __awaiter(n,void 0,void 0,function(){var n;return __generator(this,function(e){return t.ns&&t.ns.coll&&(n=t.ns.coll,this.collection(n))&&this.invalidateQueryCache(n),[2]})})}),t.on("error",function(e){console.log(new Date,"Mongo change stream error. Restart..."),t.close(),setTimeout(function(){return n.setupChangeStream()},5e3)}),t.on("close",function(){console.log(new Date,"Mongo change stream closed. Restarting..."),setTimeout(function(){return n.setupChangeStream()},5e3)})},MongoManager}(),MongoManagerModel=(exports.MongoManager=MongoManager,function(e){var n;this.collection_main=null,this.collection_version=null,"users"===e.collectionName?this.collection_main=new MongoManagerUserCollection(e):this.collection_main=new MongoManagerCollection(e),e.useVersionCollection&&(this.collection_main.useVersions=!0,(n=(0,common_1.deepCopy)(e.schema))._id.type="Object",n._id.blackbox=!0,n={collectionName:e.collectionName+".versions",schema:n,useVersionCollection:!1,useReportBuilder:!1,reportBuilderLookupTables:[],timestamps:!0,createLogs:!1,checkSchema:!1,collectionOptions:null},"users"===e.collectionName?this.collection_version=new MongoManagerUserCollection(n):this.collection_version=new MongoManagerCollection(n),this.collection_version.createIndex({"_id._id":1,"_id.__v":1}),this.collection_main.versionCollection=e.collectionName+".versions")}),MongoManagerCollection=(exports.MongoManagerModel=MongoManagerModel,function(){function MongoManagerCollection(e){var n,t=this,o=(this.collectionName="",this.checkSchema=!1,this.simplschema=null,this.rbSchema=null,this.timestamps=!1,this.useVersions=!1,this.versionCollection="",this.createLogs=!0,this.useRB=!1,this.collectionName=e.collectionName,this.simplschema=new simpl_schema_1.default(e.schema),this.timestamps=e.timestamps,this.createLogs=e.createLogs,this.checkSchema=e.checkSchema,this.collectionOptions=e.collectionOptions,e.useReportBuilder&&(this.useRB=!0,n=(0,common_1.deepCopy)(e.schema),e=(0,common_1.buildRbLookups)(e.reportBuilderLookupTables,n,[]),this.rbSchema=(0,common_1.buildRbSchema)(e)),setInterval(function(){index_1.ResolveIOServer&&index_1.ResolveIOServer.getMainServer()&&index_1.ResolveIOServer.getMongoManager()&&index_1.ResolveIOServer.getMongoManager().getServerCollections().length&&(index_1.ResolveIOServer.getMongoManager().registerCollection(t),clearInterval(o))},1))}var e;return MongoManagerCollection.prototype.extractIndexNameFromError=function(e){var n=e.match(/Index already exists with a different name: (\S+)/);return(n=!n||n.length<=1?e.match(/existing index:.*name: "([^"]+)"/):n)&&1<n.length?n[1]:null},MongoManagerCollection.prototype.aggregate=function(i,r,e){var a=this;return void 0===e&&(e=!1),new Promise(function(n,t){var o;e?(o=new monitor_manager_1.MonitorMongo("aggregate",a.collectionName,JSON.stringify([i,r])),index_1.ResolveIOServer.getMainDB().collection(a.collectionName,a.collectionOptions).aggregate(i,r).toArray().then(function(e){o.finish(),n(e)},function(e){o.finish(),console.log(new Date,"Error Aggregate",a.collectionName,i,r,e),t(e)})):index_1.ResolveIOServer.getMongoManager().aggregate(a.collectionName,i,r).then(function(e){n(e)},function(e){t(e)})})},MongoManagerCollection.prototype.aggregateCount=function(r,a){return __awaiter(this,void 0,void 0,function(){var i=this;return __generator(this,function(e){return[2,new Promise(function(n,t){var o=new monitor_manager_1.MonitorMongo("aggregateCount",i.collectionName,JSON.stringify([r,a]));index_1.ResolveIOServer.getMainDB().collection(i.collectionName,i.collectionOptions).aggregate(r,a).toArray().then(function(e){o.finish(),n(e.length)},function(e){o.finish(),console.log(new Date,"Error Aggregate",i.collectionName,r,a,e),t(0)})})]})})},MongoManagerCollection.prototype.aggregateCursor=function(e,n){var t=new monitor_manager_1.MonitorMongo("aggregateCursor",this.collectionName,JSON.stringify([e,n])),e=index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).aggregate(e,n);return e.on("close",function(e){return t.finish(),e}),e},MongoManagerCollection.prototype.aggregateStream=function(e,n,t){var o=new monitor_manager_1.MonitorMongo("aggregateStream",this.collectionName,JSON.stringify([e,n,t])),e=index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).aggregate(e,n).stream(t);return e.on("end",function(e){return o.finish(),e}).on("error",function(e){return o.finish(),e}).on("close",function(e){return o.finish(),e}),e},MongoManagerCollection.prototype.bulkWrite=function(y,I,w,x,N){return void 0===w&&(w=!1),void 0===x&&(x=!1),void 0===N&&(N=!1),__awaiter(this,void 0,void 0,function(){var n,t,o,i,r,a,s,c,l,d,g,u,_,h,v,m,f,p,M,O,S;return __generator(this,function(e){switch(e.label){case 0:if(!y.length)return[2,null];n=1e3,t=0,e.label=1;case 1:if(!(t<y.length))return[3,18];o=y.slice(t,t+n),i=[],r=[];try{for(O=void 0,a=__values(o),s=a.next();!s.done;s=a.next()){if(c=s.value,l=Object.keys(c)[0],d=c[l],this.checkSchema&&!w){if(g=this.simplschema.newContext(),u=void 0,"insertOne"===l)u=g.validate(d.document);else if("replaceOne"===l)u=g.validate(d.replacement);else if("updateOne"===l||"updateMany"===l)u=g.validate(d.update,{modifier:!0});else{if("deleteOne"!==l&&"deleteMany"!==l)throw new Error("Unsupported operation type: ".concat(l));u=!0}if(!u)throw new Error("Schema validation failed for ".concat(l,": ").concat(JSON.stringify(g.validationErrors())))}if("insertOne"===l)this.timestamps&&(d.document.createdAt=new Date,d.document.updatedAt=new Date),!x&&this.createLogs&&i.push({insertOne:{document:{_id:objectIdHexString(),type:"document",collection:this.collectionName,id_document:d.document._id||objectIdHexString(),payload:(0,common_1.getBinarySize)(JSON.stringify(d.document))<2e5?JSON.stringify(d.document,null,2):"Too Big",method:"insertOne",id_user:"",user:"",messageId:0,route:"",createdAt:new Date}}}),!N&&this.useVersions&&(_=__assign(__assign({},d.document),{__v:0,_id:{_id:d.document._id||objectIdHexString(),__v:0}}),r.push({insertOne:{document:_}})),c[l].document=d.document;else if("updateOne"===l||"updateMany"===l)this.timestamps&&(d.update.$set||(d.update.$set={}),d.update.$set.updatedAt=new Date),!N&&this.useVersions&&(d.update.$inc||(d.update.$inc={}),d.update.$inc.__v=1),!x&&this.createLogs&&i.push({insertOne:{document:{_id:objectIdHexString(),type:"document",collection:this.collectionName,id_document:d.filter._id||null,payload:(0,common_1.getBinarySize)(JSON.stringify(d.update))<2e5?JSON.stringify(d.update,null,2):"Too Big",method:l,id_user:"",user:"",messageId:0,route:"",createdAt:new Date}}}),!N&&this.useVersions&&r.push({filter:d.filter});else if("replaceOne"===l)this.timestamps&&(d.replacement.updatedAt=new Date),!N&&this.useVersions&&(d.replacement.__v=(d.replacement.__v||0)+1),!x&&this.createLogs&&i.push({insertOne:{document:{_id:objectIdHexString(),type:"document",collection:this.collectionName,id_document:d.filter._id||null,payload:(0,common_1.getBinarySize)(JSON.stringify(d.replacement))<2e5?JSON.stringify(d.replacement,null,2):"Too Big",method:"replaceOne",id_user:"",user:"",messageId:0,route:"",createdAt:new Date}}}),!N&&this.useVersions&&r.push({filter:d.filter}),c[l].replacement=d.replacement;else{if("deleteOne"!==l&&"deleteMany"!==l)throw new Error("Unsupported operation type: ".concat(l));!x&&this.createLogs&&i.push({insertOne:{document:{_id:objectIdHexString(),type:"document",collection:this.collectionName,id_document:d.filter._id||null,payload:(0,common_1.getBinarySize)(JSON.stringify(d.filter))<2e5?JSON.stringify(d.filter,null,2):"Too Big",method:l,id_user:"",user:"",messageId:0,route:"",createdAt:new Date}}}),!N&&this.useVersions&&r.push({filter:d.filter})}}}catch(e){O={error:e}}finally{try{s&&!s.done&&(S=a.return)&&S.call(a)}finally{if(O)throw O.error}}if(h=[],!(!N&&this.useVersions&&0<r.length))return[3,7];e.label=2;case 2:return e.trys.push([2,6,,7]),v=r.map(function(e){return e.filter}),[4,index_1.ResolveIOServer.getMainDB().collection(this.collectionName).find({$or:v}).toArray()];case 3:return(h=e.sent(),0<(v=h.map(function(e){return{insertOne:{document:__assign(__assign({},e),{_id:{_id:e._id,__v:e.__v}})}}})).length)?[4,index_1.ResolveIOServer.getMainDB().collection(this.versionCollection).bulkWrite(v,{ordered:!1})]:[3,5];case 4:e.sent(),e.label=5;case 5:return[3,7];case 6:return f=e.sent(),console.error("Error during version creation:",f),[3,7];case 7:return m=new monitor_manager_1.MonitorMongo("bulkWrite",this.collectionName,JSON.stringify([o,I])),[4,index_1.ResolveIOServer.getMainDB().collection(this.collectionName).bulkWrite(o,I)];case 8:return(e.sent(),m.finish(),!x&&this.createLogs&&0<i.length)?[4,index_1.ResolveIOServer.getMainDB().collection("logs").bulkWrite(i)]:[3,10];case 9:e.sent(),e.label=10;case 10:if(N||!this.useVersions)return[3,16];e.label=11;case 11:return e.trys.push([11,15,,16]),f=h.map(function(e){return e._id}),p=[{$match:{"_id._id":{$in:f}}},{$sort:{"_id._id":1,"_id.__v":-1}},{$group:{_id:"$_id._id",versions:{$push:"$_id"}}},{$project:{versionsToDelete:{$slice:["$versions",5,{$size:"$versions"}]}}},{$unwind:"$versionsToDelete"},{$replaceRoot:{newRoot:{_id:"$versionsToDelete"}}}],[4,index_1.ResolveIOServer.getMainDB().collection(this.versionCollection).aggregate(p).toArray()];case 12:return 0<(p=e.sent()).length?[4,index_1.ResolveIOServer.getMainDB().collection(this.versionCollection).deleteMany({_id:{$in:p.map(function(e){return e._id})}})]:[3,14];case 13:e.sent(),e.label=14;case 14:return[3,16];case 15:return M=e.sent(),console.error("Error during version cleanup:",M),[3,16];case 16:return t+=n,[4,new Promise(function(e){return setImmediate(e)})];case 17:return e.sent(),index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(this.collectionName),[3,1];case 18:return[2,{ok:1}]}})})},MongoManagerCollection.prototype.countDocuments=function(a,s,c){var e=this;return void 0===a&&(a={}),void 0===c&&(c=!1),new Promise(function(i,r){return __awaiter(e,void 0,void 0,function(){var n,t,o=this;return __generator(this,function(e){switch(e.label){case 0:return(e.trys.push([0,4,,5]),0===Object.keys(a).length)?[4,index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).estimatedDocumentCount(s)]:[3,2];case 1:return t=e.sent(),i(t),[3,3];case 2:c?(n=new monitor_manager_1.MonitorMongo("countDocuments",this.collectionName,JSON.stringify([a,s])),index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).countDocuments(a,s).then(function(e){n.finish(),i(e)},function(e){n.finish(),console.log(new Date,"Error Count Documents",o.collectionName,a,s,e),r(e)})):index_1.ResolveIOServer.getMongoManager().countDocuments(this.collectionName,a,s).then(function(e){return i(e)},function(e){return r(e)}),e.label=3;case 3:return[3,5];case 4:return t=e.sent(),console.log(new Date,"Error Count Documents (Stats)",this.collectionName,a,s,t),r(t),[3,5];case 5:return[2]}})})})},MongoManagerCollection.prototype.create=function(e,n){return Array.isArray(e)?1===e.length?this.insertOne(e[0],n):this.insertMany(e,n):this.insertOne(e,n)},MongoManagerCollection.prototype.createIndex=function(i,r){var e=this;return new Promise(function(t,o){return __awaiter(e,void 0,void 0,function(){var n;return __generator(this,function(e){switch(e.label){case 0:return e.trys.push([0,2,,3]),[4,index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).indexes()];case 1:return(n=e.sent(),n.some(function(e){return JSON.stringify(e.key)===JSON.stringify(i)}))?[2,t("Index already exists")]:(MongoManagerCollection.indexQueue.push({action:"createIndex",collection:this,specs:[i],options:r},function(e,n){e?o(e):t(n)}),[3,3]);case 2:return n=e.sent(),o(n),[3,3];case 3:return[2]}})})})},MongoManagerCollection.prototype.createIndexes=function(r,a){var e=this;return new Promise(function(o,i){return __awaiter(e,void 0,void 0,function(){var t,n;return __generator(this,function(e){switch(e.label){case 0:return e.trys.push([0,2,,3]),[4,index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).indexes()];case 1:return(t=e.sent(),0===(n=r.filter(function(n){return!t.some(function(e){return JSON.stringify(e.key)===JSON.stringify(n.key)})})).length)?[2,o(["All indexes already exist"])]:(MongoManagerCollection.indexQueue.push({action:"createIndexes",collection:this,specs:[n],options:a},function(e,n){e?i(e):o(n)}),[3,3]);case 2:return n=e.sent(),i(n),[3,3];case 3:return[2]}})})})},MongoManagerCollection.prototype.deleteMany=function(l,d,g){var e=this;return void 0===l&&(l={}),void 0===g&&(g=!1),new Promise(function(s,c){return __awaiter(e,void 0,void 0,function(){var n,t,o,i,r,a=this;return __generator(this,function(e){switch(e.label){case 0:return this.createLogs&&!g||this.useVersions?[4,this.find(l)]:[3,2];case 1:for(n=e.sent(),t=0;t<n.length;t++)o=n[t],this.createLogs&&!g&&index_1.ResolveIOServer.getMainDB().collection("logs").insertOne({_id:objectIdHexString(),type:"document",collection:this.collectionName,id_document:o._id,payload:(0,common_1.getBinarySize)(JSON.stringify([o,l,d]))<2e5?JSON.stringify([o,l,d],null,2):"Too Big",method:"deleteMany",id_user:"",user:"",messageId:0,route:"",createdAt:new Date}),this.useVersions&&((i=(0,common_1.deepCopy)(o))._id={_id:o._id,__v:o.__v},index_1.ResolveIOServer.getMongoManager().collection(this.versionCollection).replaceOne({_id:{_id:o._id,__v:o.__v}},i,{upsert:!0}),index_1.ResolveIOServer.getMongoManager().collection(this.versionCollection).deleteMany({$and:[{"_id._id":o._id},{"_id.__v":{$lt:o.__v-1}}]}));e.label=2;case 2:return r=new monitor_manager_1.MonitorMongo("deleteMany",this.collectionName,JSON.stringify([l,d])),index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).deleteMany(l,d).then(function(e){r.finish(),e.acknowledged?(index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(a.collectionName),s(e.deletedCount)):c(e.acknowledged)},function(e){r.finish(),console.log(new Date,"Error Delete Many",a.collectionName,l,d,e),c(e)}),[2]}})})})},MongoManagerCollection.prototype.deleteOne=function(a,s,c){var e=this;return void 0===a&&(a={}),void 0===c&&(c=!1),new Promise(function(r,o){return __awaiter(e,void 0,void 0,function(){var i,n,t=this;return __generator(this,function(e){return this.createLogs&&!c?(i=new monitor_manager_1.MonitorMongo("findOneAndDelete",this.collectionName,JSON.stringify([a,s])),index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).findOneAndDelete(a,s).then(function(o){return __awaiter(t,void 0,void 0,function(){var n,t;return __generator(this,function(e){return i.finish(),(n=o.value)?(this.createLogs&&!c&&index_1.ResolveIOServer.getMainDB().collection("logs").insertOne({_id:objectIdHexString(),type:"document",collection:this.collectionName,id_document:n._id,payload:(0,common_1.getBinarySize)(JSON.stringify([n,a,s]))<2e5?JSON.stringify([n,a,s],null,2):"Too Big",method:"deleteOne",id_user:"",user:"",messageId:0,route:"",createdAt:new Date}),this.useVersions&&((t=(0,common_1.deepCopy)(n))._id={_id:n._id,__v:n.__v},index_1.ResolveIOServer.getMongoManager().collection(this.versionCollection).replaceOne({_id:{_id:n._id,__v:n.__v}},t,{upsert:!0}),index_1.ResolveIOServer.getMongoManager().collection(this.versionCollection).deleteMany({$and:[{"_id._id":n._id},{"_id.__v":{$lt:n.__v-1}}]})),index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(this.collectionName),r(1)):r(0),[2]})})},function(e){i.finish(),console.log(new Date,"Error Find One And Delete",t.collectionName,a,s,e),o(e)})):(n=new monitor_manager_1.MonitorMongo("deleteOne",this.collectionName,JSON.stringify([a,s])),index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).deleteOne(a,s).then(function(e){n.finish(),e.acknowledged?(index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(t.collectionName),r(e.deletedCount)):o(e.acknowledged)},function(e){n.finish(),console.log(new Date,"Error Delete One",t.collectionName,a,s,e),o(e)})),[2]})})})},MongoManagerCollection.prototype.distinct=function(e,i,r){var a=this;return new Promise(function(n,t){var o=new monitor_manager_1.MonitorMongo("distinct",a.collectionName,JSON.stringify([e,i,r]));index_1.ResolveIOServer.getMainDB().collection(a.collectionName,a.collectionOptions).distinct(e,i,r).then(function(e){o.finish(),n(e)},function(e){o.finish(),console.log(new Date,"Error Distinct",a.collectionName,i,r,e),t(e)})})},MongoManagerCollection.prototype.drop=function(i){var r=this;return new Promise(function(n,t){var o=new monitor_manager_1.MonitorMongo("drop",r.collectionName,JSON.stringify([i]));index_1.ResolveIOServer.getMainDB().collection(r.collectionName,r.collectionOptions).drop(i).then(function(e){o.finish(),n(e)},function(e){o.finish(),console.log(new Date,"Error Count Documents",r.collectionName,i,e),t(e)})})},MongoManagerCollection.prototype.dropIndex=function(i,r){var a=this;return new Promise(function(n,t){var o=new monitor_manager_1.MonitorMongo("dropIndex",a.collectionName,JSON.stringify([i,r]));index_1.ResolveIOServer.getMainDB().collection(a.collectionName,a.collectionOptions).dropIndex(i,r).then(function(e){o.finish(),n(e)},function(e){o.finish(),console.log(new Date,"Error Drop Index",a.collectionName,i,r,e),t(e)})})},MongoManagerCollection.prototype.dropIndexes=function(i){var r=this;return new Promise(function(n,t){var o=new monitor_manager_1.MonitorMongo("dropIndexes",r.collectionName,JSON.stringify([i]));index_1.ResolveIOServer.getMainDB().collection(r.collectionName,r.collectionOptions).dropIndexes(i).then(function(e){o.finish(),n(e)},function(e){o.finish(),console.log(new Date,"Error Drop Indexes",r.collectionName,i,e),t(e)})})},MongoManagerCollection.prototype.find=function(r,a,s){var e=this;return void 0===r&&(r={}),void 0===s&&(s=!1),new Promise(function(o,i){return __awaiter(e,void 0,void 0,function(){var n,t=this;return __generator(this,function(e){return s?(n=new monitor_manager_1.MonitorMongo("find",this.collectionName,JSON.stringify([r,a])),index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).find(r,a).toArray().then(function(e){n.finish(),o(e)},function(e){n.finish(),console.log(new Date,"Error Find",t.collectionName,r,a,e),i(e)})):index_1.ResolveIOServer.getMongoManager().find(this.collectionName,r,a).then(function(e){o(e)},function(e){i(e)}),[2]})})})},MongoManagerCollection.prototype.findById=function(i,r){var a=this;return new Promise(function(n,t){var o=new monitor_manager_1.MonitorMongo("findById",a.collectionName,JSON.stringify([{_id:i},r]));index_1.ResolveIOServer.getMainDB().collection(a.collectionName,a.collectionOptions).findOne({_id:i},r).then(function(e){o.finish(),n(e)},function(e){o.finish(),console.log(new Date,"Error Find By Id",a.collectionName,{_id:i},r,e),t(e)})})},MongoManagerCollection.prototype.findCount=function(i,r){var a=this;return void 0===i&&(i={}),new Promise(function(n,t){var o=new monitor_manager_1.MonitorMongo("findCount",a.collectionName,JSON.stringify([i,r]));index_1.ResolveIOServer.getMainDB().collection(a.collectionName,a.collectionOptions).find(i,r).count().then(function(e){o.finish(),n(e)},function(e){o.finish(),console.log(new Date,"Error Find Count",a.collectionName,i,r,e),t(e)})})},MongoManagerCollection.prototype.findCursor=function(e,n){void 0===e&&(e={});var t=new monitor_manager_1.MonitorMongo("findCursor",this.collectionName,JSON.stringify([e,n])),o=index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).find(e,n);return o.on("close",function(e){return t.finish(),o.removeAllListeners(),e}),o},MongoManagerCollection.prototype.findStream=function(e,n,t){void 0===e&&(e={});var o=new monitor_manager_1.MonitorMongo("findStream",this.collectionName,JSON.stringify([e,n,t])),e=index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).find(e,n).stream(t);return e.on("end",function(e){return o.finish(),e}).on("error",function(e){return o.finish(),e}).on("close",function(e){return o.finish(),e}),e},MongoManagerCollection.prototype.findOne=function(i,r,e){var a=this;return void 0===i&&(i={}),void 0===e&&(e=!1),new Promise(function(n,t){var o;e?(o=new monitor_manager_1.MonitorMongo("findOne",a.collectionName,JSON.stringify([i,r])),index_1.ResolveIOServer.getMainDB().collection(a.collectionName,a.collectionOptions).findOne(i,r).then(function(e){o.finish(),n(e)},function(e){o.finish(),console.log(new Date,"Error Find One",a.collectionName,i,r,e),t(e)})):index_1.ResolveIOServer.getMongoManager().findOne(a.collectionName,i,r).then(function(e){n(e)},function(e){t(e)})})},MongoManagerCollection.prototype.findOneAndDelete=function(r,a,s){var e=this;return void 0===r&&(r={}),void 0===s&&(s=!1),new Promise(function(i,n){return __awaiter(e,void 0,void 0,function(){var t,o=this;return __generator(this,function(e){return t=new monitor_manager_1.MonitorMongo("findOneAndDelete",this.collectionName,JSON.stringify([r,a])),index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).findOneAndDelete(r,a).then(function(e){t.finish();var n,e=e.value;e?(o.createLogs&&!s&&index_1.ResolveIOServer.getMainDB().collection("logs").insertOne({_id:objectIdHexString(),type:"document",collection:o.collectionName,id_document:e._id,payload:(0,common_1.getBinarySize)(JSON.stringify([e,r,a]))<2e5?JSON.stringify([e,r,a],null,2):"Too Big",method:"findOneAndDelete",id_user:"",user:"",messageId:0,route:"",createdAt:new Date}),o.useVersions&&((n=(0,common_1.deepCopy)(e))._id={_id:e._id,__v:e.__v},index_1.ResolveIOServer.getMongoManager().collection(o.versionCollection).replaceOne({_id:{_id:e._id,__v:e.__v}},n,{upsert:!0})),index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(o.collectionName),i(e)):i(null)},function(e){t.finish(),console.log(new Date,"Error Find One And Delete",o.collectionName,r,a,e),n(e)}),[2]})})})},MongoManagerCollection.prototype.findOneAndReplace=function(s,c,l,d,g){var e=this;return void 0===s&&(s={}),void 0===d&&(d=!1),void 0===g&&(g=!1),new Promise(function(r,a){return __awaiter(e,void 0,void 0,function(){var n,t,o,i=this;return __generator(this,function(e){return!this.checkSchema||g||(n=this.simplschema.newContext(),n.validate(c))?(t=new Date,this.timestamps&&(c.updatedAt=t),l&&l.upsert&&(c._id||(c._id=objectIdHexString()),this.useVersions&&(c.__v=0),this.timestamps)&&!c.createdAt&&(c.createdAt=t),o=new monitor_manager_1.MonitorMongo("findOneAndReplace",this.collectionName,JSON.stringify([s,c,l])),index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).findOneAndReplace(s,c,l).then(function(e){o.finish();var n,e=e.value;e?(i.createLogs&&!d&&index_1.ResolveIOServer.getMainDB().collection("logs").insertOne({_id:objectIdHexString(),type:"document",collection:i.collectionName,id_document:e._id,payload:(0,common_1.getBinarySize)(JSON.stringify([e,s,c,l]))<2e5?JSON.stringify([e,s,c,l],null,2):"Too Big",method:"findOneAndReplace",id_user:"",user:"",messageId:0,route:"",createdAt:new Date}),i.useVersions&&((n=(0,common_1.deepCopy)(e))._id={_id:e._id,__v:e.__v},index_1.ResolveIOServer.getMongoManager().collection(i.versionCollection).replaceOne({_id:{_id:e._id,__v:e.__v}},n,{upsert:!0})),index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(i.collectionName),r(e)):r(null)},function(e){o.finish(),console.log(new Date,"Error Find One And Replace",i.collectionName,s,l,e),a(e)})):(console.log(new Date,this.collectionName,"Schema Errors - findOneAndReplace",n.validationErrors()),index_1.ResolveIOServer.getMainServer().getMethodManager().callMethodInternal.call(index_1.ResolveIOServer.getMainServer().getMethodManager(),"insertErrorLog","Schema Failed on findOneAndReplace - "+this.collectionName,[n.validationErrors(),c]),a(n.validationErrors())),[2]})})})},MongoManagerCollection.prototype.findOneAndUpdate=function(s,c,l,d,g){var e=this;return void 0===s&&(s={}),void 0===d&&(d=!1),void 0===g&&(g=!1),new Promise(function(r,a){return __awaiter(e,void 0,void 0,function(){var n,t,o,i=this;return __generator(this,function(e){return!this.checkSchema||g||(n=this.simplschema.newContext(),n.validate(c,{modifier:!0}))?(this.timestamps&&(t=new Date,c.$set?c.$set.updatedAt=t:c.$set={updatedAt:t}),l&&l.upsert&&(c.$setOnInsert?(c.$setOnInsert._id||(c.$setOnInsert._id=objectIdHexString()),this.timestamps&&!c.$setOnInsert.createdAt&&(c.$setOnInsert.createdAt=new Date)):this.timestamps?c.$setOnInsert={_id:objectIdHexString(),createdAt:new Date}:c.$setOnInsert={_id:objectIdHexString()}),o=new monitor_manager_1.MonitorMongo("findOneAndUpdate",this.collectionName,JSON.stringify([s,c,l])),index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).findOneAndUpdate(s,c,l).then(function(e){o.finish();var n,e=e.value;e?(i.createLogs&&!d&&index_1.ResolveIOServer.getMainDB().collection("logs").insertOne({_id:objectIdHexString(),type:"document",collection:i.collectionName,id_document:e._id,payload:(0,common_1.getBinarySize)(JSON.stringify([e,s,c,l]))<2e5?JSON.stringify([e,s,c,l],null,2):"Too Big",method:"findOneAndUpdate",id_user:"",user:"",messageId:0,route:"",createdAt:new Date}),i.useVersions&&((n=(0,common_1.deepCopy)(e))._id={_id:e._id,__v:e.__v},index_1.ResolveIOServer.getMongoManager().collection(i.versionCollection).replaceOne({_id:{_id:e._id,__v:e.__v}},n,{upsert:!0})),index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(i.collectionName),r(e)):r(null)},function(e){o.finish(),console.log(new Date,"Error Find One And Update",i.collectionName,s,l,e),a(e)})):(console.log(new Date,this.collectionName,"Schema Errors - findOneAndUpdate",n.validationErrors()),index_1.ResolveIOServer.getMainServer().getMethodManager().callMethodInternal.call(index_1.ResolveIOServer.getMainServer().getMethodManager(),"insertErrorLog","Schema Failed on findOneAndUpdate - "+this.collectionName,[n.validationErrors(),c]),a(n.validationErrors())),[2]})})})},MongoManagerCollection.prototype.indexes=function(i){var r=this;return new Promise(function(n,t){var o=new monitor_manager_1.MonitorMongo("indexes",r.collectionName,JSON.stringify([i]));index_1.ResolveIOServer.getMainDB().collection(r.collectionName,r.collectionOptions).indexes(i).then(function(e){o.finish(),n(e)},function(e){o.finish(),console.log(new Date,"Error Indexes",r.collectionName,i,e),t(e)})})},MongoManagerCollection.prototype.indexExists=function(i,r){var a=this;return new Promise(function(n,t){var o=new monitor_manager_1.MonitorMongo("indexExists",a.collectionName,JSON.stringify([i,r]));index_1.ResolveIOServer.getMainDB().collection(a.collectionName,a.collectionOptions).indexExists(i,r).then(function(e){o.finish(),n(e)},function(e){o.finish(),console.log(new Date,"Error Index Exists",a.collectionName,i,r,e),t(e)})})},MongoManagerCollection.prototype.insertMany=function(d,g,u,_,h){var e=this;return void 0===u&&(u=!1),void 0===_&&(_=!1),void 0===h&&(h=!1),new Promise(function(c,l){return __awaiter(e,void 0,void 0,function(){var t,n,o,i,r,a,s=this;return __generator(this,function(e){if(d.length){for(t=[],this.checkSchema&&!_&&d.forEach(function(e){var n=s.simplschema.newContext();n.validate(e)?t.push(!0):(console.log(new Date,s.collectionName,"Schema Errors - insertMany",n.validationErrors()),index_1.ResolveIOServer.getMainServer().getMethodManager().callMethodInternal.call(index_1.ResolveIOServer.getMainServer().getMethodManager(),"insertErrorLog","Schema Failed on insertMany - "+s.collectionName,[n.validationErrors(),e]),t.push(!1))}),n=this.checkSchema?d.filter(function(e,n){return t[n]}):d,o=0;o<n.length;o++)(i=n[o])._id||(i._id=objectIdHexString()),this.timestamps&&(r=new Date,i.createdAt||(i.createdAt=r),i.updatedAt||(i.updatedAt=r)),this.useVersions&&!i.hasOwnProperty("__v")&&(i.__v=0),this.createLogs&&!u&&index_1.ResolveIOServer.getMainDB().collection("logs").insertOne({_id:objectIdHexString(),type:"document",collection:this.collectionName,id_document:i._id,payload:(0,common_1.getBinarySize)(JSON.stringify([i,g]))<2e5?JSON.stringify([i,g],null,2):"Too Big",method:"insertMany",id_user:"",user:"",messageId:0,route:"",createdAt:new Date});n.length&&(a=null,h||(a=new monitor_manager_1.MonitorMongo("insertMany",this.collectionName,JSON.stringify([n,g]))),index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).insertMany(n,g).then(function(e){a&&a.finish(),e.acknowledged?(index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(s.collectionName),c(n)):l(e.acknowledged)},function(e){a&&a.finish(),console.log(new Date,"Error Insert Many",s.collectionName,n,g,e),l(e)}))}else c([]);return[2]})})})},MongoManagerCollection.prototype.insertOne=function(s,c,l,d){var e=this;return void 0===l&&(l=!1),void 0===d&&(d=!1),new Promise(function(r,a){return __awaiter(e,void 0,void 0,function(){var n,t,o,i=this;return __generator(this,function(e){return s._id||(s._id=objectIdHexString()),!this.checkSchema||d||(n=this.simplschema.newContext(),n.validate(s))?(this.timestamps&&(t=new Date,s.createdAt||(s.createdAt=t),s.updatedAt||(s.updatedAt=t)),this.createLogs&&!l&&index_1.ResolveIOServer.getMainDB().collection("logs").insertOne({_id:objectIdHexString(),type:"document",collection:this.collectionName,id_document:s._id,payload:(0,common_1.getBinarySize)(JSON.stringify([s,c]))<2e5?JSON.stringify([s,c],null,2):"Too Big",method:"insertOne",id_user:"",user:"",messageId:0,route:"",createdAt:new Date}),this.useVersions&&!s.hasOwnProperty("__v")&&(s.__v=0),o=new monitor_manager_1.MonitorMongo("insertOne",this.collectionName,JSON.stringify([s,c])),index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).insertOne(s,c).then(function(e){o.finish(),e.acknowledged?(index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(i.collectionName),r(s)):a(e.acknowledged)},function(e){o.finish(),console.log(new Date,"Error Insert One",i.collectionName,s,c,e),a(e)})):(console.log(new Date,this.collectionName,"Schema Errors - insertOne",n.validationErrors()),index_1.ResolveIOServer.getMainServer().getMethodManager().callMethodInternal.call(index_1.ResolveIOServer.getMainServer().getMethodManager(),"insertErrorLog","Schema Failed on insertOne - "+this.collectionName,[n.validationErrors(),s]),a(n.validationErrors())),[2]})})})},MongoManagerCollection.prototype.listIndexes=function(e){var n=new monitor_manager_1.MonitorMongo("listIndexes",this.collectionName,JSON.stringify([e])),e=index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).listIndexes(e);return e.on("close",function(e){return n.finish(),e}),e},MongoManagerCollection.prototype.rename=function(i,r){var a=this;return new Promise(function(n,t){var o=new monitor_manager_1.MonitorMongo("rename",a.collectionName,JSON.stringify([i,r]));index_1.ResolveIOServer.getMainDB().collection(a.collectionName,a.collectionOptions).rename(i,r).then(function(e){o.finish(),n(e)},function(e){o.finish(),console.log(new Date,"Error Rename",a.collectionName,i,r,e),t(e)})})},MongoManagerCollection.prototype.replaceOne=function(v,m,f,p,M,O){var e=this;return void 0===p&&(p=!1),void 0===M&&(M=!1),void 0===O&&(O=null),new Promise(function(_,h){return __awaiter(e,void 0,void 0,function(){var n,t,o,i,r,a,s,c,l,d,g,u=this;return __generator(this,function(e){switch(e.label){case 0:return!this.checkSchema||M||(t=this.simplschema.newContext(),t.validate(m))?(n=new Date,this.timestamps&&(m.updatedAt=n),this.useVersions?O?[3,2]:[4,this.findOne(v,null,!0)]:[3,8]):(console.log(new Date,this.collectionName,"Schema Errors - replaceOne",t.validationErrors()),index_1.ResolveIOServer.getMainServer().getMethodManager().callMethodInternal.call(index_1.ResolveIOServer.getMainServer().getMethodManager(),"insertErrorLog","Schema Failed on replaceOne - "+this.collectionName,[t.validationErrors(),m]),h(t.validationErrors()),[2]);case 1:O=e.sent(),e.label=2;case 2:return O?(this.timestamps&&!m.createdAt&&O.createdAt&&(m.createdAt=O.createdAt),O.__v!==m.__v?[3,3]:(m.__v+=1,(t=(0,common_1.deepCopy)(O))._id={_id:O._id,__v:O.__v},index_1.ResolveIOServer.getMongoManager().collection(this.versionCollection).replaceOne({_id:{_id:O._id,__v:O.__v}},t,{upsert:!0}),4<=O.__v&&index_1.ResolveIOServer.getMongoManager().collection(this.versionCollection).deleteMany({$and:[{"_id._id":O._id},{"_id.__v":{$lt:O.__v-4}}]}),this.createLogs&&!p&&index_1.ResolveIOServer.getMainDB().collection("logs").insertOne({_id:objectIdHexString(),type:"document",collection:this.collectionName,id_document:O._id,payload:(0,common_1.getBinarySize)(JSON.stringify([O,v,m,f]))<2e5?JSON.stringify([O,v,m,f],null,2):"Too Big",method:"replaceOne",id_user:"",user:"",messageId:0,route:"",createdAt:new Date}),o=new monitor_manager_1.MonitorMongo("replaceOne",this.collectionName,JSON.stringify([v,m,f])),index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).replaceOne(v,m,f).then(function(e){o.finish(),e.acknowledged?(index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(u.collectionName),_(e.modifiedCount)):h(e.acknowledged)},function(e){o.finish(),console.log(new Date,"Error Replace One",u.collectionName,v,m,f,e),h(e)}),[3,5])):[3,6];case 3:return console.log("invalid version - "+this.collectionName,O.__v,m.__v),[4,index_1.ResolveIOServer.getMongoManager().collection(this.versionCollection).findOne({_id:{_id:O._id,__v:m.__v}},null,!0)];case 4:(i=e.sent())?(r=O._id,a=O.__v,(s=(0,common_1.getMongoMergeUpdatedDoc)(m,O,i))._id=r,s.__v=a+1,this.createLogs&&!p&&index_1.ResolveIOServer.getMainDB().collection("logs").insertOne({_id:objectIdHexString(),type:"document",collection:this.collectionName,id_document:r,payload:(0,common_1.getBinarySize)(JSON.stringify(["invalidVersion - merge",O,v,s,f]))<2e5?JSON.stringify(["invalidVersion - merge",O,v,s,f],null,2):"Too Big",method:"replaceOne",id_user:"",user:"",messageId:0,route:"",createdAt:new Date}),c=new monitor_manager_1.MonitorMongo("replaceOne",this.collectionName,JSON.stringify([v,s,f])),index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).replaceOne(v,s,f).then(function(e){c.finish(),e.acknowledged?(index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(u.collectionName),_(e.modifiedCount)):h(e.acknowledged)},function(e){c.finish(),console.log(new Date,"Error Replace One",u.collectionName,v,s,f,e),h(e)})):h("Invalid Version And Could Not Find History - DB: "+O.__v+", Trying to update with :"+m.__v),e.label=5;case 5:return[3,7];case 6:f&&f.upsert?(this.timestamps&&(m.createdAt=n),m._id||(m._id=objectIdHexString()),m.__v=0,this.createLogs&&!p&&index_1.ResolveIOServer.getMainDB().collection("logs").insertOne({_id:objectIdHexString(),type:"document",collection:this.collectionName,id_document:m._id,payload:(0,common_1.getBinarySize)(JSON.stringify(["upsert",v,m,f]))<2e5?JSON.stringify(["upsert",v,m,f],null,2):"Too Big",method:"replaceOne",id_user:"",user:"",messageId:0,route:"",createdAt:new Date}),l=new monitor_manager_1.MonitorMongo("replaceOne",this.collectionName,JSON.stringify([v,m,f])),index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).replaceOne(v,m,f).then(function(e){l.finish(),e.acknowledged?(index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(u.collectionName),_(e.modifiedCount)):h(e.acknowledged)},function(e){l.finish(),console.log(new Date,"Error Replace One",u.collectionName,v,m,f,e),h(e)})):h("No Document"),e.label=7;case 7:return[3,9];case 8:f&&f.upsert&&(this.timestamps&&!m.createdAt&&(m.createdAt=n),m._id||(m._id=objectIdHexString()),m.__v=0),this.createLogs&&!p?(f?f.returnDocument="before":f={returnDocument:"before"},d=new monitor_manager_1.MonitorMongo("findOneAndReplace",this.collectionName,JSON.stringify([v,m,f])),index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).findOneAndReplace(v,m,f).then(function(e){d.finish();e=e.value;e?index_1.ResolveIOServer.getMainDB().collection("logs").insertOne({_id:objectIdHexString(),type:"document",collection:u.collectionName,id_document:e._id,payload:(0,common_1.getBinarySize)(JSON.stringify([e,v,m,f]))<2e5?JSON.stringify([e,v,m,f],null,2):"Too Big",method:"replaceOne",id_user:"",user:"",messageId:0,route:"",createdAt:new Date}):index_1.ResolveIOServer.getMainDB().collection("logs").insertOne({_id:objectIdHexString(),type:"document",collection:u.collectionName,id_document:m._id,payload:(0,common_1.getBinarySize)(JSON.stringify(["upsert",v,m,f]))<2e5?JSON.stringify(["upsert",v,m,f],null,2):"Too Big",method:"replaceOne",id_user:"",user:"",messageId:0,route:"",createdAt:new Date}),index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(u.collectionName),_(1)},function(e){d.finish(),console.log(new Date,"Error Find One And Replace",u.collectionName,v,m,f,e),h(e)})):(g=new monitor_manager_1.MonitorMongo("replaceOne",this.collectionName,JSON.stringify([v,m,f])),index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).replaceOne(v,m,f).then(function(e){g.finish(),e.acknowledged?(index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(u.collectionName),_(e.modifiedCount)):h(e.acknowledged)},function(e){g.finish(),console.log(new Date,"Error Replace One",u.collectionName,v,m,f,e),h(e)})),e.label=9;case 9:return[2]}})})})},MongoManagerCollection.prototype.updateMany=function(d,g,u,_,h,v){var e=this;return void 0===_&&(_=!1),void 0===h&&(h=!1),void 0===v&&(v=!1),new Promise(function(c,l){return __awaiter(e,void 0,void 0,function(){var n,t,o,i,r,a,s=this;return __generator(this,function(e){switch(e.label){case 0:return g.$inc&&"{}"!==JSON.stringify(g.$inc)||g.$set&&"{}"!==JSON.stringify(g.$set)||g.$setOnInsert&&"{}"!==JSON.stringify(g.$setOnInsert)||g.$unset&&"{}"!==JSON.stringify(g.$unset)?(this.timestamps&&(n=new Date,g.$set?g.$set.updatedAt=n:g.$set={updatedAt:n}),!this.checkSchema||h||(n=this.simplschema.newContext(),n.validate(g,{modifier:!0}))?this.useVersions&&!v||this.createLogs&&!_?[4,this.find(d)]:[3,2]:(console.log(new Date,this.collectionName,"Schema Errors - updateMany",n.validationErrors()),index_1.ResolveIOServer.getMainServer().getMethodManager().callMethodInternal.call(index_1.ResolveIOServer.getMainServer().getMethodManager(),"insertErrorLog","Schema Failed on updateMany - "+this.collectionName,[n.validationErrors(),g]),l(n.validationErrors()),[2])):(c(1),[2]);case 1:for(t=e.sent(),o=0;o<t.length;o++)i=t[o],this.createLogs&&!_&&index_1.ResolveIOServer.getMainDB().collection("logs").insertOne({_id:objectIdHexString(),type:"document",collection:this.collectionName,id_document:i._id,payload:(0,common_1.getBinarySize)(JSON.stringify([i,d,g,u]))<2e5?JSON.stringify([i,d,g,u],null,2):"Too Big",method:"updateMany",id_user:"",user:"",messageId:0,route:"",createdAt:new Date}),this.useVersions&&((r=(0,common_1.deepCopy)(i))._id={_id:i._id,__v:i.__v},index_1.ResolveIOServer.getMongoManager().collection(this.versionCollection).replaceOne({_id:{_id:i._id,__v:i.__v}},r,{upsert:!0}),4<=i.__v&&index_1.ResolveIOServer.getMongoManager().collection(this.versionCollection).deleteMany({$and:[{"_id._id":i._id},{"_id.__v":{$lt:i.__v-4}}]}),objectContainsPropertyDeep(g,"__v")||(g.$inc?g.$inc.__v||(g.$inc.__v=1):g.$inc={__v:1}));e.label=2;case 2:return a=new monitor_manager_1.MonitorMongo("updateMany",this.collectionName,JSON.stringify([d,g,u])),index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).updateMany(d,g,u).then(function(e){a.finish(),e.acknowledged?(index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(s.collectionName),c(e.modifiedCount)):l(e.acknowledged)},function(e){a.finish(),console.log(new Date,"Error Update Many",s.collectionName,d,g,u,e),l(e)}),[2]}})})})},MongoManagerCollection.prototype.updateOne=function(d,g,u,_,h){var e=this;return void 0===_&&(_=!1),void 0===h&&(h=!1),new Promise(function(c,l){return __awaiter(e,void 0,void 0,function(){var n,t,o,i,r,a,s=this;return __generator(this,function(e){switch(e.label){case 0:return!this.checkSchema||h||(t=this.simplschema.newContext(),t.validate(g,{modifier:!0}))?g.$inc&&"{}"!==JSON.stringify(g.$inc)||g.$set&&"{}"!==JSON.stringify(g.$set)||g.$setOnInsert&&"{}"!==JSON.stringify(g.$setOnInsert)||g.$unset&&"{}"!==JSON.stringify(g.$unset)?(n=new Date,this.timestamps&&(g.$set?g.$set.updatedAt=n:g.$set={updatedAt:n}),this.useVersions?[4,this.findOne(d,null,!0)]:[3,2]):(c(1),[2]):(console.log(new Date,this.collectionName,"Schema Errors - updateOne",t.validationErrors()),index_1.ResolveIOServer.getMainServer().getMethodManager().callMethodInternal.call(index_1.ResolveIOServer.getMainServer().getMethodManager(),"insertErrorLog","Schema Failed on updateOne - "+this.collectionName,[t.validationErrors(),g]),l(t.validationErrors()),[2]);case 1:return(n=e.sent())?(this.createLogs&&!_&&index_1.ResolveIOServer.getMainDB().collection("logs").insertOne({_id:objectIdHexString(),type:"document",collection:this.collectionName,id_document:n._id,payload:(0,common_1.getBinarySize)(JSON.stringify([n,d,g,u]))<2e5?JSON.stringify([n,d,g,u],null,2):"Too Big",method:"updateOne",id_user:"",user:"",messageId:0,route:"",createdAt:new Date}),(t=(0,common_1.deepCopy)(n))._id={_id:n._id,__v:n.__v},index_1.ResolveIOServer.getMongoManager().collection(this.versionCollection).replaceOne({_id:{_id:n._id,__v:n.__v}},t,{upsert:!0}),4<=n.__v&&index_1.ResolveIOServer.getMongoManager().collection(this.versionCollection).deleteMany({$and:[{"_id._id":n._id},{"_id.__v":{$lt:n.__v-4}}]}),objectContainsPropertyDeep(g,"__v")||(g.$inc?g.$inc.__v||(g.$inc.__v=1):g.$inc={__v:1}),o=new monitor_manager_1.MonitorMongo("updateOne",this.collectionName,JSON.stringify([d,g,u])),index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).updateOne(d,g,u).then(function(e){o.finish(),e.acknowledged?(index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(s.collectionName),c(e.modifiedCount)):l(e.acknowledged)},function(e){o.finish(),console.log(new Date,"Error Update One",s.collectionName,d,g,u,e),l(e)})):u&&u.upsert?(g.$setOnInsert?(g.$setOnInsert._id||(g.$setOnInsert._id=objectIdHexString()),this.timestamps&&!g.$setOnInsert.createdAt&&(g.$setOnInsert.createdAt=new Date)):this.timestamps?g.$setOnInsert={_id:objectIdHexString(),__v:0,createdAt:new Date}:g.$setOnInsert={_id:objectIdHexString(),__v:0},this.createLogs&&!_&&index_1.ResolveIOServer.getMainDB().collection("logs").insertOne({_id:objectIdHexString(),type:"document",collection:this.collectionName,id_document:g.$setOnInsert._id,payload:(0,common_1.getBinarySize)(JSON.stringify(["upsert",d,g,u]))<2e5?JSON.stringify(["upsert",d,g,u],null,2):"Too Big",method:"updateOne",id_user:"",user:"",messageId:0,route:"",createdAt:new Date}),i=new monitor_manager_1.MonitorMongo("updateOne",this.collectionName,JSON.stringify([d,g,u])),index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).updateOne(d,g,u).then(function(e){i.finish(),e.acknowledged?(index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(s.collectionName),c(e.modifiedCount)):l(e.acknowledged)},function(e){i.finish(),console.log(new Date,"Error Update One",s.collectionName,d,g,u,e),l(e)})):l("No Document"),[3,3];case 2:u&&u.upsert&&(g.$setOnInsert?(g.$setOnInsert._id||(g.$setOnInsert._id=objectIdHexString()),this.timestamps&&!g.$setOnInsert.createdAt&&(g.$setOnInsert.createdAt=new Date)):this.timestamps?g.$setOnInsert={_id:objectIdHexString(),createdAt:new Date}:g.$setOnInsert={_id:objectIdHexString()}),this.createLogs&&!_?(u?u.returnDocument="before":u={returnDocument:"before"},r=new monitor_manager_1.MonitorMongo("findOneAndUpdate",this.collectionName,JSON.stringify([d,g,u])),index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).findOneAndUpdate(d,g,u).then(function(e){r.finish();var n=e.value;n?(index_1.ResolveIOServer.getMainDB().collection("logs").insertOne({_id:objectIdHexString(),type:"document",collection:s.collectionName,id_document:n._id,payload:(0,common_1.getBinarySize)(JSON.stringify([n,d,g,u]))<2e5?JSON.stringify([n,d,g,u],null,2):"Too Big",method:"updateOne",id_user:"",user:"",messageId:0,route:"",createdAt:new Date}),c(e.ok)):g.$setOnInsert?(index_1.ResolveIOServer.getMainDB().collection("logs").insertOne({_id:objectIdHexString(),type:"document",collection:s.collectionName,id_document:g.$setOnInsert._id,payload:(0,common_1.getBinarySize)(JSON.stringify(["upsert",d,g,u]))<2e5?JSON.stringify(["upsert",d,g,u],null,2):"Too Big",method:"updateOne",id_user:"",user:"",messageId:0,route:"",createdAt:new Date}),index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(s.collectionName),c(e.ok)):c(0)},function(e){r.finish(),console.log(new Date,"Error Find One And Update",s.collectionName,d,g,u,e),l(e)})):(a=new monitor_manager_1.MonitorMongo("updateOne",this.collectionName,JSON.stringify([d,g,u])),index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).updateOne(d,g,u).then(function(e){a.finish(),e.acknowledged?(index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(s.collectionName),c(e.modifiedCount)):l(e.acknowledged)},function(e){a.finish(),console.log(new Date,"Error Update One",s.collectionName,d,g,u,e),l(e)})),e.label=3;case 3:return[2]}})})})},MongoManagerCollection.prototype.watchCollection=function(e,n){return void 0===e&&(e=[]),index_1.ResolveIOServer.getMainDB().collection(this.collectionName,this.collectionOptions).watch(e,n)},(e=MongoManagerCollection).indexQueue=async_1.default.queue(function(d,g){return __awaiter(void 0,void 0,void 0,function(){var n,t,o,i,r,a,s,c,l;return __generator(e,function(e){switch(e.label){case 0:if(n=d.action,t=d.collection,o=d.specs,i=d.options,!(r=index_1.ResolveIOServer.getMainDB().collection(t.collectionName,t.collectionOptions)))return[2,g(new Error("Collection ".concat(t.collectionName," not found")))];a=new monitor_manager_1.MonitorMongo(n,t.collectionName,JSON.stringify([o,i])),e.label=1;case 1:return e.trys.push([1,3,,10]),[4,r[n].apply(r,__spreadArray(__spreadArray([],__read(o),!1),[i],!1))];case 2:return c=e.sent(),a.finish(),g(null,c),[3,10];case 3:if(85!==(s=e.sent()).code&&!s.message.includes("IndexOptionsConflict"))return[3,9];e.label=4;case 4:return(e.trys.push([4,8,,9]),l=t.extractIndexNameFromError(s.message))?[4,r.dropIndex(l)]:[3,7];case 5:return e.sent(),[4,r[n].apply(r,__spreadArray(__spreadArray([],__read(o),!1),[i],!1))];case 6:return c=e.sent(),a.finish(),g(null,c),[2];case 7:return[3,9];case 8:return l=e.sent(),g(l),[3,9];case 9:return a.finish(),g(s),[3,10];case 10:return[2]}})})},1),MongoManagerCollection}()),MongoManagerUserCollection=function(e){function MongoManagerUserCollection(){return null!==e&&e.apply(this,arguments)||this}return __extends(MongoManagerUserCollection,e),MongoManagerUserCollection.prototype.authenticate=function(a,t){var e=this;return new Promise(function(i,r){return __awaiter(e,void 0,void 0,function(){var n,o=this;return __generator(this,function(e){switch(e.label){case 0:return(n=Math.pow(100,Math.log(a.attempts+1)),n=n<3e5?n:3e5,a.last)?Date.now()-a.last.getTime()<n?(a.last=new Date,[4,user_collection_1.Users.updateOne({_id:a._id},{$set:{last:a.last}})]):[3,2]:[3,3];case 1:return e.sent(),i({data:null,error:"Attempt Too Soon"}),[2];case 2:return[3,4];case 3:a.last=new Date,e.label=4;case 4:return 5<=a.attempts?i({data:null,error:"Too Many Attempts"}):a.salt?pbkdf2(t,a.salt,{iterations:25e3,keylen:512,digestAlgorithm:"sha256"},function(n,t){return __awaiter(o,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return n?[2,r(n)]:scmp(t,Buffer.from(a.hash,"hex"))?(a.last=new Date,a.attempts=0,[4,user_collection_1.Users.updateOne({_id:a._id},{$set:{last:a.last,attempts:a.attempts}})]):[3,2];case 1:return e.sent(),i({data:a,error:""}),[3,4];case 2:return a.last=new Date,a.attempts=a.attempts+1,[4,user_collection_1.Users.updateOne({_id:a._id},{$set:{last:a.last,attempts:a.attempts}})];case 3:e.sent(),5<=a.attempts?i({data:null,error:"Too Many Attempts"}):i({data:null,error:"Invalid Username And Password"}),e.label=4;case 4:return[2]}})})}):i({data:null,error:"No Salt Value Stored"}),[2]}})})})},MongoManagerUserCollection.prototype.serializeUser=function(){return function(e,n){n(null,e.username)}},MongoManagerUserCollection.prototype.deserializeUser=function(){return function(e,n){user_collection_1.Users.findOne({username:e}).then(function(e){n(null,e)},function(e){n(e,null)})}},MongoManagerUserCollection.prototype.setPassword=function(r,a){var e=this;return new Promise(function(o,i){return __awaiter(e,void 0,void 0,function(){var n,t;return __generator(this,function(e){switch(e.label){case 0:return r?[3,1]:(i("No User"),[3,5]);case 1:return a?[3,2]:(i("No Password"),[3,5]);case 2:return[4,randomBytes(32)];case 3:return n=e.sent(),n=n.toString("hex"),[4,pbkdf2Promisified(a,n,{iterations:25e3,keylen:512,digestAlgorithm:"sha256"})];case 4:t=e.sent(),t=Buffer.from(t,"binary").toString("hex"),user_collection_1.Users.updateOne({_id:r._id},{$set:{hash:t,salt:n,services:{},attempts:0}}).then(function(e){return o(e)},function(e){return i(e)}),e.label=5;case 5:return[2]}})})})},MongoManagerUserCollection.prototype.changePassword=function(i,r,a){var e=this;return new Promise(function(t,o){return __awaiter(e,void 0,void 0,function(){var n;return __generator(this,function(e){switch(e.label){case 0:return i?[3,1]:(o("Missing User"),[3,4]);case 1:return r&&a?[3,2]:(o("Missing Password"),[3,4]);case 2:return[4,this.authenticate(i,r)];case 3:(n=e.sent()).data?this.setPassword(i,a).then(function(e){return t(e)},function(e){return o(e)}):o(n.error),e.label=4;case 4:return[2]}})})})},MongoManagerUserCollection.prototype.register=function(o,i){var e=this;return new Promise(function(n,t){return __awaiter(e,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return o.username?[3,1]:(t("Missing Username"),[3,5]);case 1:return[4,user_collection_1.Users.findOne({username:o.username})];case 2:return e.sent()?(t("Username Exists"),[3,5]):[3,3];case 3:return[4,user_collection_1.Users.findOne({email:o.email})];case 4:e.sent()?t("Email Exists"):(o.setPassword(i),n(o)),e.label=5;case 5:return[2]}})})})},MongoManagerUserCollection.prototype.resetAttempts=function(e){return user_collection_1.Users.updateOne({_id:e._id},{$set:{attempts:0}})},MongoManagerUserCollection}(exports.MongoManagerCollection=MongoManagerCollection);function objectIdHexString(){return(new mongodb_1.ObjectId).toHexString()}function pbkdf2(e,n,t,o){crypto.pbkdf2(e,n,t.iterations,t.keylen,t.digestAlgorithm,o)}function pbkdf2Promisified(e,n,i){return new Promise(function(t,o){return pbkdf2(e,n,i,function(e,n){return e?o(e):t(n)})})}function randomBytes(e){return new Promise(function(t,o){return crypto.randomBytes(e,function(e,n){return e?o(e):t(n)})})}function objectContainsPropertyDeep(e,n){var t=Object.keys(e);if(t.some(function(e){return e===n}))return!0;for(var o=0;o<t.length;o++){var i=t[o];if(e[i]&&"object"==typeof e[i]&&objectContainsPropertyDeep(e[i],n))return!0}return!1}exports.MongoManagerUserCollection=MongoManagerUserCollection,exports.objectIdHexString=objectIdHexString;
|
|
2
2
|
//# sourceMappingURL=mongo.manager.js.map
|