@resolveio/server-lib 9.2.19 → 9.2.20

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.
Files changed (221) hide show
  1. package/client-server-app.js +55 -1
  2. package/client-server-app.js.map +1 -1
  3. package/collections/app-status.collection.js +40 -1
  4. package/collections/app-status.collection.js.map +1 -1
  5. package/collections/app-version.collection.js +40 -1
  6. package/collections/app-version.collection.js.map +1 -1
  7. package/collections/counter.collection.js +43 -1
  8. package/collections/counter.collection.js.map +1 -1
  9. package/collections/cron-job-history.collection.js +71 -1
  10. package/collections/cron-job-history.collection.js.map +1 -1
  11. package/collections/cron-job.collection.js +74 -1
  12. package/collections/cron-job.collection.js.map +1 -1
  13. package/collections/email-history.collection.js +55 -1
  14. package/collections/email-history.collection.js.map +1 -1
  15. package/collections/email-verified.collection.js +50 -1
  16. package/collections/email-verified.collection.js.map +1 -1
  17. package/collections/file.collection.js +62 -1
  18. package/collections/file.collection.js.map +1 -1
  19. package/collections/flag.collection.js +44 -1
  20. package/collections/flag.collection.js.map +1 -1
  21. package/collections/log-method-latency.collection.js +53 -1
  22. package/collections/log-method-latency.collection.js.map +1 -1
  23. package/collections/log-subscription.collection.js +57 -1
  24. package/collections/log-subscription.collection.js.map +1 -1
  25. package/collections/log.collection.js +72 -1
  26. package/collections/log.collection.js.map +1 -1
  27. package/collections/logged-in-users.collection.js +58 -1
  28. package/collections/logged-in-users.collection.js.map +1 -1
  29. package/collections/method-call.collection.js +51 -1
  30. package/collections/method-call.collection.js.map +1 -1
  31. package/collections/method-response.collection.js +55 -1
  32. package/collections/method-response.collection.js.map +1 -1
  33. package/collections/monitor-cpu.collection.js +57 -1
  34. package/collections/monitor-cpu.collection.js.map +1 -1
  35. package/collections/monitor-https-inbound.collection.js +66 -1
  36. package/collections/monitor-https-inbound.collection.js.map +1 -1
  37. package/collections/monitor-https-outbound.collection.js +74 -1
  38. package/collections/monitor-https-outbound.collection.js.map +1 -1
  39. package/collections/monitor-memory.collection.js +68 -1
  40. package/collections/monitor-memory.collection.js.map +1 -1
  41. package/collections/monitor-mongo.collection.js +62 -1
  42. package/collections/monitor-mongo.collection.js.map +1 -1
  43. package/collections/notification.collection.js +40 -1
  44. package/collections/notification.collection.js.map +1 -1
  45. package/collections/report-builder-dashboard-builder.collection.js +93 -1
  46. package/collections/report-builder-dashboard-builder.collection.js.map +1 -1
  47. package/collections/report-builder-library.collection.js +76 -1
  48. package/collections/report-builder-library.collection.js.map +1 -1
  49. package/collections/report-builder-report.collection.js +138 -1
  50. package/collections/report-builder-report.collection.js.map +1 -1
  51. package/collections/user-group.collection.js +79 -1
  52. package/collections/user-group.collection.js.map +1 -1
  53. package/collections/user-guide.collection.js +46 -1
  54. package/collections/user-guide.collection.js.map +1 -1
  55. package/collections/user.collection.js +248 -1
  56. package/collections/user.collection.js.map +1 -1
  57. package/cron/cron.js +161 -1
  58. package/cron/cron.js.map +1 -1
  59. package/fixtures/cron-jobs.js +72 -1
  60. package/fixtures/cron-jobs.js.map +1 -1
  61. package/fixtures/init.js +62 -1
  62. package/fixtures/init.js.map +1 -1
  63. package/http/auth.js +697 -1
  64. package/http/auth.js.map +1 -1
  65. package/http/health.js +10 -1
  66. package/http/health.js.map +1 -1
  67. package/http/home.js +64 -1
  68. package/http/home.js.map +1 -1
  69. package/index.js +123 -1
  70. package/index.js.map +1 -1
  71. package/managers/cron.manager.js +205 -1
  72. package/managers/cron.manager.js.map +1 -1
  73. package/managers/method.manager.js +599 -1
  74. package/managers/method.manager.js.map +1 -1
  75. package/managers/mongo.manager.js +1682 -1
  76. package/managers/mongo.manager.js.map +1 -1
  77. package/managers/monitor.manager.js +334 -1
  78. package/managers/monitor.manager.js.map +1 -1
  79. package/managers/subscription.manager.js +867 -1
  80. package/managers/subscription.manager.js.map +1 -1
  81. package/managers/subscription.performance.js +100 -1
  82. package/managers/subscription.performance.js.map +1 -1
  83. package/methods/accounts.js +224 -1
  84. package/methods/accounts.js.map +1 -1
  85. package/methods/aws.js +449 -1
  86. package/methods/aws.js.map +1 -1
  87. package/methods/cloudconvert.js +214 -1
  88. package/methods/cloudconvert.js.map +1 -1
  89. package/methods/collections.js +526 -1
  90. package/methods/collections.js.map +1 -1
  91. package/methods/counters.js +121 -1
  92. package/methods/counters.js.map +1 -1
  93. package/methods/cron-jobs.js +1284 -1
  94. package/methods/cron-jobs.js.map +1 -1
  95. package/methods/flags.js +8 -1
  96. package/methods/flags.js.map +1 -1
  97. package/methods/logs.js +370 -1
  98. package/methods/logs.js.map +1 -1
  99. package/methods/monitor.js +384 -1
  100. package/methods/monitor.js.map +1 -1
  101. package/methods/pdf.js +685 -1
  102. package/methods/pdf.js.map +1 -1
  103. package/methods/report-builder.js +826 -1
  104. package/methods/report-builder.js.map +1 -1
  105. package/methods/support.js +263 -1
  106. package/methods/support.js.map +1 -1
  107. package/models/app-status.model.js +3 -1
  108. package/models/app-status.model.js.map +1 -1
  109. package/models/app-version.model.js +3 -1
  110. package/models/app-version.model.js.map +1 -1
  111. package/models/billing-logged-in-users.model.js +3 -1
  112. package/models/billing-logged-in-users.model.js.map +1 -1
  113. package/models/collection-document.model.js +3 -1
  114. package/models/collection-document.model.js.map +1 -1
  115. package/models/counter.model.js +3 -1
  116. package/models/counter.model.js.map +1 -1
  117. package/models/cron-job-history.model.js +3 -1
  118. package/models/cron-job-history.model.js.map +1 -1
  119. package/models/cron-job.model.js +3 -1
  120. package/models/cron-job.model.js.map +1 -1
  121. package/models/dialog.model.js +3 -1
  122. package/models/dialog.model.js.map +1 -1
  123. package/models/email-history.model.js +3 -1
  124. package/models/email-history.model.js.map +1 -1
  125. package/models/email-verified.model.js +3 -1
  126. package/models/email-verified.model.js.map +1 -1
  127. package/models/file.model.js +3 -1
  128. package/models/file.model.js.map +1 -1
  129. package/models/flag.model.js +3 -1
  130. package/models/flag.model.js.map +1 -1
  131. package/models/log-method-latency.model.js +3 -1
  132. package/models/log-method-latency.model.js.map +1 -1
  133. package/models/log-subscription.model.js +3 -1
  134. package/models/log-subscription.model.js.map +1 -1
  135. package/models/log.model.js +3 -1
  136. package/models/log.model.js.map +1 -1
  137. package/models/logged-in-users.model.js +3 -1
  138. package/models/logged-in-users.model.js.map +1 -1
  139. package/models/method-call.model.js +3 -1
  140. package/models/method-call.model.js.map +1 -1
  141. package/models/method-response.model.js +3 -1
  142. package/models/method-response.model.js.map +1 -1
  143. package/models/method.model.js +3 -1
  144. package/models/method.model.js.map +1 -1
  145. package/models/monitor-cpu.model.js +3 -1
  146. package/models/monitor-cpu.model.js.map +1 -1
  147. package/models/monitor-https-inbound.model.js +3 -1
  148. package/models/monitor-https-inbound.model.js.map +1 -1
  149. package/models/monitor-https-outbound.model.js +3 -1
  150. package/models/monitor-https-outbound.model.js.map +1 -1
  151. package/models/monitor-memory.model.js +3 -1
  152. package/models/monitor-memory.model.js.map +1 -1
  153. package/models/monitor-mongo.model.js +3 -1
  154. package/models/monitor-mongo.model.js.map +1 -1
  155. package/models/notification.model.js +3 -1
  156. package/models/notification.model.js.map +1 -1
  157. package/models/pagination.model.js +23 -1
  158. package/models/pagination.model.js.map +1 -1
  159. package/models/permission.model.js +3 -1
  160. package/models/permission.model.js.map +1 -1
  161. package/models/report-builder-dashboard-builder.model.js +3 -1
  162. package/models/report-builder-dashboard-builder.model.js.map +1 -1
  163. package/models/report-builder-library.model.js +3 -1
  164. package/models/report-builder-library.model.js.map +1 -1
  165. package/models/report-builder-report.model.js +3 -1
  166. package/models/report-builder-report.model.js.map +1 -1
  167. package/models/report-builder.model.js +3 -1
  168. package/models/report-builder.model.js.map +1 -1
  169. package/models/select-data-label.model.js +3 -1
  170. package/models/select-data-label.model.js.map +1 -1
  171. package/models/server-response.model.js +3 -1
  172. package/models/server-response.model.js.map +1 -1
  173. package/models/subscription.model.js +3 -1
  174. package/models/subscription.model.js.map +1 -1
  175. package/models/support-ticket.model.js +3 -1
  176. package/models/support-ticket.model.js.map +1 -1
  177. package/models/user-group.model.js +3 -1
  178. package/models/user-group.model.js.map +1 -1
  179. package/models/user-guide.model.js +3 -1
  180. package/models/user-guide.model.js.map +1 -1
  181. package/models/user.model.js +3 -1
  182. package/models/user.model.js.map +1 -1
  183. package/package.json +1 -2
  184. package/public_api.js +78 -1
  185. package/public_api.js.map +1 -1
  186. package/publications/app-status.js +16 -1
  187. package/publications/app-status.js.map +1 -1
  188. package/publications/app-version.js +16 -1
  189. package/publications/app-version.js.map +1 -1
  190. package/publications/cron-jobs.js +32 -1
  191. package/publications/cron-jobs.js.map +1 -1
  192. package/publications/files.js +36 -1
  193. package/publications/files.js.map +1 -1
  194. package/publications/flags.js +22 -1
  195. package/publications/flags.js.map +1 -1
  196. package/publications/logs.js +90 -1
  197. package/publications/logs.js.map +1 -1
  198. package/publications/method-calls.js +16 -1
  199. package/publications/method-calls.js.map +1 -1
  200. package/publications/method-responses.js +16 -1
  201. package/publications/method-responses.js.map +1 -1
  202. package/publications/notifications.js +16 -1
  203. package/publications/notifications.js.map +1 -1
  204. package/publications/report-builder-dashboard-builders.js +42 -1
  205. package/publications/report-builder-dashboard-builders.js.map +1 -1
  206. package/publications/report-builder-libraries.js +89 -1
  207. package/publications/report-builder-libraries.js.map +1 -1
  208. package/publications/report-builder-reports.js +50 -1
  209. package/publications/report-builder-reports.js.map +1 -1
  210. package/publications/super-admin.js +16 -1
  211. package/publications/super-admin.js.map +1 -1
  212. package/publications/user-groups.js +16 -1
  213. package/publications/user-groups.js.map +1 -1
  214. package/publications/user-guides.js +16 -1
  215. package/publications/user-guides.js.map +1 -1
  216. package/server-app.js +682 -1
  217. package/server-app.js.map +1 -1
  218. package/util/common.js +498 -1
  219. package/util/common.js.map +1 -1
  220. package/util/schema-report-builder.js +452 -1
  221. package/util/schema-report-builder.js.map +1 -1
@@ -1,2 +1,1683 @@
1
- "use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(e,t){return(extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])})(e,t)};return function(e,t){function __(){this.constructor=e}extendStatics(e,t),e.prototype=null===t?Object.create(t):(__.prototype=t.prototype,new __)}}(),__awaiter=this&&this.__awaiter||function(e,t,n,o){return new(n||(n=Promise))((function(i,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?i(e.value):function adopt(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))},__generator=this&&this.__generator||function(e,t){var n,o,i,r,c={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return r={next:verb(0),throw:verb(1),return:verb(2)},"function"==typeof Symbol&&(r[Symbol.iterator]=function(){return this}),r;function verb(r){return function(l){return function step(r){if(n)throw new TypeError("Generator is already executing.");for(;c;)try{if(n=1,o&&(i=2&r[0]?o.return:r[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,r[1])).done)return i;switch(o=0,i&&(r=[2&r[0],i.value]),r[0]){case 0:case 1:i=r;break;case 4:return c.label++,{value:r[1],done:!1};case 5:c.label++,o=r[1],r=[0];continue;case 7:r=c.ops.pop(),c.trys.pop();continue;default:if(!(i=c.trys,(i=i.length>0&&i[i.length-1])||6!==r[0]&&2!==r[0])){c=0;continue}if(3===r[0]&&(!i||r[1]>i[0]&&r[1]<i[3])){c.label=r[1];break}if(6===r[0]&&c.label<i[1]){c.label=i[1],i=r;break}if(i&&c.label<i[2]){c.label=i[2],c.ops.push(r);break}i[2]&&c.ops.pop(),c.trys.pop();continue}r=t.call(e,c)}catch(e){r=[6,e],o=0}finally{n=i=0}if(5&r[0])throw r[1];return{value:r[0]?r[1]:void 0,done:!0}}([r,l])}}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.objectIdHexString=exports.UserCollection=exports.Collection=exports.Model=exports.MongoManager=void 0;var simpl_schema_1=require("simpl-schema"),mongodb_1=require("mongodb"),index_1=require("../index"),user_collection_1=require("../collections/user.collection"),common_1=require("../util/common"),log_collection_1=require("../collections/log.collection"),NodeCache=require("node-cache"),crypto=require("crypto"),scmp=require("scmp"),MongoManager=function(){function MongoManager(){this._collections=[],this._mongoQueue=[],this._mongoQueueId=0,this._mongoQueueCacheId=1,this._nodeCache=new NodeCache({stdTTL:0,checkperiod:0}),this.runQueue()}return MongoManager.prototype.registerCollection=function(e){this._collections.push(e)},MongoManager.prototype.collections=function(){return this._collections},MongoManager.prototype.collection=function(e){return this._collections.filter((function(t){return t.collectionName===e}))[0]},MongoManager.prototype.addToQueue=function(e){var t=this._mongoQueue.filter((function(t){return t.name_collection===e.name_collection&&t.name_function===e.name_function&&t.name_function_addt===e.name_function_addt&&JSON.stringify(t.data_function)===JSON.stringify(e.data_function)&&JSON.stringify(t.data_function_addt)===JSON.stringify(e.data_function_addt)}))[0];t?t.running?t.cbs_next.push(e.cbs[0]):t.cbs.push(e.cbs[0]):(e._id=this._mongoQueueId,this._mongoQueueId+=1,this._mongoQueue.push(e))},MongoManager.prototype.runQueue=function(){return __awaiter(this,void 0,void 0,(function(){var e=this;return __generator(this,(function(t){return setInterval((function(){var t=e._mongoQueue.filter((function(e){return!e.running&&e.cbs.length}));if(t.length)for(var _loop_1=function(n){var o,i,r,c=t[n];if(c.running=!0,c.cacheId){var l=JSON.parse(e._nodeCache.get(c.cacheId),common_1.dateReviver);c.cbs.forEach((function(e){e(null,l,!0)})),c.cbs=[],c.running=!1}else c.name_function_addt?(i=(r=index_1.ResolveIOServer.getMainDB().collection(c.name_collection))[c.name_function].apply(r,c.data_function))[c.name_function_addt].apply(i,c.data_function_addt).then((function(t){c.cacheId=e._mongoQueueCacheId,e._mongoQueueCacheId+=1,e.addToCache(c.cacheId,t),c.cbs.forEach((function(e){e(null,t,!1)})),c.cbs_next.length?(c.cbs=c.cbs_next,c.cbs_next=[]):c.cbs=[],c.running=!1}),(function(n){c.cbs.forEach((function(e){e(n,null,!1)})),c.cbs_next.forEach((function(e){e(n,null,!1)})),t.splice(e._mongoQueue.map((function(e){return e._id})).indexOf(c._id),1),e._mongoQueue.splice(e._mongoQueue.map((function(e){return e._id})).indexOf(c._id),1)})):(o=index_1.ResolveIOServer.getMainDB().collection(c.name_collection))[c.name_function].apply(o,c.data_function).then((function(t){c.cacheId=e._mongoQueueCacheId,e._mongoQueueCacheId+=1,e.addToCache(c.cacheId,t),c.cbs.forEach((function(e){e(null,t,!1)})),c.cbs_next.length?(c.cbs=c.cbs_next,c.cbs_next=[]):c.cbs=[],c.running=!1}),(function(n){c.cbs.forEach((function(e){e(n,null,!1)})),c.cbs_next.forEach((function(e){e(n,null,!1)})),t.splice(e._mongoQueue.map((function(e){return e._id})).indexOf(c._id),1),e._mongoQueue.splice(e._mongoQueue.map((function(e){return e._id})).indexOf(c._id),1)}))},n=0;n<t.length;n++)_loop_1(n)}),10),[2]}))}))},MongoManager.prototype.addToCache=function(e,t){var n=this._nodeCache.getStats().vsize;if(n>1e8){for(var o=0,i=this._mongoQueue.filter((function(e){return e.cacheId})),r=0;r<i.length&&(this._nodeCache.del(i[r].cacheId),i[r].cacheId=0,o+=1,!((n=this._nodeCache.getStats().vsize)<1e8));r++);console.log("Query Cache: Too Big, - Deleted: "+o+" - "+n)}this._nodeCache.set(e,JSON.stringify(t))},MongoManager.prototype.invalidateQueryCache=function(e){var t=this;this._mongoQueue.filter((function(t){return(t.name_collection===e||t.lookup_collections.includes(e))&&t.cacheId})).forEach((function(e){t._nodeCache.del(e.cacheId),e.cacheId=0}))},MongoManager}();exports.MongoManager=MongoManager;var Model=function Model(e,t,n,o,i,r,c,l){if(void 0===n&&(n=!1),void 0===o&&(o=!0),void 0===i&&(i=[]),void 0===r&&(r=!0),void 0===c&&(c=!0),void 0===l&&(l=!0),this.collection_main=null,this.collection_version=null,this.collection_main="users"===e?new UserCollection(e,t,o,i,r,c,l):new Collection(e,t,o,i,r,c,l),n){this.collection_main.useVersions=!0;var s=common_1.deepCopy(t);s._id.type="Object",s._id.blackbox=!0,this.collection_version="users"===e?new UserCollection(e+".versions",s,!1,[],!0,!1,!1):new Collection(e+".versions",s,!1,[],!0,!1,!1),this.collection_version.indexExists("_id.__v_1__id._id_1")&&this.collection_version.dropIndex("_id.__v_1__id._id_1"),this.collection_version.indexExists("_id._id_1__id.__v_1")||this.collection_version.createIndex({"_id._id":1,"_id.__v":1}),this.collection_main.versionCollection=e+".versions"}};exports.Model=Model;var Collection=function(){function Collection(e,t,n,o,i,r,c){var l=this;if(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,this.simplschema=new simpl_schema_1.default(t),this.timestamps=i,this.createLogs=r,this.checkSchema=c,n){this.useRB=!0;var s=common_1.deepCopy(t),a=common_1.buildRbLookups(o,s,[]);this.rbSchema=common_1.buildRbSchema(a)}var u=setInterval((function(){index_1.ResolveIOServer&&index_1.ResolveIOServer.getMainServer()&&index_1.ResolveIOServer.getMongoManager()&&(index_1.ResolveIOServer.getMongoManager().registerCollection(l),clearInterval(u))}),1)}return Collection.prototype.aggregate=function(e,t,n){var o=this;return void 0===n&&(n=!1),new Promise((function(i,r){o.createLogs&&n?index_1.ResolveIOServer.getMongoManager().addToQueue({_id:0,name_collection:o.collectionName,name_function:"aggregate",name_function_addt:"toArray",data_function:[e,t],data_function_addt:[],cbs:[function(e,t,n){o.createLogs,e?r(e):i(t)}],cbs_next:[],running:!1,cacheId:0,lookup_collections:e.filter((function(e){return e.$lookup&&e.$lookup.from})).map((function(e){return e.$lookup.from})).filter((function(e,t,n){return t===n.indexOf(e)}))}):index_1.ResolveIOServer.getMainDB().collection(o.collectionName).aggregate(e,t).toArray().then((function(e){return i(e)}),(function(e){return r(e)}))}))},Collection.prototype.aggregateCount=function(e,t){var n=this;return new Promise((function(o,i){index_1.ResolveIOServer.getMongoManager().addToQueue({_id:0,name_collection:n.collectionName,name_function:"aggregate",name_function_addt:"count",data_function:[e,t],data_function_addt:[],cbs:[function(e,t,n){e?i(e):o(t)}],cbs_next:[],running:!1,cacheId:0,lookup_collections:e.filter((function(e){return e.$lookup&&e.$lookup.from})).map((function(e){return e.$lookup.from})).filter((function(e,t,n){return t===n.indexOf(e)}))})}))},Collection.prototype.aggregateCursor=function(e,t){return index_1.ResolveIOServer.getMainDB().collection(this.collectionName).aggregate(e,t)},Collection.prototype.aggregateStream=function(e,t){return index_1.ResolveIOServer.getMainDB().collection(this.collectionName).aggregate(e,t).stream()},Collection.prototype.countDocuments=function(e,t){return void 0===e&&(e={}),index_1.ResolveIOServer.getMainDB().collection(this.collectionName).countDocuments(e,t)},Collection.prototype.create=function(e,t){return Array.isArray(e)?this.insertMany(e,t):this.insertOne(e,t)},Collection.prototype.createIndex=function(e,t){return index_1.ResolveIOServer.getMainDB().collection(this.collectionName).createIndex(e,t)},Collection.prototype.createIndexes=function(e,t){return index_1.ResolveIOServer.getMainDB().collection(this.collectionName).createIndexes(e,t)},Collection.prototype.deleteMany=function(e,t,n){var o=this;return void 0===e&&(e={}),void 0===n&&(n=!1),new Promise((function(i,r){return __awaiter(o,void 0,void 0,(function(){var o,c,l,s;return __generator(this,(function(a){switch(a.label){case 0:return!this.createLogs||n?[3,5]:[4,this.find(e)];case 1:o=a.sent(),c=0,a.label=2;case 2:return c<o.length?(l=o[c],log_collection_1.Logs.insertOne({_id:objectIdHexString(),type:"document",collection:this.collectionName,id_document:l._id,payload:common_1.getBinarySize(JSON.stringify([l,e,t]))<2e5?JSON.stringify([l,e,t],null,2):"Too Big",method:"deleteMany",id_user:"",user:"",messageId:0,route:""}),this.useVersions?((s=common_1.deepCopy(l))._id={_id:l._id,__v:l.__v},[4,index_1.ResolveIOServer.getMongoManager().collection(this.versionCollection).replaceOne({_id:{_id:l._id,__v:l.__v}},s,{upsert:!0})]):[3,4]):[3,5];case 3:a.sent(),a.label=4;case 4:return c++,[3,2];case 5:return index_1.ResolveIOServer.getMainDB().collection(this.collectionName).deleteMany(e,t).then((function(e){e.result.ok?i(e.deletedCount):r(e.result.ok)}),(function(e){return r(e)})),[2]}}))}))}))},Collection.prototype.deleteOne=function(e,t,n){var o=this;return void 0===e&&(e={}),void 0===n&&(n=!1),new Promise((function(i,r){return __awaiter(o,void 0,void 0,(function(){var o,c;return __generator(this,(function(l){switch(l.label){case 0:return!this.createLogs||n?[3,3]:[4,this.findOne(e,null,!0)];case 1:return(o=l.sent())?(log_collection_1.Logs.insertOne({_id:objectIdHexString(),type:"document",collection:this.collectionName,id_document:o._id,payload:common_1.getBinarySize(JSON.stringify([o,e,t]))<2e5?JSON.stringify([o,e,t],null,2):"Too Big",method:"deleteOne",id_user:"",user:"",messageId:0,route:""}),this.useVersions?((c=common_1.deepCopy(o))._id={_id:o._id,__v:o.__v},[4,index_1.ResolveIOServer.getMongoManager().collection(this.versionCollection).replaceOne({_id:{_id:o._id,__v:o.__v}},c,{upsert:!0})]):[3,3]):[3,3];case 2:l.sent(),l.label=3;case 3:return index_1.ResolveIOServer.getMainDB().collection(this.collectionName).deleteOne(e,t).then((function(e){e.result.ok?i(e.deletedCount):r(e.result.ok)}),(function(e){return r(e)})),[2]}}))}))}))},Collection.prototype.distinct=function(e,t,n){return index_1.ResolveIOServer.getMainDB().collection(this.collectionName).distinct(e,t,n)},Collection.prototype.drop=function(e){return index_1.ResolveIOServer.getMainDB().collection(this.collectionName).drop(e)},Collection.prototype.dropIndex=function(e,t){return index_1.ResolveIOServer.getMainDB().collection(this.collectionName).dropIndex(e,t)},Collection.prototype.dropIndexes=function(e){return index_1.ResolveIOServer.getMainDB().collection(this.collectionName).dropIndexes(e)},Collection.prototype.find=function(e,t,n){var o=this;return void 0===e&&(e={}),void 0===n&&(n=!1),new Promise((function(i,r){return __awaiter(o,void 0,void 0,(function(){var o=this;return __generator(this,(function(c){return this.createLogs&&!n?index_1.ResolveIOServer.getMongoManager().addToQueue({_id:0,name_collection:this.collectionName,name_function:"find",name_function_addt:"toArray",data_function:[e,t],data_function_addt:[],cbs:[function(e,t,n){o.createLogs,e?r(e):i(t)}],cbs_next:[],running:!1,cacheId:0,lookup_collections:[]}):index_1.ResolveIOServer.getMainDB().collection(this.collectionName).find(e,t).toArray().then((function(e){return i(e)}),(function(e){return r(e)})),[2]}))}))}))},Collection.prototype.findById=function(e,t){return index_1.ResolveIOServer.getMainDB().collection(this.collectionName).findOne({_id:e},t)},Collection.prototype.findCount=function(e,t,n){return void 0===e&&(e={}),void 0===n&&(n=!1),this.createLogs,index_1.ResolveIOServer.getMainDB().collection(this.collectionName).find(e,t).count()},Collection.prototype.findCursor=function(e,t){return void 0===e&&(e={}),index_1.ResolveIOServer.getMainDB().collection(this.collectionName).find(e,t)},Collection.prototype.findStream=function(e,t,n){return void 0===e&&(e={}),index_1.ResolveIOServer.getMainDB().collection(this.collectionName).find(e,t).stream(n)},Collection.prototype.findOne=function(e,t,n){var o=this;return void 0===e&&(e={}),void 0===n&&(n=!1),new Promise((function(i,r){o.createLogs&&!n?index_1.ResolveIOServer.getMongoManager().addToQueue({_id:0,name_collection:o.collectionName,name_function:"findOne",name_function_addt:"",data_function:[e,t],data_function_addt:[],cbs:[function(e,t,n){e?r(e):i(t),o.createLogs}],cbs_next:[],running:!1,cacheId:0,lookup_collections:[]}):index_1.ResolveIOServer.getMainDB().collection(o.collectionName).findOne(e,t).then((function(e){return i(e)}),(function(e){return r(e)}))}))},Collection.prototype.findOneAndDelete=function(e,t,n){var o=this;return void 0===e&&(e={}),void 0===n&&(n=!1),new Promise((function(i,r){return __awaiter(o,void 0,void 0,(function(){var o,c=this;return __generator(this,(function(l){switch(l.label){case 0:return!this.createLogs||n?[3,2]:[4,this.findOne(e,null,!0)];case 1:(o=l.sent())&&log_collection_1.Logs.insertOne({_id:objectIdHexString(),type:"document",collection:this.collectionName,id_document:o._id,payload:common_1.getBinarySize(JSON.stringify([o,e,t]))<2e5?JSON.stringify([o,e,t],null,2):"Too Big",method:"findOneAndDelete",id_user:"",user:"",messageId:0,route:""}),l.label=2;case 2:return index_1.ResolveIOServer.getMainDB().collection(this.collectionName).findOneAndDelete(e,t).then((function(e){e.ok?i(e.value):r(e.lastErrorObject),c.createLogs}),(function(e){r(e),c.createLogs})),[2]}}))}))}))},Collection.prototype.findOneAndReplace=function(e,t,n,o,i){var r=this;return void 0===e&&(e={}),void 0===o&&(o=!1),void 0===i&&(i=!1),new Promise((function(c,l){return __awaiter(r,void 0,void 0,(function(){var r,s,a,u=this;return __generator(this,(function(d){switch(d.label){case 0:return!this.checkSchema||i||(r=this.simplschema.newContext(),r.validate(t))?(s=new Date,this.timestamps&&(t.updatedAt=s),!this.createLogs||o?[3,2]:[4,this.findOne(e,null,!0)]):(console.log(new Date,this.collectionName,"Schema Errors - findOneAndReplace",r.validationErrors()),index_1.ResolveIOServer.getMainServer().getMethodManager().callMethodInternal("insertErrorLog","Schema Failed on findOneAndReplace - "+this.collectionName,[r.validationErrors(),t]),l(r.validationErrors()),[2]);case 1:(a=d.sent())&&log_collection_1.Logs.insertOne({_id:objectIdHexString(),type:"document",collection:this.collectionName,id_document:a._id,payload:common_1.getBinarySize(JSON.stringify([a,e,t,n]))<2e5?JSON.stringify([a,e,t,n],null,2):"Too Big",method:"findOneAndReplace",id_user:"",user:"",messageId:0,route:""}),d.label=2;case 2:return index_1.ResolveIOServer.getMainDB().collection(this.collectionName).findOneAndReplace(e,t,n).then((function(e){e.ok?c(e.value):l(e.lastErrorObject),u.createLogs}),(function(e){l(e),u.createLogs})),[2]}}))}))}))},Collection.prototype.findOneAndUpdate=function(e,t,n,o,i){var r=this;return void 0===e&&(e={}),void 0===o&&(o=!1),void 0===i&&(i=!1),new Promise((function(c,l){return __awaiter(r,void 0,void 0,(function(){var r,s,a,u=this;return __generator(this,(function(d){switch(d.label){case 0:return!this.checkSchema||i||(r=this.simplschema.newContext(),r.validate(t,{modifier:!0}))?(this.timestamps&&(s=new Date,t.$set?t.$set.updatedAt=s:t.$set={updatedAt:s}),!this.createLogs||o?[3,2]:[4,this.findOne(e,null,!0)]):(console.log(new Date,this.collectionName,"Schema Errors - findOneAndUpdate",r.validationErrors()),index_1.ResolveIOServer.getMainServer().getMethodManager().callMethodInternal("insertErrorLog","Schema Failed on findOneAndUpdate - "+this.collectionName,[r.validationErrors(),t]),l(r.validationErrors()),[2]);case 1:(a=d.sent())&&log_collection_1.Logs.insertOne({_id:objectIdHexString(),type:"document",collection:this.collectionName,id_document:a._id,payload:common_1.getBinarySize(JSON.stringify([a,e,t,n]))<2e5?JSON.stringify([a,e,t,n],null,2):"Too Big",method:"findOneAndUpdate",id_user:"",user:"",messageId:0,route:""}),d.label=2;case 2:return index_1.ResolveIOServer.getMainDB().collection(this.collectionName).findOneAndUpdate(e,t,n).then((function(e){e.ok?c(e.value):l(e.lastErrorObject),u.createLogs}),(function(e){l(e),u.createLogs})),[2]}}))}))}))},Collection.prototype.indexes=function(e){return index_1.ResolveIOServer.getMainDB().collection(this.collectionName).indexes(e)},Collection.prototype.indexExists=function(e,t){return index_1.ResolveIOServer.getMainDB().collection(this.collectionName).indexExists(e,t)},Collection.prototype.insertMany=function(e,t,n,o){var i=this;return void 0===n&&(n=!1),void 0===o&&(o=!1),new Promise((function(r,c){return __awaiter(i,void 0,void 0,(function(){var i,l,s,a,u,d=this;return __generator(this,(function(_){if(!e.length)return r([]),[2];for(i=[],this.checkSchema&&!o&&e.forEach((function(e){var t=d.simplschema.newContext();t.validate(e)?i.push(!0):(console.log(new Date,d.collectionName,"Schema Errors - insertMany",t.validationErrors()),index_1.ResolveIOServer.getMainServer().getMethodManager().callMethodInternal("insertErrorLog","Schema Failed on insertMany - "+d.collectionName,[t.validationErrors(),e]),i.push(!1))})),l=this.checkSchema?e.filter((function(e,t){return i[t]})):e,s=0;s<l.length;s++)(a=l[s])._id||(a._id=objectIdHexString()),this.timestamps&&(u=new Date,a.createdAt=u,a.updatedAt=u),this.createLogs&&!n&&log_collection_1.Logs.insertOne({_id:objectIdHexString(),type:"document",collection:this.collectionName,id_document:a._id,payload:common_1.getBinarySize(JSON.stringify([a,t]))<2e5?JSON.stringify([a,t],null,2):"Too Big",method:"insertMany",id_user:"",user:"",messageId:0,route:""});return l.length&&index_1.ResolveIOServer.getMainDB().collection(this.collectionName).insertMany(l,t).then((function(e){e.result.ok?r(l):c(e.result.ok)}),(function(e){c(e)})),[2]}))}))}))},Collection.prototype.insertOne=function(e,t,n,o){var i=this;return void 0===n&&(n=!1),void 0===o&&(o=!1),new Promise((function(r,c){return __awaiter(i,void 0,void 0,(function(){var i,l;return __generator(this,(function(s){return e._id||(e._id=objectIdHexString()),!this.checkSchema||o||(i=this.simplschema.newContext(),i.validate(e))?(this.timestamps&&(l=new Date,e.createdAt=l,e.updatedAt=l),this.createLogs&&!n&&log_collection_1.Logs.insertOne({_id:objectIdHexString(),type:"document",collection:this.collectionName,id_document:e._id,payload:common_1.getBinarySize(JSON.stringify([e,t]))<2e5?JSON.stringify([e,t],null,2):"Too Big",method:"insertOne",id_user:"",user:"",messageId:0,route:""}),this.useVersions&&!e.hasOwnProperty("__v")&&(e.__v=0),index_1.ResolveIOServer.getMainDB().collection(this.collectionName).insertOne(e,t).then((function(t){t.result.ok?r(e):c(t.result.ok)}),(function(e){c(e)})),[2]):(console.log(new Date,this.collectionName,"Schema Errors - insertOne",i.validationErrors()),index_1.ResolveIOServer.getMainServer().getMethodManager().callMethodInternal("insertErrorLog","Schema Failed on insertOne - "+this.collectionName,[i.validationErrors(),e]),c(i.validationErrors()),[2])}))}))}))},Collection.prototype.listIndexes=function(e){return index_1.ResolveIOServer.getMainDB().collection(this.collectionName).listIndexes(e)},Collection.prototype.reIndex=function(e){return index_1.ResolveIOServer.getMainDB().collection(this.collectionName).reIndex(e)},Collection.prototype.rename=function(e,t){return index_1.ResolveIOServer.getMainDB().collection(this.collectionName).rename(e,t)},Collection.prototype.replaceOne=function(e,t,n,o,i,r){var c=this;return void 0===o&&(o=!1),void 0===i&&(i=!1),void 0===r&&(r=null),new Promise((function(l,s){return __awaiter(c,void 0,void 0,(function(){var c,a,u,d,_,h,f;return __generator(this,(function(g){switch(g.label){case 0:return!this.checkSchema||i||(c=this.simplschema.newContext(),c.validate(t))?(a=new Date,this.timestamps&&(t.updatedAt=a),r?[3,2]:[4,this.findOne(e,null,!0)]):(console.log(new Date,this.collectionName,"Schema Errors - replaceOne",c.validationErrors()),index_1.ResolveIOServer.getMainServer().getMethodManager().callMethodInternal("insertErrorLog","Schema Failed on replaceOne - "+this.collectionName,[c.validationErrors(),t]),s(c.validationErrors()),[2]);case 1:r=g.sent(),g.label=2;case 2:return r?(this.timestamps&&!t.createdAt&&r.createdAt&&(t.createdAt=r.createdAt),this.createLogs&&!o&&log_collection_1.Logs.insertOne({_id:objectIdHexString(),type:"document",collection:this.collectionName,id_document:r._id,payload:common_1.getBinarySize(JSON.stringify([r,e,t,n]))<2e5?JSON.stringify([r,e,t,n],null,2):"Too Big",method:"replaceOne",id_user:"",user:"",messageId:0,route:""}),this.useVersions?r.__v!==t.__v?[3,6]:(t.__v+=1,(u=common_1.deepCopy(r))._id={_id:r._id,__v:r.__v},[4,index_1.ResolveIOServer.getMongoManager().collection(this.versionCollection).replaceOne({_id:{_id:r._id,__v:r.__v}},u,{upsert:!0})]):[3,9]):[3,11];case 3:return g.sent(),r.__v>=4?[4,index_1.ResolveIOServer.getMongoManager().collection(this.versionCollection).deleteMany({_id:{_id:r._id,__v:{$lte:r.__v-4}}})]:[3,5];case 4:g.sent(),g.label=5;case 5:return index_1.ResolveIOServer.getMainDB().collection(this.collectionName).replaceOne(e,t,n).then((function(e){e.result.ok?l(e.result.nModified):s(e.result.ok)}),(function(e){s(e)})),[3,8];case 6:return console.log("invalid version - "+this.collectionName,r.__v,t.__v),[4,index_1.ResolveIOServer.getMongoManager().collection(this.versionCollection).findOne({_id:{_id:r._id,__v:t.__v}},null,!0)];case 7:(d=g.sent())?(_=r._id,h=r.__v,(f=common_1.getMongoMergeUpdatedDoc(t,r,d))._id=_,f.__v=h+1,index_1.ResolveIOServer.getMainDB().collection(this.collectionName).replaceOne(e,f,n).then((function(e){e.result.ok?l(e.result.nModified):s(e.result.ok)}),(function(e){s(e)}))):s("Invalid Version And Could Not Find History - DB: "+r.__v+", Trying to update with :"+t.__v),g.label=8;case 8:return[3,10];case 9:index_1.ResolveIOServer.getMainDB().collection(this.collectionName).replaceOne(e,t,n).then((function(e){e.result.ok?l(e.result.nModified):s(e.result.ok)}),(function(e){s(e)})),g.label=10;case 10:return[3,12];case 11:n&&n.upsert?(this.timestamps&&(t.createdAt=a),this.createLogs&&!o&&log_collection_1.Logs.insertOne({_id:objectIdHexString(),type:"document",collection:this.collectionName,id_document:t._id,payload:common_1.getBinarySize(JSON.stringify([e,t,n]))<2e5?JSON.stringify([e,t,n],null,2):"Too Big",method:"replaceOne",id_user:"",user:"",messageId:0,route:""}),this.useVersions&&(t.__v=0),index_1.ResolveIOServer.getMainDB().collection(this.collectionName).replaceOne(e,t,n).then((function(e){e.result.ok?l(e.result.nModified):s(e.result.ok)}),(function(e){s(e)}))):s("No Document"),g.label=12;case 12:return[2]}}))}))}))},Collection.prototype.stats=function(e){return index_1.ResolveIOServer.getMainDB().collection(this.collectionName).stats(e)},Collection.prototype.updateMany=function(e,t,n,o,i){var r=this;return void 0===o&&(o=!1),void 0===i&&(i=!1),new Promise((function(c,l){return __awaiter(r,void 0,void 0,(function(){var r,s,a,u,d;return __generator(this,(function(_){switch(_.label){case 0:return this.timestamps&&(r=new Date,t.$set?t.$set.updatedAt=r:t.$set={updatedAt:r}),!this.checkSchema||i||(s=this.simplschema.newContext(),s.validate(t,{modifier:!0}))?!this.createLogs||o?[3,2]:[4,this.find(e)]:(console.log(new Date,this.collectionName,"Schema Errors - updateMany",s.validationErrors()),index_1.ResolveIOServer.getMainServer().getMethodManager().callMethodInternal("insertErrorLog","Schema Failed on updateMany - "+this.collectionName,[s.validationErrors(),t]),l(s.validationErrors()),[2]);case 1:for(a=_.sent(),u=0;u<a.length;u++)d=a[u],log_collection_1.Logs.insertOne({_id:objectIdHexString(),type:"document",collection:this.collectionName,id_document:d._id,payload:common_1.getBinarySize(JSON.stringify([d,e,t,n]))<2e5?JSON.stringify([d,e,t,n],null,2):"Too Big",method:"updateMany",id_user:"",user:"",messageId:0,route:""});_.label=2;case 2:return index_1.ResolveIOServer.getMainDB().collection(this.collectionName).updateMany(e,t,n).then((function(e){e.result.ok?c(e.result.nModified):l(e.result.ok)}),(function(e){return l(e)})),[2]}}))}))}))},Collection.prototype.updateOne=function(e,t,n,o,i){var r=this;return void 0===o&&(o=!1),void 0===i&&(i=!1),new Promise((function(c,l){return __awaiter(r,void 0,void 0,(function(){var r,s,a,u;return __generator(this,(function(d){switch(d.label){case 0:return r=new Date,this.timestamps&&(t.$set?t.$set.updatedAt=r:t.$set={updatedAt:r}),!this.checkSchema||i||(s=this.simplschema.newContext(),s.validate(t,{modifier:!0}))?[4,this.findOne(e,null,!0)]:(console.log(new Date,this.collectionName,"Schema Errors - updateOne",s.validationErrors()),index_1.ResolveIOServer.getMainServer().getMethodManager().callMethodInternal("insertErrorLog","Schema Failed on updateOne - "+this.collectionName,[s.validationErrors(),t]),l(s.validationErrors()),[2]);case 1:return(a=d.sent())?(this.createLogs&&!o&&log_collection_1.Logs.insertOne({_id:objectIdHexString(),type:"document",collection:this.collectionName,id_document:a._id,payload:common_1.getBinarySize(JSON.stringify([a,e,t,n]))<2e5?JSON.stringify([a,e,t,n],null,2):"Too Big",method:"updateOne",id_user:"",user:"",messageId:0,route:""}),this.useVersions?((u=common_1.deepCopy(a))._id={_id:a._id,__v:a.__v},[4,index_1.ResolveIOServer.getMongoManager().collection(this.versionCollection).replaceOne({_id:{_id:a._id,__v:a.__v}},u,{upsert:!0})]):[3,5]):[3,7];case 2:return d.sent(),a.__v>=4?[4,index_1.ResolveIOServer.getMongoManager().collection(this.versionCollection).deleteMany({_id:{_id:a._id,__v:{$lte:a.__v-4}}})]:[3,4];case 3:d.sent(),d.label=4;case 4:return objectContainsPropertyDeep(t,"__v")||(t.$inc?t.$inc.__v||(t.$inc.__v=1):t.$inc={__v:1}),index_1.ResolveIOServer.getMainDB().collection(this.collectionName).updateOne(e,t,n).then((function(e){e.result.ok?c(e.result.nModified):l(e.result.ok)}),(function(e){return l(e)})),[3,6];case 5:index_1.ResolveIOServer.getMainDB().collection(this.collectionName).updateOne(e,t,n).then((function(e){e.result.ok?c(e.result.nModified):l(e.result.ok)}),(function(e){return l(e)})),d.label=6;case 6:return[3,8];case 7:n&&n.upsert&&t.$setOnInsert&&t.$setOnInsert._id?(this.timestamps&&(t.$setOnInsert.createdAt||(t.$setOnInsert.createdAt=r)),this.createLogs&&!o&&log_collection_1.Logs.insertOne({_id:objectIdHexString(),type:"document",collection:this.collectionName,id_document:t.$setOnInsert._id,payload:common_1.getBinarySize(JSON.stringify([e,t,n]))<2e5?JSON.stringify([e,t,n],null,2):"Too Big",method:"updateOne",id_user:"",user:"",messageId:0,route:""}),this.useVersions&&(objectContainsPropertyDeep(t,"__v")||(t.$setOnInsert.__v=0)),index_1.ResolveIOServer.getMainDB().collection(this.collectionName).updateOne(e,t,n).then((function(e){e.result.ok?c(e.result.nModified):l(e.result.ok)}),(function(e){return l(e)}))):l("No Document"),d.label=8;case 8:return[2]}}))}))}))},Collection.prototype.watchCollection=function(e,t){return void 0===e&&(e=[]),index_1.ResolveIOServer.getMainDB().collection(this.collectionName).watch(e,t)},Collection.prototype.watchCollectionWithAggregate=function(e,t){return void 0===e&&(e=[]),index_1.ResolveIOServer.getMainDB().collection(this.collectionName).watch(e,t)},Collection}();exports.Collection=Collection;var UserCollection=function(e){function UserCollection(){return null!==e&&e.apply(this,arguments)||this}return __extends(UserCollection,e),UserCollection.prototype.authenticateStrategy=function(){var e=this;return function(t,n,o){return __awaiter(e,void 0,void 0,(function(){var e;return __generator(this,(function(i){switch(i.label){case 0:return[4,user_collection_1.Users.findOne({username:t})];case 1:return e=i.sent(),this.authenticate(e,n).then((function(t){t.data?o(null,e,null):o(null,null,t.error)}),(function(e){o(e,null,null)})),[2]}}))}))}},UserCollection.prototype.authenticate=function(e,t){var n=this;return new Promise((function(o,i){return __awaiter(n,void 0,void 0,(function(){var n,r,c=this;return __generator(this,(function(l){switch(l.label){case 0:return n=Math.pow(100,Math.log(e.attempts+1)),r=n<3e5?n:3e5,e.last?Date.now()-e.last.getTime()<r?(e.last=new Date,[4,user_collection_1.Users.updateOne({_id:e._id},{$set:{last:e.last}})]):[3,2]:[3,3];case 1:return l.sent(),o({data:null,error:"Attempt Too Soon"}),[2];case 2:return[3,4];case 3:e.last=new Date,l.label=4;case 4:return e.attempts>=5?(o({data:null,error:"Too Many Attempts"}),[2]):e.salt?(pbkdf2(t,e.salt,{iterations:25e3,keylen:512,digestAlgorithm:"sha256"},(function(t,n){return __awaiter(c,void 0,void 0,(function(){return __generator(this,(function(r){switch(r.label){case 0:return t?[2,i(t)]:scmp(n,Buffer.from(e.hash,"hex"))?(e.last=new Date,e.attempts=0,[4,user_collection_1.Users.updateOne({_id:e._id},{$set:{last:e.last,attempts:e.attempts}})]):[3,2];case 1:return r.sent(),o({data:e,error:""}),[3,4];case 2:return e.last=new Date,e.attempts=e.attempts+1,[4,user_collection_1.Users.updateOne({_id:e._id},{$set:{last:e.last,attempts:e.attempts}})];case 3:r.sent(),e.attempts>=5?o({data:null,error:"Too Many Attempts"}):o({data:null,error:"Invalid Username And Password"}),r.label=4;case 4:return[2]}}))}))})),[2]):(o({data:null,error:"No Salt Value Stored"}),[2])}}))}))}))},UserCollection.prototype.serializeUser=function(){return function(e,t){t(null,e.username)}},UserCollection.prototype.deserializeUser=function(){return function(e,t){user_collection_1.Users.findOne({username:e}).then((function(e){t(null,e)}),(function(e){t(e,null)}))}},UserCollection.prototype.setPassword=function(e,t){var n=this;return new Promise((function(o,i){return __awaiter(n,void 0,void 0,(function(){var n,r,c,l;return __generator(this,(function(s){switch(s.label){case 0:return e?[3,1]:(i("No User"),[3,5]);case 1:return t?[3,2]:(i("No Password"),[3,5]);case 2:return[4,randomBytes(32)];case 3:return n=s.sent(),r=n.toString("hex"),[4,pbkdf2Promisified(t,r,{iterations:25e3,keylen:512,digestAlgorithm:"sha256"})];case 4:c=s.sent(),l=Buffer.from(c,"binary").toString("hex"),user_collection_1.Users.updateOne({_id:e._id},{$set:{hash:l,salt:r,services:{}}}).then((function(e){return o(e)}),(function(e){return i(e)})),s.label=5;case 5:return[2]}}))}))}))},UserCollection.prototype.changePassword=function(e,t,n){var o=this;return new Promise((function(i,r){return __awaiter(o,void 0,void 0,(function(){var o;return __generator(this,(function(c){switch(c.label){case 0:return e?[3,1]:(r("Missing User"),[3,4]);case 1:return t&&n?[3,2]:(r("Missing Password"),[3,4]);case 2:return[4,this.authenticate(e,t)];case 3:(o=c.sent()).data?this.setPassword(e,n).then((function(e){return i(e)}),(function(e){return r(e)})):r(o.error),c.label=4;case 4:return[2]}}))}))}))},UserCollection.prototype.register=function(e,t){var n=this;return new Promise((function(o,i){return __awaiter(n,void 0,void 0,(function(){return __generator(this,(function(n){switch(n.label){case 0:return e.username?[3,1]:(i("Missing Username"),[3,5]);case 1:return[4,user_collection_1.Users.findOne({username:e.username})];case 2:return n.sent()?(i("Username Exists"),[3,5]):[3,3];case 3:return[4,user_collection_1.Users.findOne({email:e.email})];case 4:n.sent()?i("Email Exists"):(e.setPassword(t),o(e)),n.label=5;case 5:return[2]}}))}))}))},UserCollection.prototype.resetAttempts=function(e){return user_collection_1.Users.updateOne({_id:e._id},{$set:{attempts:0}})},UserCollection}(Collection);function objectIdHexString(){return(new mongodb_1.ObjectId).toHexString()}function pbkdf2(e,t,n,o){crypto.pbkdf2(e,t,n.iterations,n.keylen,n.digestAlgorithm,o)}function pbkdf2Promisified(e,t,n){return new Promise((function(o,i){return pbkdf2(e,t,n,(function(e,t){return e?i(e):o(t)}))}))}function randomBytes(e){return new Promise((function(t,n){return crypto.randomBytes(e,(function(e,o){return e?n(e):t(o)}))}))}function objectContainsPropertyDeep(e,t){var n=Object.keys(e);if(n.some((function(e){return e===t})))return!0;for(var o=0;o<n.length;o++){var i=n[o];if(e[i]&&"object"==typeof e[i]&&objectContainsPropertyDeep(e[i],t))return!0}return!1}exports.UserCollection=UserCollection,exports.objectIdHexString=objectIdHexString;
1
+ "use strict";
2
+ var __extends = (this && this.__extends) || (function () {
3
+ var extendStatics = function (d, b) {
4
+ extendStatics = Object.setPrototypeOf ||
5
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
6
+ function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
7
+ return extendStatics(d, b);
8
+ };
9
+ return function (d, b) {
10
+ extendStatics(d, b);
11
+ function __() { this.constructor = d; }
12
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13
+ };
14
+ })();
15
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
16
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
17
+ return new (P || (P = Promise))(function (resolve, reject) {
18
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
19
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
20
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
21
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
22
+ });
23
+ };
24
+ var __generator = (this && this.__generator) || function (thisArg, body) {
25
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
26
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
27
+ function verb(n) { return function (v) { return step([n, v]); }; }
28
+ function step(op) {
29
+ if (f) throw new TypeError("Generator is already executing.");
30
+ while (_) try {
31
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
32
+ if (y = 0, t) op = [op[0] & 2, t.value];
33
+ switch (op[0]) {
34
+ case 0: case 1: t = op; break;
35
+ case 4: _.label++; return { value: op[1], done: false };
36
+ case 5: _.label++; y = op[1]; op = [0]; continue;
37
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
38
+ default:
39
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
40
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
41
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
42
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
43
+ if (t[2]) _.ops.pop();
44
+ _.trys.pop(); continue;
45
+ }
46
+ op = body.call(thisArg, _);
47
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
48
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
49
+ }
50
+ };
51
+ Object.defineProperty(exports, "__esModule", { value: true });
52
+ exports.objectIdHexString = exports.UserCollection = exports.Collection = exports.Model = exports.MongoManager = void 0;
53
+ var simpl_schema_1 = require("simpl-schema");
54
+ var mongodb_1 = require("mongodb");
55
+ var index_1 = require("../index");
56
+ var user_collection_1 = require("../collections/user.collection");
57
+ var common_1 = require("../util/common");
58
+ var log_collection_1 = require("../collections/log.collection");
59
+ var NodeCache = require("node-cache");
60
+ var crypto = require('crypto');
61
+ var scmp = require('scmp');
62
+ var MongoManager = /** @class */ (function () {
63
+ function MongoManager() {
64
+ this._collections = [];
65
+ this._mongoQueue = [];
66
+ this._mongoQueueId = 0;
67
+ this._mongoQueueCacheId = 1;
68
+ this._nodeCache = new NodeCache({ stdTTL: 0, checkperiod: 0 });
69
+ this.runQueue();
70
+ }
71
+ MongoManager.prototype.registerCollection = function (collection) {
72
+ this._collections.push(collection);
73
+ };
74
+ MongoManager.prototype.collections = function () {
75
+ return this._collections;
76
+ };
77
+ MongoManager.prototype.collection = function (collectionName) {
78
+ return this._collections.filter(function (a) { return a.collectionName === collectionName; })[0];
79
+ };
80
+ MongoManager.prototype.addToQueue = function (mongoQueue) {
81
+ var _mongoQueue = this._mongoQueue.filter(function (a) { return a.name_collection === mongoQueue.name_collection && a.name_function === mongoQueue.name_function && a.name_function_addt === mongoQueue.name_function_addt && JSON.stringify(a.data_function) === JSON.stringify(mongoQueue.data_function) && JSON.stringify(a.data_function_addt) === JSON.stringify(mongoQueue.data_function_addt); })[0];
82
+ if (_mongoQueue) {
83
+ if (!_mongoQueue.running) {
84
+ _mongoQueue.cbs.push(mongoQueue.cbs[0]);
85
+ }
86
+ else {
87
+ _mongoQueue.cbs_next.push(mongoQueue.cbs[0]);
88
+ }
89
+ }
90
+ else {
91
+ mongoQueue._id = this._mongoQueueId;
92
+ this._mongoQueueId += 1;
93
+ this._mongoQueue.push(mongoQueue);
94
+ }
95
+ };
96
+ MongoManager.prototype.runQueue = function () {
97
+ return __awaiter(this, void 0, void 0, function () {
98
+ var _this = this;
99
+ return __generator(this, function (_a) {
100
+ setInterval(function () {
101
+ var queueArr = _this._mongoQueue.filter(function (a) { return !a.running && a.cbs.length; });
102
+ if (queueArr.length) {
103
+ var _loop_1 = function (i) {
104
+ var _a, _b, _c;
105
+ var mongoQueue = queueArr[i];
106
+ mongoQueue.running = true;
107
+ if (mongoQueue.cacheId) {
108
+ var res_1 = JSON.parse(_this._nodeCache.get(mongoQueue.cacheId), common_1.dateReviver);
109
+ mongoQueue.cbs.forEach(function (cb) {
110
+ cb(null, res_1, true);
111
+ });
112
+ mongoQueue.cbs = [];
113
+ mongoQueue.running = false;
114
+ }
115
+ else {
116
+ if (!mongoQueue.name_function_addt) {
117
+ (_a = index_1.ResolveIOServer.getMainDB().collection(mongoQueue.name_collection))[mongoQueue.name_function].apply(_a, mongoQueue.data_function).then(function (res) {
118
+ mongoQueue.cacheId = _this._mongoQueueCacheId;
119
+ _this._mongoQueueCacheId += 1;
120
+ _this.addToCache(mongoQueue.cacheId, res);
121
+ mongoQueue.cbs.forEach(function (cb) {
122
+ cb(null, res, false);
123
+ });
124
+ if (mongoQueue.cbs_next.length) {
125
+ mongoQueue.cbs = mongoQueue.cbs_next;
126
+ mongoQueue.cbs_next = [];
127
+ }
128
+ else {
129
+ mongoQueue.cbs = [];
130
+ }
131
+ mongoQueue.running = false;
132
+ }, function (err) {
133
+ mongoQueue.cbs.forEach(function (cb) {
134
+ cb(err, null, false);
135
+ });
136
+ mongoQueue.cbs_next.forEach(function (cb) {
137
+ cb(err, null, false);
138
+ });
139
+ queueArr.splice(_this._mongoQueue.map(function (a) { return a._id; }).indexOf(mongoQueue._id), 1);
140
+ _this._mongoQueue.splice(_this._mongoQueue.map(function (a) { return a._id; }).indexOf(mongoQueue._id), 1);
141
+ });
142
+ }
143
+ else {
144
+ (_b = (_c = index_1.ResolveIOServer.getMainDB().collection(mongoQueue.name_collection))[mongoQueue.name_function].apply(_c, mongoQueue.data_function))[mongoQueue.name_function_addt].apply(_b, mongoQueue.data_function_addt).then(function (res) {
145
+ mongoQueue.cacheId = _this._mongoQueueCacheId;
146
+ _this._mongoQueueCacheId += 1;
147
+ _this.addToCache(mongoQueue.cacheId, res);
148
+ mongoQueue.cbs.forEach(function (cb) {
149
+ cb(null, res, false);
150
+ });
151
+ if (mongoQueue.cbs_next.length) {
152
+ mongoQueue.cbs = mongoQueue.cbs_next;
153
+ mongoQueue.cbs_next = [];
154
+ }
155
+ else {
156
+ mongoQueue.cbs = [];
157
+ }
158
+ mongoQueue.running = false;
159
+ }, function (err) {
160
+ mongoQueue.cbs.forEach(function (cb) {
161
+ cb(err, null, false);
162
+ });
163
+ mongoQueue.cbs_next.forEach(function (cb) {
164
+ cb(err, null, false);
165
+ });
166
+ queueArr.splice(_this._mongoQueue.map(function (a) { return a._id; }).indexOf(mongoQueue._id), 1);
167
+ _this._mongoQueue.splice(_this._mongoQueue.map(function (a) { return a._id; }).indexOf(mongoQueue._id), 1);
168
+ });
169
+ }
170
+ }
171
+ };
172
+ for (var i = 0; i < queueArr.length; i++) {
173
+ _loop_1(i);
174
+ }
175
+ }
176
+ }, 10);
177
+ return [2 /*return*/];
178
+ });
179
+ });
180
+ };
181
+ MongoManager.prototype.addToCache = function (id, data) {
182
+ var nodeCacheSize = this._nodeCache.getStats().vsize;
183
+ if (nodeCacheSize > 100000000) {
184
+ var deleteCount = 0;
185
+ var queueArr = this._mongoQueue.filter(function (a) { return a.cacheId; });
186
+ for (var zz = 0; zz < queueArr.length; zz++) {
187
+ this._nodeCache.del(queueArr[zz].cacheId);
188
+ queueArr[zz].cacheId = 0;
189
+ deleteCount += 1;
190
+ nodeCacheSize = this._nodeCache.getStats().vsize;
191
+ if (nodeCacheSize < 100000000) {
192
+ break;
193
+ }
194
+ }
195
+ console.log('Query Cache: ' + 'Too Big, - Deleted: ' + deleteCount + ' - ' + nodeCacheSize);
196
+ }
197
+ this._nodeCache.set(id, JSON.stringify(data));
198
+ };
199
+ MongoManager.prototype.invalidateQueryCache = function (collection) {
200
+ var _this = this;
201
+ this._mongoQueue.filter(function (a) { return (a.name_collection === collection || a.lookup_collections.includes(collection)) && a.cacheId; }).forEach(function (queue) {
202
+ _this._nodeCache.del(queue.cacheId);
203
+ queue.cacheId = 0;
204
+ });
205
+ };
206
+ return MongoManager;
207
+ }());
208
+ exports.MongoManager = MongoManager;
209
+ var Model = /** @class */ (function () {
210
+ function Model(collectionName, schema, useVersionCollection, useReportBuilder, reportBuilderLookupTables, timestamps, createLogs, checkSchema) {
211
+ if (useVersionCollection === void 0) { useVersionCollection = false; }
212
+ if (useReportBuilder === void 0) { useReportBuilder = true; }
213
+ if (reportBuilderLookupTables === void 0) { reportBuilderLookupTables = []; }
214
+ if (timestamps === void 0) { timestamps = true; }
215
+ if (createLogs === void 0) { createLogs = true; }
216
+ if (checkSchema === void 0) { checkSchema = true; }
217
+ this.collection_main = null;
218
+ this.collection_version = null;
219
+ if (collectionName === 'users') {
220
+ this.collection_main = new UserCollection(collectionName, schema, useReportBuilder, reportBuilderLookupTables, timestamps, createLogs, checkSchema);
221
+ }
222
+ else {
223
+ this.collection_main = new Collection(collectionName, schema, useReportBuilder, reportBuilderLookupTables, timestamps, createLogs, checkSchema);
224
+ }
225
+ if (useVersionCollection) {
226
+ this.collection_main.useVersions = true;
227
+ var versionSchema = common_1.deepCopy(schema);
228
+ versionSchema['_id'].type = 'Object';
229
+ versionSchema['_id'].blackbox = true;
230
+ if (collectionName === 'users') {
231
+ this.collection_version = new UserCollection(collectionName + '.versions', versionSchema, false, [], true, false, false);
232
+ }
233
+ else {
234
+ this.collection_version = new Collection(collectionName + '.versions', versionSchema, false, [], true, false, false);
235
+ }
236
+ if (this.collection_version.indexExists('_id.__v_1__id._id_1')) {
237
+ this.collection_version.dropIndex('_id.__v_1__id._id_1');
238
+ }
239
+ if (!this.collection_version.indexExists('_id._id_1__id.__v_1')) {
240
+ this.collection_version.createIndex({ '_id._id': 1, '_id.__v': 1 });
241
+ }
242
+ this.collection_main.versionCollection = collectionName + '.versions';
243
+ }
244
+ }
245
+ return Model;
246
+ }());
247
+ exports.Model = Model;
248
+ var Collection = /** @class */ (function () {
249
+ function Collection(collectionName, schema, useReportBuilder, reportBuilderLookupTables, timestamps, createLogs, checkSchema) {
250
+ var _this = this;
251
+ this.collectionName = '';
252
+ this.checkSchema = false;
253
+ this.simplschema = null;
254
+ this.rbSchema = null;
255
+ this.timestamps = false;
256
+ this.useVersions = false;
257
+ this.versionCollection = '';
258
+ this.createLogs = true;
259
+ this.useRB = false;
260
+ this.collectionName = collectionName;
261
+ this.simplschema = new simpl_schema_1.default(schema);
262
+ this.timestamps = timestamps;
263
+ this.createLogs = createLogs;
264
+ this.checkSchema = checkSchema;
265
+ if (useReportBuilder) {
266
+ this.useRB = true;
267
+ var schemaCopy = common_1.deepCopy(schema);
268
+ var rbSchema = common_1.buildRbLookups(reportBuilderLookupTables, schemaCopy, []);
269
+ this.rbSchema = common_1.buildRbSchema(rbSchema);
270
+ }
271
+ var interval = setInterval(function () {
272
+ if (index_1.ResolveIOServer && index_1.ResolveIOServer.getMainServer() && index_1.ResolveIOServer.getMongoManager()) {
273
+ index_1.ResolveIOServer.getMongoManager().registerCollection(_this);
274
+ clearInterval(interval);
275
+ }
276
+ }, 1);
277
+ }
278
+ Collection.prototype.aggregate = function (pipeline, options, allowLogs) {
279
+ var _this = this;
280
+ if (allowLogs === void 0) { allowLogs = false; }
281
+ return new Promise(function (resolve, reject) {
282
+ if (_this.createLogs && allowLogs) {
283
+ // Logs.insertOne({
284
+ // _id: objectIdHexString(),
285
+ // type: 'query',
286
+ // collection: this.collectionName,
287
+ // id_document: '',
288
+ // payload: JSON.stringify([pipeline, options], null, 2),
289
+ // method: 'aggregate',
290
+ // id_user: '',
291
+ // user: '',
292
+ // messageId: 0,
293
+ // route: ''
294
+ // });
295
+ index_1.ResolveIOServer.getMongoManager().addToQueue({
296
+ _id: 0,
297
+ name_collection: _this.collectionName,
298
+ name_function: 'aggregate',
299
+ name_function_addt: 'toArray',
300
+ data_function: [pipeline, options],
301
+ data_function_addt: [],
302
+ cbs: [function (err, res, cached) {
303
+ if (_this.createLogs && allowLogs) {
304
+ // Logs.insertOne({
305
+ // _id: objectIdHexString(),
306
+ // type: 'queryResponse',
307
+ // collection: this.collectionName,
308
+ // id_document: '',
309
+ // payload: getBinarySize(JSON.stringify(['Is Cached: ' + cached, err, res])) < 200000 ? JSON.stringify(['Is Cached: ' + cached, err, res], null, 2) : 'Too Big',
310
+ // method: 'aggregate',
311
+ // id_user: '',
312
+ // user: '',
313
+ // messageId: 0,
314
+ // route: ''
315
+ // });
316
+ }
317
+ if (err) {
318
+ reject(err);
319
+ }
320
+ else {
321
+ resolve(res);
322
+ }
323
+ }],
324
+ cbs_next: [],
325
+ running: false,
326
+ cacheId: 0,
327
+ lookup_collections: pipeline.filter(function (a) { return a['$lookup'] && a['$lookup'].from; }).map(function (a) { return a['$lookup'].from; }).filter(function (elem, index, self) {
328
+ return index === self.indexOf(elem);
329
+ })
330
+ });
331
+ }
332
+ else {
333
+ index_1.ResolveIOServer.getMainDB().collection(_this.collectionName).aggregate(pipeline, options).toArray().then(function (res) { return resolve(res); }, function (err) { return reject(err); });
334
+ }
335
+ });
336
+ };
337
+ Collection.prototype.aggregateCount = function (pipeline, options) {
338
+ var _this = this;
339
+ return new Promise(function (resolve, reject) {
340
+ index_1.ResolveIOServer.getMongoManager().addToQueue({
341
+ _id: 0,
342
+ name_collection: _this.collectionName,
343
+ name_function: 'aggregate',
344
+ name_function_addt: 'count',
345
+ data_function: [pipeline, options],
346
+ data_function_addt: [],
347
+ cbs: [function (err, res, cached) {
348
+ if (err) {
349
+ reject(err);
350
+ }
351
+ else {
352
+ resolve(res);
353
+ }
354
+ }],
355
+ cbs_next: [],
356
+ running: false,
357
+ cacheId: 0,
358
+ lookup_collections: pipeline.filter(function (a) { return a['$lookup'] && a['$lookup'].from; }).map(function (a) { return a['$lookup'].from; }).filter(function (elem, index, self) {
359
+ return index === self.indexOf(elem);
360
+ })
361
+ });
362
+ });
363
+ };
364
+ Collection.prototype.aggregateCursor = function (pipeline, options) {
365
+ return index_1.ResolveIOServer.getMainDB().collection(this.collectionName).aggregate(pipeline, options);
366
+ };
367
+ Collection.prototype.aggregateStream = function (pipeline, options) {
368
+ return index_1.ResolveIOServer.getMainDB().collection(this.collectionName).aggregate(pipeline, options).stream();
369
+ };
370
+ Collection.prototype.countDocuments = function (filter, options) {
371
+ if (filter === void 0) { filter = {}; }
372
+ return index_1.ResolveIOServer.getMainDB().collection(this.collectionName).countDocuments(filter, options);
373
+ };
374
+ Collection.prototype.create = function (f_docs, options) {
375
+ var docs = [];
376
+ if (!Array.isArray(f_docs)) {
377
+ return this.insertOne(f_docs, options);
378
+ }
379
+ return this.insertMany(f_docs, options);
380
+ };
381
+ Collection.prototype.createIndex = function (fieldOrSpec, options) {
382
+ return index_1.ResolveIOServer.getMainDB().collection(this.collectionName).createIndex(fieldOrSpec, options);
383
+ };
384
+ Collection.prototype.createIndexes = function (indexSpecs, options) {
385
+ return index_1.ResolveIOServer.getMainDB().collection(this.collectionName).createIndexes(indexSpecs, options);
386
+ };
387
+ Collection.prototype.deleteMany = function (filter, options, bypassLogs) {
388
+ var _this = this;
389
+ if (filter === void 0) { filter = {}; }
390
+ if (bypassLogs === void 0) { bypassLogs = false; }
391
+ return new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
392
+ var docs, i, doc, versionDoc;
393
+ return __generator(this, function (_a) {
394
+ switch (_a.label) {
395
+ case 0:
396
+ if (!(this.createLogs && !bypassLogs)) return [3 /*break*/, 5];
397
+ return [4 /*yield*/, this.find(filter)];
398
+ case 1:
399
+ docs = _a.sent();
400
+ i = 0;
401
+ _a.label = 2;
402
+ case 2:
403
+ if (!(i < docs.length)) return [3 /*break*/, 5];
404
+ doc = docs[i];
405
+ log_collection_1.Logs.insertOne({
406
+ _id: objectIdHexString(),
407
+ type: 'document',
408
+ collection: this.collectionName,
409
+ id_document: doc['_id'],
410
+ payload: common_1.getBinarySize(JSON.stringify([doc, filter, options])) < 200000 ? JSON.stringify([doc, filter, options], null, 2) : 'Too Big',
411
+ method: 'deleteMany',
412
+ id_user: '',
413
+ user: '',
414
+ messageId: 0,
415
+ route: ''
416
+ });
417
+ if (!this.useVersions) return [3 /*break*/, 4];
418
+ versionDoc = common_1.deepCopy(doc);
419
+ versionDoc['_id'] = { _id: doc['_id'], __v: doc['__v'] };
420
+ return [4 /*yield*/, index_1.ResolveIOServer.getMongoManager().collection(this.versionCollection).replaceOne({ _id: { _id: doc['_id'], __v: doc['__v'] } }, versionDoc, { upsert: true })];
421
+ case 3:
422
+ _a.sent();
423
+ _a.label = 4;
424
+ case 4:
425
+ i++;
426
+ return [3 /*break*/, 2];
427
+ case 5:
428
+ index_1.ResolveIOServer.getMainDB().collection(this.collectionName).deleteMany(filter, options).then(function (res) {
429
+ if (res.result.ok) {
430
+ resolve(res.deletedCount);
431
+ }
432
+ else {
433
+ reject(res.result.ok);
434
+ }
435
+ }, function (err) { return reject(err); });
436
+ return [2 /*return*/];
437
+ }
438
+ });
439
+ }); });
440
+ };
441
+ Collection.prototype.deleteOne = function (filter, options, bypassLogs) {
442
+ var _this = this;
443
+ if (filter === void 0) { filter = {}; }
444
+ if (bypassLogs === void 0) { bypassLogs = false; }
445
+ return new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
446
+ var doc, versionDoc;
447
+ return __generator(this, function (_a) {
448
+ switch (_a.label) {
449
+ case 0:
450
+ if (!(this.createLogs && !bypassLogs)) return [3 /*break*/, 3];
451
+ return [4 /*yield*/, this.findOne(filter, null, true)];
452
+ case 1:
453
+ doc = _a.sent();
454
+ if (!doc) return [3 /*break*/, 3];
455
+ log_collection_1.Logs.insertOne({
456
+ _id: objectIdHexString(),
457
+ type: 'document',
458
+ collection: this.collectionName,
459
+ id_document: doc['_id'],
460
+ payload: common_1.getBinarySize(JSON.stringify([doc, filter, options])) < 200000 ? JSON.stringify([doc, filter, options], null, 2) : 'Too Big',
461
+ method: 'deleteOne',
462
+ id_user: '',
463
+ user: '',
464
+ messageId: 0,
465
+ route: ''
466
+ });
467
+ if (!this.useVersions) return [3 /*break*/, 3];
468
+ versionDoc = common_1.deepCopy(doc);
469
+ versionDoc['_id'] = { _id: doc['_id'], __v: doc['__v'] };
470
+ return [4 /*yield*/, index_1.ResolveIOServer.getMongoManager().collection(this.versionCollection).replaceOne({ _id: { _id: doc['_id'], __v: doc['__v'] } }, versionDoc, { upsert: true })];
471
+ case 2:
472
+ _a.sent();
473
+ _a.label = 3;
474
+ case 3:
475
+ index_1.ResolveIOServer.getMainDB().collection(this.collectionName).deleteOne(filter, options).then(function (res) {
476
+ if (res.result.ok) {
477
+ resolve(res.deletedCount);
478
+ }
479
+ else {
480
+ reject(res.result.ok);
481
+ }
482
+ }, function (err) { return reject(err); });
483
+ return [2 /*return*/];
484
+ }
485
+ });
486
+ }); });
487
+ };
488
+ Collection.prototype.distinct = function (key, filter, options) {
489
+ return index_1.ResolveIOServer.getMainDB().collection(this.collectionName).distinct(key, filter, options);
490
+ };
491
+ Collection.prototype.drop = function (options) {
492
+ return index_1.ResolveIOServer.getMainDB().collection(this.collectionName).drop(options);
493
+ };
494
+ Collection.prototype.dropIndex = function (indexName, options) {
495
+ return index_1.ResolveIOServer.getMainDB().collection(this.collectionName).dropIndex(indexName, options);
496
+ };
497
+ Collection.prototype.dropIndexes = function (options) {
498
+ return index_1.ResolveIOServer.getMainDB().collection(this.collectionName).dropIndexes(options);
499
+ };
500
+ Collection.prototype.find = function (filter, options, bypassLogs) {
501
+ var _this = this;
502
+ if (filter === void 0) { filter = {}; }
503
+ if (bypassLogs === void 0) { bypassLogs = false; }
504
+ return new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
505
+ var _this = this;
506
+ return __generator(this, function (_a) {
507
+ if (this.createLogs && !bypassLogs) {
508
+ // Logs.insertOne({
509
+ // _id: objectIdHexString(),
510
+ // type: 'query',
511
+ // collection: this.collectionName,
512
+ // id_document: '',
513
+ // payload: JSON.stringify([filter, options], null, 2),
514
+ // method: 'find',
515
+ // id_user: '',
516
+ // user: '',
517
+ // messageId: 0,
518
+ // route: ''
519
+ // });
520
+ index_1.ResolveIOServer.getMongoManager().addToQueue({
521
+ _id: 0,
522
+ name_collection: this.collectionName,
523
+ name_function: 'find',
524
+ name_function_addt: 'toArray',
525
+ data_function: [filter, options],
526
+ data_function_addt: [],
527
+ cbs: [function (err, res, cached) {
528
+ if (_this.createLogs && !bypassLogs) {
529
+ // Logs.insertOne({
530
+ // _id: objectIdHexString(),
531
+ // type: 'queryResponse',
532
+ // collection: this.collectionName,
533
+ // id_document: '',
534
+ // payload: getBinarySize(JSON.stringify(['Is Cached: ' + cached, err, res])) < 200000 ? JSON.stringify(['Is Cached: ' + cached, err, res], null, 2) : 'Too Big',
535
+ // method: 'find',
536
+ // id_user: '',
537
+ // user: '',
538
+ // messageId: 0,
539
+ // route: ''
540
+ // });
541
+ }
542
+ if (err) {
543
+ reject(err);
544
+ }
545
+ else {
546
+ resolve(res);
547
+ }
548
+ }],
549
+ cbs_next: [],
550
+ running: false,
551
+ cacheId: 0,
552
+ lookup_collections: []
553
+ });
554
+ }
555
+ else {
556
+ index_1.ResolveIOServer.getMainDB().collection(this.collectionName).find(filter, options).toArray().then(function (res) { return resolve(res); }, function (err) { return reject(err); });
557
+ }
558
+ return [2 /*return*/];
559
+ });
560
+ }); });
561
+ };
562
+ Collection.prototype.findById = function (id, options) {
563
+ return index_1.ResolveIOServer.getMainDB().collection(this.collectionName).findOne({ _id: id }, options);
564
+ };
565
+ Collection.prototype.findCount = function (filter, options, bypassLogs) {
566
+ if (filter === void 0) { filter = {}; }
567
+ if (bypassLogs === void 0) { bypassLogs = false; }
568
+ if (this.createLogs && !bypassLogs) {
569
+ // Logs.insertOne({
570
+ // _id: objectIdHexString(),
571
+ // type: 'query',
572
+ // collection: this.collectionName,
573
+ // id_document: '',
574
+ // payload: JSON.stringify([filter, options], null, 2),
575
+ // method: 'findCount',
576
+ // id_user: '',
577
+ // user: '',
578
+ // messageId: 0,
579
+ // route: ''
580
+ // });
581
+ }
582
+ return index_1.ResolveIOServer.getMainDB().collection(this.collectionName).find(filter, options).count();
583
+ };
584
+ Collection.prototype.findCursor = function (filter, options) {
585
+ if (filter === void 0) { filter = {}; }
586
+ return index_1.ResolveIOServer.getMainDB().collection(this.collectionName).find(filter, options);
587
+ };
588
+ Collection.prototype.findStream = function (filter, options, streamOptions) {
589
+ if (filter === void 0) { filter = {}; }
590
+ return index_1.ResolveIOServer.getMainDB().collection(this.collectionName).find(filter, options).stream(streamOptions);
591
+ };
592
+ Collection.prototype.findOne = function (filter, options, bypassLogs) {
593
+ var _this = this;
594
+ if (filter === void 0) { filter = {}; }
595
+ if (bypassLogs === void 0) { bypassLogs = false; }
596
+ return new Promise(function (resolve, reject) {
597
+ if (_this.createLogs && !bypassLogs) {
598
+ // Logs.insertOne({
599
+ // _id: objectIdHexString(),
600
+ // type: 'query',
601
+ // collection: this.collectionName,
602
+ // id_document: '',
603
+ // payload: JSON.stringify([filter, options], null, 2),
604
+ // method: 'findOne',
605
+ // id_user: '',
606
+ // user: '',
607
+ // messageId: 0,
608
+ // route: ''
609
+ // });
610
+ index_1.ResolveIOServer.getMongoManager().addToQueue({
611
+ _id: 0,
612
+ name_collection: _this.collectionName,
613
+ name_function: 'findOne',
614
+ name_function_addt: '',
615
+ data_function: [filter, options],
616
+ data_function_addt: [],
617
+ cbs: [function (err, res, cached) {
618
+ if (err) {
619
+ reject(err);
620
+ }
621
+ else {
622
+ resolve(res);
623
+ }
624
+ if (_this.createLogs && !bypassLogs) {
625
+ // Logs.insertOne({
626
+ // _id: objectIdHexString(),
627
+ // type: 'queryResponse',
628
+ // collection: this.collectionName,
629
+ // id_document: '',
630
+ // payload: getBinarySize(JSON.stringify(['Is Cached: ' + cached, err, res])) < 200000 ? JSON.stringify(['Is Cached: ' + cached, err, res], null, 2) : 'Too Big',
631
+ // method: 'findOne',
632
+ // id_user: '',
633
+ // user: '',
634
+ // messageId: 0,
635
+ // route: ''
636
+ // });
637
+ }
638
+ }],
639
+ cbs_next: [],
640
+ running: false,
641
+ cacheId: 0,
642
+ lookup_collections: []
643
+ });
644
+ }
645
+ else {
646
+ index_1.ResolveIOServer.getMainDB().collection(_this.collectionName).findOne(filter, options).then(function (res) { return resolve(res); }, function (err) { return reject(err); });
647
+ }
648
+ });
649
+ };
650
+ Collection.prototype.findOneAndDelete = function (filter, options, bypassLogs) {
651
+ var _this = this;
652
+ if (filter === void 0) { filter = {}; }
653
+ if (bypassLogs === void 0) { bypassLogs = false; }
654
+ return new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
655
+ var doc;
656
+ var _this = this;
657
+ return __generator(this, function (_a) {
658
+ switch (_a.label) {
659
+ case 0:
660
+ if (!(this.createLogs && !bypassLogs)) return [3 /*break*/, 2];
661
+ return [4 /*yield*/, this.findOne(filter, null, true)];
662
+ case 1:
663
+ doc = _a.sent();
664
+ if (doc) {
665
+ log_collection_1.Logs.insertOne({
666
+ _id: objectIdHexString(),
667
+ type: 'document',
668
+ collection: this.collectionName,
669
+ id_document: doc['_id'],
670
+ payload: common_1.getBinarySize(JSON.stringify([doc, filter, options])) < 200000 ? JSON.stringify([doc, filter, options], null, 2) : 'Too Big',
671
+ method: 'findOneAndDelete',
672
+ id_user: '',
673
+ user: '',
674
+ messageId: 0,
675
+ route: ''
676
+ });
677
+ }
678
+ _a.label = 2;
679
+ case 2:
680
+ index_1.ResolveIOServer.getMainDB().collection(this.collectionName).findOneAndDelete(filter, options).then(function (res) {
681
+ if (res.ok) {
682
+ resolve(res.value);
683
+ }
684
+ else {
685
+ reject(res.lastErrorObject);
686
+ }
687
+ if (_this.createLogs && !bypassLogs) {
688
+ // Logs.insertOne({
689
+ // _id: objectIdHexString(),
690
+ // type: 'queryResponse',
691
+ // collection: this.collectionName,
692
+ // id_document: '',
693
+ // payload: getBinarySize(JSON.stringify([res.value])) < 200000 ? JSON.stringify([res.value], null, 2) : 'Too Big',
694
+ // method: 'findOneAndDelete',
695
+ // id_user: '',
696
+ // user: '',
697
+ // messageId: 0,
698
+ // route: ''
699
+ // });
700
+ }
701
+ }, function (err) {
702
+ reject(err);
703
+ if (_this.createLogs && !bypassLogs) {
704
+ // Logs.insertOne({
705
+ // _id: objectIdHexString(),
706
+ // type: 'queryResponse',
707
+ // collection: this.collectionName,
708
+ // id_document: '',
709
+ // payload: getBinarySize(JSON.stringify([err])) < 200000 ? JSON.stringify([err], null, 2) : 'Too Big',
710
+ // method: 'findOneAndDelete',
711
+ // id_user: '',
712
+ // user: '',
713
+ // messageId: 0,
714
+ // route: ''
715
+ // });
716
+ }
717
+ });
718
+ return [2 /*return*/];
719
+ }
720
+ });
721
+ }); });
722
+ };
723
+ Collection.prototype.findOneAndReplace = function (filter, replacement, options, bypassLogs, bypassCheckSchema) {
724
+ var _this = this;
725
+ if (filter === void 0) { filter = {}; }
726
+ if (bypassLogs === void 0) { bypassLogs = false; }
727
+ if (bypassCheckSchema === void 0) { bypassCheckSchema = false; }
728
+ return new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
729
+ var validation, isValid, date, doc;
730
+ var _this = this;
731
+ return __generator(this, function (_a) {
732
+ switch (_a.label) {
733
+ case 0:
734
+ if (this.checkSchema && !bypassCheckSchema) {
735
+ validation = this.simplschema.newContext();
736
+ isValid = validation.validate(replacement);
737
+ if (!isValid) {
738
+ console.log(new Date(), this.collectionName, 'Schema Errors - findOneAndReplace', validation.validationErrors());
739
+ index_1.ResolveIOServer.getMainServer().getMethodManager().callMethodInternal('insertErrorLog', 'Schema Failed on findOneAndReplace - ' + this.collectionName, [validation.validationErrors(), replacement]);
740
+ reject(validation.validationErrors());
741
+ return [2 /*return*/];
742
+ }
743
+ }
744
+ date = new Date();
745
+ if (this.timestamps) {
746
+ replacement['updatedAt'] = date;
747
+ }
748
+ if (!(this.createLogs && !bypassLogs)) return [3 /*break*/, 2];
749
+ return [4 /*yield*/, this.findOne(filter, null, true)];
750
+ case 1:
751
+ doc = _a.sent();
752
+ if (doc) {
753
+ log_collection_1.Logs.insertOne({
754
+ _id: objectIdHexString(),
755
+ type: 'document',
756
+ collection: this.collectionName,
757
+ id_document: doc['_id'],
758
+ payload: common_1.getBinarySize(JSON.stringify([doc, filter, replacement, options])) < 200000 ? JSON.stringify([doc, filter, replacement, options], null, 2) : 'Too Big',
759
+ method: 'findOneAndReplace',
760
+ id_user: '',
761
+ user: '',
762
+ messageId: 0,
763
+ route: ''
764
+ });
765
+ }
766
+ _a.label = 2;
767
+ case 2:
768
+ index_1.ResolveIOServer.getMainDB().collection(this.collectionName).findOneAndReplace(filter, replacement, options).then(function (res) {
769
+ if (res.ok) {
770
+ resolve(res.value);
771
+ }
772
+ else {
773
+ reject(res.lastErrorObject);
774
+ }
775
+ if (_this.createLogs && !bypassLogs) {
776
+ // Logs.insertOne({
777
+ // _id: objectIdHexString(),
778
+ // type: 'queryResponse',
779
+ // collection: this.collectionName,
780
+ // id_document: '',
781
+ // payload: getBinarySize(JSON.stringify([res.value])) < 200000 ? JSON.stringify([res.value], null, 2) : 'Too Big',
782
+ // method: 'findOneAndReplace',
783
+ // id_user: '',
784
+ // user: '',
785
+ // messageId: 0,
786
+ // route: ''
787
+ // });
788
+ }
789
+ }, function (err) {
790
+ reject(err);
791
+ if (_this.createLogs && !bypassLogs) {
792
+ // Logs.insertOne({
793
+ // _id: objectIdHexString(),
794
+ // type: 'queryResponse',
795
+ // collection: this.collectionName,
796
+ // id_document: '',
797
+ // payload: getBinarySize(JSON.stringify([err])) < 200000 ? JSON.stringify([err], null, 2) : 'Too Big',
798
+ // method: 'findOneAndReplace',
799
+ // id_user: '',
800
+ // user: '',
801
+ // messageId: 0,
802
+ // route: ''
803
+ // });
804
+ }
805
+ });
806
+ return [2 /*return*/];
807
+ }
808
+ });
809
+ }); });
810
+ };
811
+ Collection.prototype.findOneAndUpdate = function (filter, update, options, bypassLogs, bypassCheckSchema) {
812
+ var _this = this;
813
+ if (filter === void 0) { filter = {}; }
814
+ if (bypassLogs === void 0) { bypassLogs = false; }
815
+ if (bypassCheckSchema === void 0) { bypassCheckSchema = false; }
816
+ return new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
817
+ var validation, isValid, date, doc;
818
+ var _this = this;
819
+ return __generator(this, function (_a) {
820
+ switch (_a.label) {
821
+ case 0:
822
+ if (this.checkSchema && !bypassCheckSchema) {
823
+ validation = this.simplschema.newContext();
824
+ isValid = validation.validate(update, { modifier: true });
825
+ if (!isValid) {
826
+ console.log(new Date(), this.collectionName, 'Schema Errors - findOneAndUpdate', validation.validationErrors());
827
+ index_1.ResolveIOServer.getMainServer().getMethodManager().callMethodInternal('insertErrorLog', 'Schema Failed on findOneAndUpdate - ' + this.collectionName, [validation.validationErrors(), update]);
828
+ reject(validation.validationErrors());
829
+ return [2 /*return*/];
830
+ }
831
+ }
832
+ if (this.timestamps) {
833
+ date = new Date();
834
+ if (!update['$set']) {
835
+ update['$set'] = { updatedAt: date };
836
+ }
837
+ else {
838
+ update['$set']['updatedAt'] = date;
839
+ }
840
+ }
841
+ if (!(this.createLogs && !bypassLogs)) return [3 /*break*/, 2];
842
+ return [4 /*yield*/, this.findOne(filter, null, true)];
843
+ case 1:
844
+ doc = _a.sent();
845
+ if (doc) {
846
+ log_collection_1.Logs.insertOne({
847
+ _id: objectIdHexString(),
848
+ type: 'document',
849
+ collection: this.collectionName,
850
+ id_document: doc['_id'],
851
+ payload: common_1.getBinarySize(JSON.stringify([doc, filter, update, options])) < 200000 ? JSON.stringify([doc, filter, update, options], null, 2) : 'Too Big',
852
+ method: 'findOneAndUpdate',
853
+ id_user: '',
854
+ user: '',
855
+ messageId: 0,
856
+ route: ''
857
+ });
858
+ }
859
+ _a.label = 2;
860
+ case 2:
861
+ index_1.ResolveIOServer.getMainDB().collection(this.collectionName).findOneAndUpdate(filter, update, options).then(function (res) {
862
+ if (res.ok) {
863
+ resolve(res.value);
864
+ }
865
+ else {
866
+ reject(res.lastErrorObject);
867
+ }
868
+ if (_this.createLogs && !bypassLogs) {
869
+ // Logs.insertOne({
870
+ // _id: objectIdHexString(),
871
+ // type: 'queryResponse',
872
+ // collection: this.collectionName,
873
+ // id_document: '',
874
+ // payload: getBinarySize(JSON.stringify([res.value])) < 200000 ? JSON.stringify([res.value], null, 2) : 'Too Big',
875
+ // method: 'findOneAndUpdate',
876
+ // id_user: '',
877
+ // user: '',
878
+ // messageId: 0,
879
+ // route: ''
880
+ // });
881
+ }
882
+ }, function (err) {
883
+ reject(err);
884
+ if (_this.createLogs && !bypassLogs) {
885
+ // Logs.insertOne({
886
+ // _id: objectIdHexString(),
887
+ // type: 'queryResponse',
888
+ // collection: this.collectionName,
889
+ // id_document: '',
890
+ // payload: getBinarySize(JSON.stringify([err])) < 200000 ? JSON.stringify([err], null, 2) : 'Too Big',
891
+ // method: 'findOneAndUpdate',
892
+ // id_user: '',
893
+ // user: '',
894
+ // messageId: 0,
895
+ // route: ''
896
+ // });
897
+ }
898
+ });
899
+ return [2 /*return*/];
900
+ }
901
+ });
902
+ }); });
903
+ };
904
+ Collection.prototype.indexes = function (options) {
905
+ return index_1.ResolveIOServer.getMainDB().collection(this.collectionName).indexes(options);
906
+ };
907
+ Collection.prototype.indexExists = function (indexes, options) {
908
+ return index_1.ResolveIOServer.getMainDB().collection(this.collectionName).indexExists(indexes, options);
909
+ };
910
+ Collection.prototype.insertMany = function (docs, options, bypassLogs, bypassCheckSchema) {
911
+ var _this = this;
912
+ if (bypassLogs === void 0) { bypassLogs = false; }
913
+ if (bypassCheckSchema === void 0) { bypassCheckSchema = false; }
914
+ return new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
915
+ var validationResults, validDocs, i, doc, date;
916
+ var _this = this;
917
+ return __generator(this, function (_a) {
918
+ if (!docs.length) {
919
+ resolve([]);
920
+ return [2 /*return*/];
921
+ }
922
+ validationResults = [];
923
+ if (this.checkSchema && !bypassCheckSchema) {
924
+ docs.forEach(function (doc) {
925
+ var validation = _this.simplschema.newContext();
926
+ var isValid = validation.validate(doc);
927
+ if (!isValid) {
928
+ console.log(new Date(), _this.collectionName, 'Schema Errors - insertMany', validation.validationErrors());
929
+ index_1.ResolveIOServer.getMainServer().getMethodManager().callMethodInternal('insertErrorLog', 'Schema Failed on insertMany - ' + _this.collectionName, [validation.validationErrors(), doc]);
930
+ validationResults.push(false);
931
+ }
932
+ else {
933
+ validationResults.push(true);
934
+ }
935
+ });
936
+ }
937
+ validDocs = this.checkSchema ? docs.filter(function (a, idx) { return validationResults[idx]; }) : docs;
938
+ for (i = 0; i < validDocs.length; i++) {
939
+ doc = validDocs[i];
940
+ if (!doc['_id']) {
941
+ doc['_id'] = objectIdHexString();
942
+ }
943
+ if (this.timestamps) {
944
+ date = new Date();
945
+ doc['createdAt'] = date;
946
+ doc['updatedAt'] = date;
947
+ }
948
+ if (this.createLogs && !bypassLogs) {
949
+ log_collection_1.Logs.insertOne({
950
+ _id: objectIdHexString(),
951
+ type: 'document',
952
+ collection: this.collectionName,
953
+ id_document: doc['_id'],
954
+ payload: common_1.getBinarySize(JSON.stringify([doc, options])) < 200000 ? JSON.stringify([doc, options], null, 2) : 'Too Big',
955
+ method: 'insertMany',
956
+ id_user: '',
957
+ user: '',
958
+ messageId: 0,
959
+ route: ''
960
+ });
961
+ }
962
+ }
963
+ if (validDocs.length) {
964
+ index_1.ResolveIOServer.getMainDB().collection(this.collectionName).insertMany(validDocs, options).then(function (res) {
965
+ if (res.result.ok) {
966
+ resolve(validDocs);
967
+ }
968
+ else {
969
+ reject(res.result.ok);
970
+ }
971
+ }, function (err) {
972
+ reject(err);
973
+ });
974
+ }
975
+ return [2 /*return*/];
976
+ });
977
+ }); });
978
+ };
979
+ Collection.prototype.insertOne = function (doc, options, bypassLogs, bypassCheckSchema) {
980
+ var _this = this;
981
+ if (bypassLogs === void 0) { bypassLogs = false; }
982
+ if (bypassCheckSchema === void 0) { bypassCheckSchema = false; }
983
+ return new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
984
+ var validation, isValid, date;
985
+ return __generator(this, function (_a) {
986
+ if (!doc['_id']) {
987
+ doc['_id'] = objectIdHexString();
988
+ }
989
+ if (this.checkSchema && !bypassCheckSchema) {
990
+ validation = this.simplschema.newContext();
991
+ isValid = validation.validate(doc);
992
+ if (!isValid) {
993
+ console.log(new Date(), this.collectionName, 'Schema Errors - insertOne', validation.validationErrors());
994
+ index_1.ResolveIOServer.getMainServer().getMethodManager().callMethodInternal('insertErrorLog', 'Schema Failed on insertOne - ' + this.collectionName, [validation.validationErrors(), doc]);
995
+ reject(validation.validationErrors());
996
+ return [2 /*return*/];
997
+ }
998
+ }
999
+ if (this.timestamps) {
1000
+ date = new Date();
1001
+ doc['createdAt'] = date;
1002
+ doc['updatedAt'] = date;
1003
+ }
1004
+ if (this.createLogs && !bypassLogs) {
1005
+ log_collection_1.Logs.insertOne({
1006
+ _id: objectIdHexString(),
1007
+ type: 'document',
1008
+ collection: this.collectionName,
1009
+ id_document: doc['_id'],
1010
+ payload: common_1.getBinarySize(JSON.stringify([doc, options])) < 200000 ? JSON.stringify([doc, options], null, 2) : 'Too Big',
1011
+ method: 'insertOne',
1012
+ id_user: '',
1013
+ user: '',
1014
+ messageId: 0,
1015
+ route: ''
1016
+ });
1017
+ }
1018
+ if (this.useVersions && !doc.hasOwnProperty('__v')) {
1019
+ doc['__v'] = 0;
1020
+ }
1021
+ index_1.ResolveIOServer.getMainDB().collection(this.collectionName).insertOne(doc, options).then(function (res) {
1022
+ if (res.result.ok) {
1023
+ resolve(doc);
1024
+ }
1025
+ else {
1026
+ reject(res.result.ok);
1027
+ }
1028
+ }, function (err) {
1029
+ reject(err);
1030
+ });
1031
+ return [2 /*return*/];
1032
+ });
1033
+ }); });
1034
+ };
1035
+ Collection.prototype.listIndexes = function (options) {
1036
+ return index_1.ResolveIOServer.getMainDB().collection(this.collectionName).listIndexes(options);
1037
+ };
1038
+ Collection.prototype.reIndex = function (options) {
1039
+ return index_1.ResolveIOServer.getMainDB().collection(this.collectionName).reIndex(options);
1040
+ };
1041
+ Collection.prototype.rename = function (newName, options) {
1042
+ return index_1.ResolveIOServer.getMainDB().collection(this.collectionName).rename(newName, options);
1043
+ };
1044
+ Collection.prototype.replaceOne = function (filter, replacement, options, bypassLogs, bypassCheckSchema, doc) {
1045
+ var _this = this;
1046
+ if (bypassLogs === void 0) { bypassLogs = false; }
1047
+ if (bypassCheckSchema === void 0) { bypassCheckSchema = false; }
1048
+ if (doc === void 0) { doc = null; }
1049
+ return new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
1050
+ var validation, isValid, date, versionDoc, prevDoc, docId, docVersion, updatedDoc;
1051
+ return __generator(this, function (_a) {
1052
+ switch (_a.label) {
1053
+ case 0:
1054
+ if (this.checkSchema && !bypassCheckSchema) {
1055
+ validation = this.simplschema.newContext();
1056
+ isValid = validation.validate(replacement);
1057
+ if (!isValid) {
1058
+ console.log(new Date(), this.collectionName, 'Schema Errors - replaceOne', validation.validationErrors());
1059
+ index_1.ResolveIOServer.getMainServer().getMethodManager().callMethodInternal('insertErrorLog', 'Schema Failed on replaceOne - ' + this.collectionName, [validation.validationErrors(), replacement]);
1060
+ reject(validation.validationErrors());
1061
+ return [2 /*return*/];
1062
+ }
1063
+ }
1064
+ date = new Date();
1065
+ if (this.timestamps) {
1066
+ replacement['updatedAt'] = date;
1067
+ }
1068
+ if (!!doc) return [3 /*break*/, 2];
1069
+ return [4 /*yield*/, this.findOne(filter, null, true)];
1070
+ case 1:
1071
+ doc = _a.sent();
1072
+ _a.label = 2;
1073
+ case 2:
1074
+ if (!doc) return [3 /*break*/, 11];
1075
+ if (this.timestamps && !replacement['createdAt'] && doc['createdAt']) {
1076
+ replacement['createdAt'] = doc['createdAt'];
1077
+ }
1078
+ if (this.createLogs && !bypassLogs) {
1079
+ log_collection_1.Logs.insertOne({
1080
+ _id: objectIdHexString(),
1081
+ type: 'document',
1082
+ collection: this.collectionName,
1083
+ id_document: doc['_id'],
1084
+ payload: common_1.getBinarySize(JSON.stringify([doc, filter, replacement, options])) < 200000 ? JSON.stringify([doc, filter, replacement, options], null, 2) : 'Too Big',
1085
+ method: 'replaceOne',
1086
+ id_user: '',
1087
+ user: '',
1088
+ messageId: 0,
1089
+ route: ''
1090
+ });
1091
+ }
1092
+ if (!this.useVersions) return [3 /*break*/, 9];
1093
+ if (!(doc['__v'] === replacement['__v'])) return [3 /*break*/, 6];
1094
+ replacement['__v'] += 1;
1095
+ versionDoc = common_1.deepCopy(doc);
1096
+ versionDoc['_id'] = { _id: doc['_id'], __v: doc['__v'] };
1097
+ return [4 /*yield*/, index_1.ResolveIOServer.getMongoManager().collection(this.versionCollection).replaceOne({ _id: { _id: doc['_id'], __v: doc['__v'] } }, versionDoc, { upsert: true })];
1098
+ case 3:
1099
+ _a.sent();
1100
+ if (!(doc['__v'] >= 4)) return [3 /*break*/, 5];
1101
+ return [4 /*yield*/, index_1.ResolveIOServer.getMongoManager().collection(this.versionCollection).deleteMany({
1102
+ _id: {
1103
+ _id: doc['_id'],
1104
+ __v: { $lte: doc['__v'] - 4 }
1105
+ }
1106
+ })];
1107
+ case 4:
1108
+ _a.sent();
1109
+ _a.label = 5;
1110
+ case 5:
1111
+ index_1.ResolveIOServer.getMainDB().collection(this.collectionName).replaceOne(filter, replacement, options).then(function (res) {
1112
+ if (res.result.ok) {
1113
+ resolve(res.result.nModified);
1114
+ }
1115
+ else {
1116
+ reject(res.result.ok);
1117
+ }
1118
+ }, function (err) {
1119
+ reject(err);
1120
+ });
1121
+ return [3 /*break*/, 8];
1122
+ case 6:
1123
+ console.log('invalid version - ' + this.collectionName, doc['__v'], replacement['__v']);
1124
+ return [4 /*yield*/, index_1.ResolveIOServer.getMongoManager().collection(this.versionCollection).findOne({
1125
+ _id: {
1126
+ _id: doc['_id'],
1127
+ __v: replacement['__v']
1128
+ }
1129
+ }, null, true)];
1130
+ case 7:
1131
+ prevDoc = _a.sent();
1132
+ if (prevDoc) {
1133
+ docId = doc['_id'];
1134
+ docVersion = doc['__v'];
1135
+ updatedDoc = common_1.getMongoMergeUpdatedDoc(replacement, doc, prevDoc);
1136
+ updatedDoc['_id'] = docId;
1137
+ updatedDoc['__v'] = docVersion + 1;
1138
+ index_1.ResolveIOServer.getMainDB().collection(this.collectionName).replaceOne(filter, updatedDoc, options).then(function (res) {
1139
+ if (res.result.ok) {
1140
+ resolve(res.result.nModified);
1141
+ }
1142
+ else {
1143
+ reject(res.result.ok);
1144
+ }
1145
+ }, function (err) {
1146
+ reject(err);
1147
+ });
1148
+ }
1149
+ else {
1150
+ reject('Invalid Version And Could Not Find History - DB: ' + doc['__v'] + ', Trying to update with :' + replacement['__v']);
1151
+ }
1152
+ _a.label = 8;
1153
+ case 8: return [3 /*break*/, 10];
1154
+ case 9:
1155
+ index_1.ResolveIOServer.getMainDB().collection(this.collectionName).replaceOne(filter, replacement, options).then(function (res) {
1156
+ if (res.result.ok) {
1157
+ resolve(res.result.nModified);
1158
+ }
1159
+ else {
1160
+ reject(res.result.ok);
1161
+ }
1162
+ }, function (err) {
1163
+ reject(err);
1164
+ });
1165
+ _a.label = 10;
1166
+ case 10: return [3 /*break*/, 12];
1167
+ case 11:
1168
+ if (options && options.upsert) {
1169
+ if (this.timestamps) {
1170
+ replacement['createdAt'] = date;
1171
+ }
1172
+ if (this.createLogs && !bypassLogs) {
1173
+ log_collection_1.Logs.insertOne({
1174
+ _id: objectIdHexString(),
1175
+ type: 'document',
1176
+ collection: this.collectionName,
1177
+ id_document: replacement['_id'],
1178
+ payload: common_1.getBinarySize(JSON.stringify([filter, replacement, options])) < 200000 ? JSON.stringify([filter, replacement, options], null, 2) : 'Too Big',
1179
+ method: 'replaceOne',
1180
+ id_user: '',
1181
+ user: '',
1182
+ messageId: 0,
1183
+ route: ''
1184
+ });
1185
+ }
1186
+ if (this.useVersions) {
1187
+ replacement['__v'] = 0;
1188
+ }
1189
+ index_1.ResolveIOServer.getMainDB().collection(this.collectionName).replaceOne(filter, replacement, options).then(function (res) {
1190
+ if (res.result.ok) {
1191
+ resolve(res.result.nModified);
1192
+ }
1193
+ else {
1194
+ reject(res.result.ok);
1195
+ }
1196
+ }, function (err) {
1197
+ reject(err);
1198
+ });
1199
+ }
1200
+ else {
1201
+ reject('No Document');
1202
+ }
1203
+ _a.label = 12;
1204
+ case 12: return [2 /*return*/];
1205
+ }
1206
+ });
1207
+ }); });
1208
+ };
1209
+ Collection.prototype.stats = function (options) {
1210
+ return index_1.ResolveIOServer.getMainDB().collection(this.collectionName).stats(options);
1211
+ };
1212
+ Collection.prototype.updateMany = function (filter, update, options, bypassLogs, bypassCheckSchema) {
1213
+ var _this = this;
1214
+ if (bypassLogs === void 0) { bypassLogs = false; }
1215
+ if (bypassCheckSchema === void 0) { bypassCheckSchema = false; }
1216
+ return new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
1217
+ var date, validation, isValid, docs, i, doc;
1218
+ return __generator(this, function (_a) {
1219
+ switch (_a.label) {
1220
+ case 0:
1221
+ if (this.timestamps) {
1222
+ date = new Date();
1223
+ if (!update.$set) {
1224
+ update.$set = { updatedAt: date };
1225
+ }
1226
+ else {
1227
+ update.$set['updatedAt'] = date;
1228
+ }
1229
+ }
1230
+ if (this.checkSchema && !bypassCheckSchema) {
1231
+ validation = this.simplschema.newContext();
1232
+ isValid = validation.validate(update, { modifier: true });
1233
+ if (!isValid) {
1234
+ console.log(new Date(), this.collectionName, 'Schema Errors - updateMany', validation.validationErrors());
1235
+ index_1.ResolveIOServer.getMainServer().getMethodManager().callMethodInternal('insertErrorLog', 'Schema Failed on updateMany - ' + this.collectionName, [validation.validationErrors(), update]);
1236
+ reject(validation.validationErrors());
1237
+ return [2 /*return*/];
1238
+ }
1239
+ }
1240
+ if (!(this.createLogs && !bypassLogs)) return [3 /*break*/, 2];
1241
+ return [4 /*yield*/, this.find(filter)];
1242
+ case 1:
1243
+ docs = _a.sent();
1244
+ for (i = 0; i < docs.length; i++) {
1245
+ doc = docs[i];
1246
+ log_collection_1.Logs.insertOne({
1247
+ _id: objectIdHexString(),
1248
+ type: 'document',
1249
+ collection: this.collectionName,
1250
+ id_document: doc['_id'],
1251
+ payload: common_1.getBinarySize(JSON.stringify([doc, filter, update, options])) < 200000 ? JSON.stringify([doc, filter, update, options], null, 2) : 'Too Big',
1252
+ method: 'updateMany',
1253
+ id_user: '',
1254
+ user: '',
1255
+ messageId: 0,
1256
+ route: ''
1257
+ });
1258
+ }
1259
+ _a.label = 2;
1260
+ case 2:
1261
+ index_1.ResolveIOServer.getMainDB().collection(this.collectionName).updateMany(filter, update, options).then(function (res) {
1262
+ if (res.result.ok) {
1263
+ resolve(res.result.nModified);
1264
+ }
1265
+ else {
1266
+ reject(res.result.ok);
1267
+ }
1268
+ }, function (err) { return reject(err); });
1269
+ return [2 /*return*/];
1270
+ }
1271
+ });
1272
+ }); });
1273
+ };
1274
+ Collection.prototype.updateOne = function (filter, update, options, bypassLogs, bypassCheckSchema) {
1275
+ var _this = this;
1276
+ if (bypassLogs === void 0) { bypassLogs = false; }
1277
+ if (bypassCheckSchema === void 0) { bypassCheckSchema = false; }
1278
+ return new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
1279
+ var date, validation, isValid, doc, versionDoc;
1280
+ return __generator(this, function (_a) {
1281
+ switch (_a.label) {
1282
+ case 0:
1283
+ date = new Date();
1284
+ if (this.timestamps) {
1285
+ if (!update.$set) {
1286
+ update.$set = { updatedAt: date };
1287
+ }
1288
+ else {
1289
+ update.$set['updatedAt'] = date;
1290
+ }
1291
+ }
1292
+ if (this.checkSchema && !bypassCheckSchema) {
1293
+ validation = this.simplschema.newContext();
1294
+ isValid = validation.validate(update, { modifier: true });
1295
+ if (!isValid) {
1296
+ console.log(new Date(), this.collectionName, 'Schema Errors - updateOne', validation.validationErrors());
1297
+ index_1.ResolveIOServer.getMainServer().getMethodManager().callMethodInternal('insertErrorLog', 'Schema Failed on updateOne - ' + this.collectionName, [validation.validationErrors(), update]);
1298
+ reject(validation.validationErrors());
1299
+ return [2 /*return*/];
1300
+ }
1301
+ }
1302
+ return [4 /*yield*/, this.findOne(filter, null, true)];
1303
+ case 1:
1304
+ doc = _a.sent();
1305
+ if (!doc) return [3 /*break*/, 7];
1306
+ if (this.createLogs && !bypassLogs) {
1307
+ log_collection_1.Logs.insertOne({
1308
+ _id: objectIdHexString(),
1309
+ type: 'document',
1310
+ collection: this.collectionName,
1311
+ id_document: doc['_id'],
1312
+ payload: common_1.getBinarySize(JSON.stringify([doc, filter, update, options])) < 200000 ? JSON.stringify([doc, filter, update, options], null, 2) : 'Too Big',
1313
+ method: 'updateOne',
1314
+ id_user: '',
1315
+ user: '',
1316
+ messageId: 0,
1317
+ route: ''
1318
+ });
1319
+ }
1320
+ if (!this.useVersions) return [3 /*break*/, 5];
1321
+ versionDoc = common_1.deepCopy(doc);
1322
+ versionDoc['_id'] = { _id: doc['_id'], __v: doc['__v'] };
1323
+ return [4 /*yield*/, index_1.ResolveIOServer.getMongoManager().collection(this.versionCollection).replaceOne({ _id: { _id: doc['_id'], __v: doc['__v'] } }, versionDoc, { upsert: true })];
1324
+ case 2:
1325
+ _a.sent();
1326
+ if (!(doc['__v'] >= 4)) return [3 /*break*/, 4];
1327
+ return [4 /*yield*/, index_1.ResolveIOServer.getMongoManager().collection(this.versionCollection).deleteMany({
1328
+ _id: {
1329
+ _id: doc['_id'],
1330
+ __v: { $lte: doc['__v'] - 4 }
1331
+ }
1332
+ })];
1333
+ case 3:
1334
+ _a.sent();
1335
+ _a.label = 4;
1336
+ case 4:
1337
+ if (!objectContainsPropertyDeep(update, '__v')) {
1338
+ if (!update.$inc) {
1339
+ update.$inc = { __v: 1 };
1340
+ }
1341
+ else if (!update.$inc.__v) {
1342
+ update.$inc.__v = 1;
1343
+ }
1344
+ }
1345
+ index_1.ResolveIOServer.getMainDB().collection(this.collectionName).updateOne(filter, update, options).then(function (res) {
1346
+ if (res.result.ok) {
1347
+ resolve(res.result.nModified);
1348
+ }
1349
+ else {
1350
+ reject(res.result.ok);
1351
+ }
1352
+ }, function (err) { return reject(err); });
1353
+ return [3 /*break*/, 6];
1354
+ case 5:
1355
+ index_1.ResolveIOServer.getMainDB().collection(this.collectionName).updateOne(filter, update, options).then(function (res) {
1356
+ if (res.result.ok) {
1357
+ resolve(res.result.nModified);
1358
+ }
1359
+ else {
1360
+ reject(res.result.ok);
1361
+ }
1362
+ }, function (err) { return reject(err); });
1363
+ _a.label = 6;
1364
+ case 6: return [3 /*break*/, 8];
1365
+ case 7:
1366
+ if (options && options.upsert && update.$setOnInsert && update.$setOnInsert._id) {
1367
+ if (this.timestamps) {
1368
+ if (!update.$setOnInsert.createdAt) {
1369
+ update.$setOnInsert.createdAt = date;
1370
+ }
1371
+ }
1372
+ if (this.createLogs && !bypassLogs) {
1373
+ log_collection_1.Logs.insertOne({
1374
+ _id: objectIdHexString(),
1375
+ type: 'document',
1376
+ collection: this.collectionName,
1377
+ id_document: update.$setOnInsert._id,
1378
+ payload: common_1.getBinarySize(JSON.stringify([filter, update, options])) < 200000 ? JSON.stringify([filter, update, options], null, 2) : 'Too Big',
1379
+ method: 'updateOne',
1380
+ id_user: '',
1381
+ user: '',
1382
+ messageId: 0,
1383
+ route: ''
1384
+ });
1385
+ }
1386
+ if (this.useVersions) {
1387
+ if (!objectContainsPropertyDeep(update, '__v')) {
1388
+ update.$setOnInsert.__v = 0;
1389
+ }
1390
+ }
1391
+ index_1.ResolveIOServer.getMainDB().collection(this.collectionName).updateOne(filter, update, options).then(function (res) {
1392
+ if (res.result.ok) {
1393
+ resolve(res.result.nModified);
1394
+ }
1395
+ else {
1396
+ reject(res.result.ok);
1397
+ }
1398
+ }, function (err) { return reject(err); });
1399
+ }
1400
+ else {
1401
+ reject('No Document');
1402
+ }
1403
+ _a.label = 8;
1404
+ case 8: return [2 /*return*/];
1405
+ }
1406
+ });
1407
+ }); });
1408
+ };
1409
+ Collection.prototype.watchCollection = function (pipeline, options) {
1410
+ if (pipeline === void 0) { pipeline = []; }
1411
+ return index_1.ResolveIOServer.getMainDB().collection(this.collectionName).watch(pipeline, options);
1412
+ };
1413
+ Collection.prototype.watchCollectionWithAggregate = function (pipeline, options) {
1414
+ if (pipeline === void 0) { pipeline = []; }
1415
+ return index_1.ResolveIOServer.getMainDB().collection(this.collectionName).watch(pipeline, options);
1416
+ };
1417
+ return Collection;
1418
+ }());
1419
+ exports.Collection = Collection;
1420
+ var UserCollection = /** @class */ (function (_super) {
1421
+ __extends(UserCollection, _super);
1422
+ function UserCollection() {
1423
+ return _super !== null && _super.apply(this, arguments) || this;
1424
+ }
1425
+ UserCollection.prototype.authenticateStrategy = function () {
1426
+ var _this = this;
1427
+ return function (username, password, cb) { return __awaiter(_this, void 0, void 0, function () {
1428
+ var user;
1429
+ return __generator(this, function (_a) {
1430
+ switch (_a.label) {
1431
+ case 0: return [4 /*yield*/, user_collection_1.Users.findOne({ username: username })];
1432
+ case 1:
1433
+ user = _a.sent();
1434
+ this.authenticate(user, password).then(function (authUser) {
1435
+ if (authUser.data) {
1436
+ cb(null, user, null);
1437
+ }
1438
+ else {
1439
+ cb(null, null, authUser.error);
1440
+ }
1441
+ }, function (err) {
1442
+ cb(err, null, null);
1443
+ });
1444
+ return [2 /*return*/];
1445
+ }
1446
+ });
1447
+ }); };
1448
+ };
1449
+ UserCollection.prototype.authenticate = function (user, password) {
1450
+ var _this = this;
1451
+ return new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
1452
+ var attemptsInterval, calculatedInterval;
1453
+ var _this = this;
1454
+ return __generator(this, function (_a) {
1455
+ switch (_a.label) {
1456
+ case 0:
1457
+ attemptsInterval = Math.pow(100, Math.log(user.attempts + 1));
1458
+ calculatedInterval = attemptsInterval < 300000 ? attemptsInterval : 300000;
1459
+ if (!user.last) return [3 /*break*/, 3];
1460
+ if (!(Date.now() - user.last.getTime() < calculatedInterval)) return [3 /*break*/, 2];
1461
+ user.last = new Date();
1462
+ return [4 /*yield*/, user_collection_1.Users.updateOne({ _id: user._id }, { $set: { last: user.last } })];
1463
+ case 1:
1464
+ _a.sent();
1465
+ resolve({
1466
+ data: null,
1467
+ error: 'Attempt Too Soon'
1468
+ });
1469
+ return [2 /*return*/];
1470
+ case 2: return [3 /*break*/, 4];
1471
+ case 3:
1472
+ user.last = new Date();
1473
+ _a.label = 4;
1474
+ case 4:
1475
+ if (user.attempts >= 5) {
1476
+ resolve({
1477
+ data: null,
1478
+ error: 'Too Many Attempts'
1479
+ });
1480
+ return [2 /*return*/];
1481
+ }
1482
+ if (!user.salt) {
1483
+ resolve({
1484
+ data: null,
1485
+ error: 'No Salt Value Stored'
1486
+ });
1487
+ return [2 /*return*/];
1488
+ }
1489
+ pbkdf2(password, user.salt, {
1490
+ iterations: 25000,
1491
+ keylen: 512,
1492
+ digestAlgorithm: 'sha256'
1493
+ }, function (err, hashBuffer) { return __awaiter(_this, void 0, void 0, function () {
1494
+ return __generator(this, function (_a) {
1495
+ switch (_a.label) {
1496
+ case 0:
1497
+ if (err) {
1498
+ return [2 /*return*/, reject(err)];
1499
+ }
1500
+ if (!scmp(hashBuffer, Buffer.from(user.hash, 'hex'))) return [3 /*break*/, 2];
1501
+ user.last = new Date();
1502
+ user.attempts = 0;
1503
+ return [4 /*yield*/, user_collection_1.Users.updateOne({ _id: user._id }, { $set: { last: user.last, attempts: user.attempts } })];
1504
+ case 1:
1505
+ _a.sent();
1506
+ resolve({
1507
+ data: user,
1508
+ error: ''
1509
+ });
1510
+ return [3 /*break*/, 4];
1511
+ case 2:
1512
+ user.last = new Date();
1513
+ user.attempts = user.attempts + 1;
1514
+ return [4 /*yield*/, user_collection_1.Users.updateOne({ _id: user._id }, { $set: { last: user.last, attempts: user.attempts } })];
1515
+ case 3:
1516
+ _a.sent();
1517
+ if (user.attempts >= 5) {
1518
+ resolve({
1519
+ data: null,
1520
+ error: 'Too Many Attempts'
1521
+ });
1522
+ }
1523
+ else {
1524
+ resolve({
1525
+ data: null,
1526
+ error: 'Invalid Username And Password'
1527
+ });
1528
+ }
1529
+ _a.label = 4;
1530
+ case 4: return [2 /*return*/];
1531
+ }
1532
+ });
1533
+ }); });
1534
+ return [2 /*return*/];
1535
+ }
1536
+ });
1537
+ }); });
1538
+ };
1539
+ UserCollection.prototype.serializeUser = function () {
1540
+ return function (user, cb) {
1541
+ cb(null, user.username);
1542
+ };
1543
+ };
1544
+ UserCollection.prototype.deserializeUser = function () {
1545
+ return function (username, cb) {
1546
+ user_collection_1.Users.findOne({ username: username }).then(function (res) {
1547
+ cb(null, res);
1548
+ }, function (err) {
1549
+ cb(err, null);
1550
+ });
1551
+ };
1552
+ };
1553
+ UserCollection.prototype.setPassword = function (user, password) {
1554
+ var _this = this;
1555
+ return new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
1556
+ var saltBuffer, salt, hashRaw, hash;
1557
+ return __generator(this, function (_a) {
1558
+ switch (_a.label) {
1559
+ case 0:
1560
+ if (!!user) return [3 /*break*/, 1];
1561
+ reject('No User');
1562
+ return [3 /*break*/, 5];
1563
+ case 1:
1564
+ if (!!password) return [3 /*break*/, 2];
1565
+ reject('No Password');
1566
+ return [3 /*break*/, 5];
1567
+ case 2: return [4 /*yield*/, randomBytes(32)];
1568
+ case 3:
1569
+ saltBuffer = _a.sent();
1570
+ salt = saltBuffer.toString('hex');
1571
+ return [4 /*yield*/, pbkdf2Promisified(password, salt, {
1572
+ iterations: 25000,
1573
+ keylen: 512,
1574
+ digestAlgorithm: 'sha256'
1575
+ })];
1576
+ case 4:
1577
+ hashRaw = _a.sent();
1578
+ hash = Buffer.from(hashRaw, 'binary').toString('hex');
1579
+ user_collection_1.Users.updateOne({ _id: user._id }, { $set: { hash: hash, salt: salt, services: {} } }).then(function (res) { return resolve(res); }, function (rej) { return reject(rej); });
1580
+ _a.label = 5;
1581
+ case 5: return [2 /*return*/];
1582
+ }
1583
+ });
1584
+ }); });
1585
+ };
1586
+ ;
1587
+ UserCollection.prototype.changePassword = function (user, oldPassword, newPassword) {
1588
+ var _this = this;
1589
+ return new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
1590
+ var authUser;
1591
+ return __generator(this, function (_a) {
1592
+ switch (_a.label) {
1593
+ case 0:
1594
+ if (!!user) return [3 /*break*/, 1];
1595
+ reject('Missing User');
1596
+ return [3 /*break*/, 4];
1597
+ case 1:
1598
+ if (!(!oldPassword || !newPassword)) return [3 /*break*/, 2];
1599
+ reject('Missing Password');
1600
+ return [3 /*break*/, 4];
1601
+ case 2: return [4 /*yield*/, this.authenticate(user, oldPassword)];
1602
+ case 3:
1603
+ authUser = _a.sent();
1604
+ if (!authUser['data']) {
1605
+ reject(authUser['error']);
1606
+ }
1607
+ else {
1608
+ this.setPassword(user, newPassword).then(function (res) { return resolve(res); }, function (rej) { return reject(rej); });
1609
+ }
1610
+ _a.label = 4;
1611
+ case 4: return [2 /*return*/];
1612
+ }
1613
+ });
1614
+ }); });
1615
+ };
1616
+ UserCollection.prototype.register = function (user, password) {
1617
+ var _this = this;
1618
+ return new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
1619
+ var dbUser;
1620
+ return __generator(this, function (_a) {
1621
+ switch (_a.label) {
1622
+ case 0:
1623
+ if (!!user.username) return [3 /*break*/, 1];
1624
+ reject('Missing Username');
1625
+ return [3 /*break*/, 5];
1626
+ case 1: return [4 /*yield*/, user_collection_1.Users.findOne({ username: user.username })];
1627
+ case 2:
1628
+ dbUser = _a.sent();
1629
+ if (!dbUser) return [3 /*break*/, 3];
1630
+ reject('Username Exists');
1631
+ return [3 /*break*/, 5];
1632
+ case 3: return [4 /*yield*/, user_collection_1.Users.findOne({ email: user.email })];
1633
+ case 4:
1634
+ dbUser = _a.sent();
1635
+ if (dbUser) {
1636
+ reject('Email Exists');
1637
+ }
1638
+ else {
1639
+ user.setPassword(password);
1640
+ resolve(user);
1641
+ }
1642
+ _a.label = 5;
1643
+ case 5: return [2 /*return*/];
1644
+ }
1645
+ });
1646
+ }); });
1647
+ };
1648
+ UserCollection.prototype.resetAttempts = function (user) {
1649
+ return user_collection_1.Users.updateOne({ _id: user._id }, { $set: { attempts: 0 } });
1650
+ };
1651
+ return UserCollection;
1652
+ }(Collection));
1653
+ exports.UserCollection = UserCollection;
1654
+ function objectIdHexString() {
1655
+ var objectId = new mongodb_1.ObjectId();
1656
+ return objectId.toHexString();
1657
+ }
1658
+ exports.objectIdHexString = objectIdHexString;
1659
+ function pbkdf2(password, salt, options, callback) {
1660
+ crypto.pbkdf2(password, salt, options.iterations, options.keylen, options.digestAlgorithm, callback);
1661
+ }
1662
+ ;
1663
+ function pbkdf2Promisified(password, salt, options) {
1664
+ return new Promise(function (resolve, reject) { return pbkdf2(password, salt, options, function (err, hashRaw) { return (err ? reject(err) : resolve(hashRaw)); }); });
1665
+ }
1666
+ function randomBytes(saltlen) {
1667
+ return new Promise(function (resolve, reject) { return crypto.randomBytes(saltlen, function (err, saltBuffer) { return (err ? reject(err) : resolve(saltBuffer)); }); });
1668
+ }
1669
+ function objectContainsPropertyDeep(obj, prop) {
1670
+ var keys = Object.keys(obj);
1671
+ if (keys.some(function (a) { return a === prop; })) {
1672
+ return true;
1673
+ }
1674
+ for (var i = 0; i < keys.length; i++) {
1675
+ var key = keys[i];
1676
+ if (obj[key] && typeof obj[key] === 'object' && objectContainsPropertyDeep(obj[key], prop)) {
1677
+ return true;
1678
+ }
1679
+ }
1680
+ return false;
1681
+ }
1682
+
2
1683
  //# sourceMappingURL=mongo.manager.js.map